Blowfish C++没有正确加密/解密..为什么..?

tom*_*med 0 c++ encryption blowfish

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

(从OP的原始版本复制到http://pastebin.com/AaWSF5pX)

#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;
}
Run Code Online (Sandbox Code Playgroud)

输入:"Hello World"

输出:"你好wo4 \Z "

Gar*_*han 6

Blowfish在64位块上运行:即8字节的倍数.BF_ecb_*处理单个这样的块.这是你的字符串的前8个字符.其余部分被BF_ecb_*忽略.如果你想加密更长的东西,如果你真的很高兴使用ECB模式,或者使用类似BF_ofb_*的东西,那么在循环中将BF_ecb_*一个接一个地应用于一个块.