Search code examples
c++encryptionblowfish

Blowfish C++ does not correctly encrypt/decrypt.. why..?


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?

(copied from OP's original at 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;
}

Input: "Hello World"

Output: "hello wo4�\Z��"


Solution

  • 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_*.