本文介绍了Blowfish C ++没有正确加密/解密..为什么..?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个测试代码使用Blowfish(openssl / blowfish.h)加密,然后解密一个字符串。但是当它再次出来,它没有被正确解密。任何人都可以告诉我为什么要?

I have this piece of test code that uses Blowfish (openssl/blowfish.h) to encrypt, then decrypt a string. But when it comes out again, it hasn't been decrypted properly. Can anyone tell me why please?

(从)

#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

Input: "Hello World"

输出:hellowo4 \Z

Output: "hello wo4�\Z��"

推荐答案

Blowfish在64位块上运行:即8个字节的倍数。 BF_ecb_ *处理单个这样的块。这是你的字符串的前8个字符。其余的被BF_ecb_ *忽略。如果你想要加密更长的时间,如果你真的很高兴使用ECB模式,或使用类似BF_ofb _ *的东西,应用BF_ecb_ *一个块接着一个循环。

Blowfish operates on 64-bit blocks: that is, multiples of 8 bytes. BF_ecb_* processes a single such block. That's the first 8 characters of your string. The rest is ignored by BF_ecb_*. If you want to encrypt something longer, apply BF_ecb_* to one block after another in a loop if you're really happy to use the ECB mode, or use something like BF_ofb_*.

这篇关于Blowfish C ++没有正确加密/解密..为什么..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 18:15