这是加密和解密消息的基本代码:
#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 的倍数。
多次调用加密,每次迭代加密 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;
}
在最后一个 block 中编码一个已知字节 (\0
) 不太舒服。不同的长度指示可能是谨慎的。
关于c - 使用 Blowfish 加密和解密消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20133502/