2016-09-29 90 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