Encrypting and decrypting a message with Blowfish

混江龙づ霸主 提交于 2020-01-05 12:26:20

问题


Here is a basic code of encryping and decrypting a message:

#include <stdio.h>
#include <openssl/blowfish.h>
#include <string.h>

//gcc cryptage.c -o cryptage -lcrypto

int main(){

BF_KEY *key = malloc(sizeof(BF_KEY));

unsigned char *crypt_key = "Key of encryption";
const unsigned char *in = "Message to encrypt";
int len = strlen(crypt_key);
unsigned char *out = malloc(sizeof(char)*len);
unsigned char *result = malloc(sizeof(char)*len);


//Defining encryption key
BF_set_key(key, len, crypt_key);

//Encryption
BF_ecb_encrypt(in, out, key, BF_ENCRYPT);

//Décryption
BF_ecb_encrypt(out, result, key, BF_DECRYPT);

fprintf(stdout,"Result: %s\n",result);

return 0;

}

My problem is the result i get. It's always a String of 8 caracters, no more. Can you please help me encrypt and decrypt the full message?

Thank you!


回答1:


As @WhozCraig says, do things 8 bytes at a time.

The data to encrypt should be viewed as a byte array and not a C string.
So consider the string to encrypt with the \0 and padded with random data to form a byte array that is a multiple of 8.
Call encrypt multiple times, encrypting 8 bytes per iteration.

To decrypt, call decryption the same number of iterations. Note that the result buffer may need to be sized up to a multiple of 8.

const unsigned char *in = "Message to encrypt";
size_t InSize = strlen(in) + 1;
int KeyLen = strlen(crypt_key);
size_t OutSize = (InSize + 7) & (~7);
unsigned char *out = malloc(Outsize);
unsigned char *outnext = out;
//Defining encryption key
BF_set_key(key, KeyLen, crypt_key);

//Encryption
while (InSize >= 8) {    
  BF_ecb_encrypt(in, outnext, key, BF_ENCRYPT);
  in += 8;
  outnext += 8;
  InSize -= 8;
}
if (Insize > 0) {  // Cope with non-octal length
  unsigned char buf8[8];
  memcpy(buf8, in, InSize);
  for (i=InSize; i<8; i++) {
    buf8[i] = rand();
  }  
  BF_ecb_encrypt(buf8, outnext, key, BF_ENCRYPT);
}

//Décryption
unsigned char *result = malloc(OutSize);
unsigned char *resultNext = result;
while (OutSize) {
  BF_ecb_encrypt(out, resultNext, key, BF_DECRYPT);
  out += 8;
  resultNext += 8;
  OutSize -= 8;
}

fprintf(stdout,"Result: %s\n",result);
// No need to print the random bytes that were generated.
return 0;
}

Not quite comfortable have a known byte (\0) encoded in the last block. A different length indication may be prudent.



来源:https://stackoverflow.com/questions/20133502/encrypting-and-decrypting-a-message-with-blowfish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!