在C中encryption一个纯文本文件

我目前正在用C写一个从configuration文件中读取的linux应用程序。 这个configuration文件包含一些我想encryption的数据,所以它不是纯文本。 我花了几个小时研究这个,并没有find一个可行的解决scheme。 由于应用程序将需要从configuration中读取,我将需要能够encryption并在运行中解密。 至于研究,我真的很喜欢openSSLencryption库。 我知道从命令行你可以做到:

openssl enc -aes-256-cbc -salt -in file.txt -out file.enc

如果任何人都可以提供一个如何在C中做到这一点的例子,将不胜感激。

你应该看看O'Reilly-Book 。 有几个关于如何加密事物的例子。 不幸的是,最多的是网络加密。

我在书中找到了一个例子,但没有对它进行测试:

#include <openssl/evp.h> int main(int argc, char *argv[]) { EVP_CIPHER_CTX ctx; char key[EVP_MAX_KEY_LENGTH]; char iv[EVP_MAX_IV_LENGTH]; char *ct, *out; char final[EVP_MAX_BLOCK_LENGTH]; char str[] = "123456789abcdef"; int i; if (!seed_prng()) { printf("Fatal Error! Unable to seed the PRNG!\n"); abort(); } select_random_key(key, EVP_MAX_KEY_LENGTH); select_random_iv(iv, EVP_MAX_IV_LENGTH); EVP_EncryptInit(&ctx, EVP_bf_cbc(), key, iv); ct = encrypt_example(&ctx, str, strlen(str), &i); printf("Ciphertext is %d bytes.\n", i); EVP_DecryptInit(&ctx, EVP_bf_cbc(), key, iv); out = decrypt_example(&ctx, ct, 8); printf("Decrypted: >>%s<<\n", out); out = decrypt_example(&ctx, ct + 8, 8); printf("Decrypted: >>%s<<\n", out); if (!EVP_DecryptFinal(&ctx, final, &i)) { printf("Padding incorrect.\n"); abort(); } final[i] = 0; printf("Decrypted: >>%s<<\n", final); } char *encrypt_example(EVP_CIPHER_CTX *ctx, char *data, int inl, int *rb) { char *ret; int i, tmp, ol; ol = 0; ret = (char *)malloc(inl + EVP_CIPHER_CTX_block_size(ctx)); for (i = 0; i < inl / 100; i++) { EVP_EncryptUpdate(ctx, &ret[ol], &tmp, &data[ol], 100); ol += tmp; } if (inl % 100) { EVP_EncryptUpdate(ctx, &ret[ol], &tmp, &data[ol], inl%100); ol += tmp; } EVP_EncryptFinal(ctx, &ret[ol], &tmp); *rb = ol + tmp; return ret; } char *decrypt_example(EVP_CIPHER_CTX *ctx, char *ct, int inl) { /* We're going to null-terminate the plaintext under the assumption it's * non-null terminated ASCII text. The null can be ignored otherwise. */ char *pt = (char *)malloc(inl + EVP_CIPHER_CTX_block_size(ctx) + 1); int ol; EVP_DecryptUpdate(ctx, pt, &ol, ct, inl); if (!ol) /* there's no block to decrypt */ { free(pt); return NULL; } pt[ol] = 0; return pt; } 

希望这会帮助你。

检查这个答案,并检查这篇文章 。

您可以使用EVP_bf_cbc()替换EVP_bf_cbc() EVP_aes_128_cbc() EVP_aes_192_cbc() or EVP_aes_256_cbc()具体取决于您需要的内容。

您需要SSL开发包。 (Ubuntu中的libssl-dev)。 取决于你如何实现它,你还需要libcrypto-dev。

我不是一个庞大的O'Reilly粉丝,但是我发现这本书第一次启动这种类型的东西时非常有帮助。

为什么不自己做? 从dev / random(您的密钥)中读取足够的字节,并用它对XOR配置文件进行异或。 要解密,用相同的密钥再次XOR。 这很简单,快速和安全。 没有复杂的库需要。