理想情况下,您可以使用现有工具,例如ccrypt
,但这里是:
#include <openssl/aes.h>
/* ... */
{
int bytes_read, bytes_written;
unsigned char indata[AES_BLOCK_SIZE];
unsigned char outdata[AES_BLOCK_SIZE];
/* ckey and ivec are the two 128-bits keys necesary to
en- and recrypt your data. Note that ckey can be
192 or 256 bits as well */
unsigned char ckey[] = "thiskeyisverybad";
unsigned char ivec[] = "dontusethisinput";
/* data structure that contains the key itself */
AES_KEY key;
/* set the encryption key */
AES_set_encrypt_key(ckey, 128, &key);
/* set where on the 128 bit encrypted block to begin encryption*/
int num = 0;
while (1) {
bytes_read = fread(indata, 1, AES_BLOCK_SIZE, ifp);
AES_cfb128_encrypt(indata, outdata, bytes_read, &key, ivec, &num,
AES_ENCRYPT);
bytes_written = fwrite(outdata, 1, bytes_read, ofp);
if (bytes_read < AES_BLOCK_SIZE)
break;
}
}
解密是通过调用完成的AES_cfb128_encrypt
with AES_DECRYPT
作为最后一个参数。请注意,此代码仅经过最基本的测试,并且您确实应该为 ckey 和 ivec 使用正确的 8 位随机数据。
EDIT: 它似乎AES_cfb128_encrypt
接受任意长度的数据,因此您不需要按块进行加密AES_BLOCK_SIZE
(16) 字节。