2016-09-29 88 views
-1

我需要使用OpenSSL庫來獲得Blowfish加密。但有些東西不起作用。
我在做什麼錯?我試圖做這種方式:如何使用OpenSSL將消息加密到Blowfish?

#include <iostream> 
#include <openssl/blowfish.h> 
#include "OpenSSL_Base64.h" 
#include "Base64.h" 

using namespace std; 

int main() 
{ 
    unsigned char ciphertext[BF_BLOCK]; 
    unsigned char plaintext[BF_BLOCK]; 

    // blowfish key 
    const unsigned char *key = (const unsigned char*)"topsecret"; 
    //unsigned char key_data[10] = "topsecret"; 
    BF_KEY bfKey; 
    BF_set_key(&bfKey, 10, key); 

    /* Open SSL's Blowfish ECB encrypt/decrypt function only handles 8 bytes of data */ 
    char a_str[] = "8 Bytes";//{8, ,B,y,t,e,s,\0} 
    char *arr_ptr = &a_str[0]; 

    //unsigned char* data_to_encrypt = (unsigned char*)"8 Bytes"; // 7 + \0 

    BF_ecb_encrypt((unsigned char*)arr_ptr, ciphertext, &bfKey, BF_ENCRYPT); 

    unsigned char* ret = new unsigned char[BF_BLOCK + 1]; 
    strcpy((char*)ret, (char*)ciphertext); 
    ret[BF_BLOCK + 1] = '\0'; 

    char* base_enc = OpenSSL_Base64::Base64Encode((char*)ret, strlen((char*)ret)); 

    cout << base_enc << endl; 

    cin.get(); 

    return 0; 
} 

,但我得到了錯誤的輸出:

fy7maf+FhmbM 

我用它檢查:

http://sladex.org/blowfish.js/

它應該是:fEcC5/EKDVY =

Base64:

http://pastebin.com/wNLZQxQT

+0

此問題已被詢問了很多次... [openssl blowfish encryption example site:stackoverflow.com ](http://www.google.com/search?q=openssl+blowfish+encryption+example+site%3Astackoverflow.com)。'strlen((char *)ciphertext' does not not *** work。另請參閱OpenSSL wiki上的[EVP Symmetric Encryption and Decryption](http://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption),它甚至提供了一個使用它的C++示例 – jww

+0

沒有這麼多,我見過最多的問題,並在github上搜索了兩天,我發現的所有內容都不完整,或者輸出錯誤,所以我從頭開始,我試圖理解 – Vadim

+0

當然,Blowfish不應該用於新作品,AES是當前的選擇。 – zaph

回答

0

的問題是,ret可以包含一個空字節,加密是8位字節開始,而不是基於字符和將包含值fromthe全範圍爲0-255。 strlen將終止於它找到的第一個空字節,其長度小於加密數據的全長。

注意:使用加密時要特別注意提供準確的長度參數和數據,不要依賴填充。 (輸入數據的例外是支持數據填充的加密函數,例如PKCS#7(néePKCS#5)填充。

+0

密鑰長度不正確(如果我手動設置10(長度爲10!),只適用於strlen() BF_set_key(&bfKey ,strlen((char *)key),key); 如果消息是8字節加密錯誤,只有當超過8 = \ 正確的加密+幾個垃圾字符(而不是它不是\ 0) 。我仍然不明白= \ 我明白,我接受你的回答是正確的,我仍然有問題。謝謝你的幫助! – Vadim