2011-03-07 39 views
0

我有一段使用Blowfish(openssl/blowfish.h)加密的测试代码,然后解密一个字符串。但是当它再次出现时,它还没有被正确解密。谁能告诉我为什么请?Blowfish C++没有正确加密/解密..为什么..?

(在http://pastebin.com/AaWSF5pX从OP的原始拷贝)

#include <stdlib.h> 
#include <cstdio> 
#include <string.h> 
#include <iostream> 
using namespace std; 

int main(int argc, char **argv) 
{ 
    // blowfish key 
    const char *key = "h&6^5fVghasV_Fte"; 
    BF_KEY bfKey; 
    BF_set_key(&bfKey, strlen(key), (const unsigned char*)key); 

    // encrypt 
    const unsigned char *inStr = (const unsigned char *)"hello world\0"; 
    unsigned char *outStr = (unsigned char *)malloc(sizeof(unsigned char) * 100); 
    BF_ecb_encrypt(inStr, outStr, &bfKey, BF_ENCRYPT); 

    // decrypt 
    unsigned char buf[100]; 
    BF_ecb_encrypt((const unsigned char*)outStr, buf, &bfKey, BF_DECRYPT); 
    std::cout << "decrypted: " << buf << "\n"; 
    free(outStr); 

    return 0; 
} 

输入: “Hello World” 的

输出: “你好WO4 \ Z”

+1

请包括问题中的代码,而不是把它放在外部网站 – Erik 2011-03-07 22:31:08

回答

6

河豚上运行64位块:即8个字节的倍数。 BF_ecb_ *处理一个这样的块。这是你的字符串的前8个字符。其余的被BF_ecb_ *忽略。如果您想加密更长的内容,如果您真的很乐意使用ECB模式,或者使用BF_ofb_ *之类的方法,请将BF_ecb_ *应用于一个接一个的循环中。

+0

但我似乎是在cbc得到一个段错误:http://pastebin.com/MAYsnShb – tommed 2011-03-07 23:09:55

+0

最有可能你需要填补输出和输入,所以它们是8个字节的倍数。 – 2011-03-07 23:14:18

0

BF_ecb_encrypt手册页:

它加密或解密的前64位中使用的关键钥匙,把结果出来。

阅读文档。

+0

公平点,谢谢 – tommed 2013-11-26 12:03:42