以下是加密和解密消息的基本代码:

#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;

}

我的问题是我得到的结果。它总是由8个字符组成,不再是了。
你能帮我加密和解密完整的信息吗?
谢谢您!

最佳答案

正如@WhozCraig所说,一次做8字节的事情。
要加密的数据应视为字节数组,而不是C字符串。
因此,考虑用\0加密的字符串,并用随机数据填充,以形成一个8的倍数的字节数组。
多次调用encrypt,每次迭代加密8个字节。
要解密,请调用相同迭代次数的解密。注意,结果缓冲区的大小可能需要达到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;
}

在最后一个块中编码一个已知字节(\0)不太合适。不同长度的指示可能比较谨慎。

10-07 19:52
查看更多