加密和解密使用openssl的一个小文件 [英] Encrypting and decrypting a small file using openssl
问题描述
我想用C / C ++其内容的小文本文件,并对其进行加密,使用的是内部键的小程序。然后,我也需要写另一个小程序,可以在内部使用相同的密钥解密加密的文件。
I want to write a small program in C/C++ which reads a small text file, and encrypts it, using a "internal" key. Then I also want to write another small program which can decrypt the encrypted file using internally the same key.
我看着OpenSSL的网站,用Google搜索,但发现不是简单的例子,已经有人试过做这件事情?
I looked at openSSL site and googled but found not simple example, has somebody ever tried to do this thing?
推荐答案
在理想情况下,你可以使用像 ccrypt
现有的工具,但这里有云:
Ideally, you could use an existing tool like ccrypt
, but here goes:
#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
与 AES_DECRYPT
做作为最后一个参数。请注意,这code没有得到任何比最初级的测试多了,而且你真的应该使用正确的8位随机数据ckey和IVEC。
Decryption is done by calling AES_cfb128_encrypt
with AES_DECRYPT
as the last parameter. Note that this code hasn't been given anything more than the most elementary of testing, and that you really should use proper 8-bits random data for ckey and ivec.
修改:看来 AES_cfb128_encrypt
接受任意长度的数据,这样你就不会在 AES_BLOCK_SIZE
(16)个字节。
EDIT: It seems AES_cfb128_encrypt
accepts data of arbitrary length, so you're not required to encrypt in blocks of AES_BLOCK_SIZE
(16) bytes.
这篇关于加密和解密使用openssl的一个小文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!