这是对文件test.txt
到test.enc
进行加密的代码.
密钥对key.pem
和key.pub
是使用openssl
:
openssl genrsa -out key.pem
openssl rsa -in key.pem -out key.pub -pubout
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <dirent.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#define BUFFER_SIZE 1024
static int evp_aes_encrypt(char *in_path, char *out_path, EVP_PKEY *pkey)
{
FILE *in_file = fopen(in_path, "rb");
if (!in_file)
return -1;
FILE *out_file = fopen(out_path, "wb");
if (!out_file)
{
fclose(in_file);
return -1;
}
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx)
{
fclose(in_file);
fclose(out_file);
return -1;
}
int len;
unsigned char iv[EVP_MAX_IV_LENGTH];
int i;
unsigned char* ek = NULL;
if (EVP_SealInit(ctx, EVP_aes_256_cbc(), &ek, &len, iv, &pkey, 1) != 1)
{
printf("1\n");
EVP_CIPHER_CTX_free(ctx);
fclose(in_file);
fclose(out_file);
return -1;
}
unsigned char in_buffer[BUFFER_SIZE];
unsigned char out_buffer[BUFFER_SIZE + EVP_MAX_IV_LENGTH];
int bytes_read, bytes_written;
while ((bytes_read = fread(in_buffer, 1, BUFFER_SIZE, in_file)) > 0)
{
if (EVP_SealUpdate(ctx, out_buffer, &bytes_written, in_buffer, bytes_read) != 1) {
EVP_CIPHER_CTX_free(ctx);
fclose(in_file);
fclose(out_file);
return -1;
}
fwrite(out_buffer, 1, bytes_written, out_file);
}
if (EVP_SealFinal(ctx, out_buffer, &bytes_written) != 1) {
EVP_CIPHER_CTX_free(ctx);
fclose(in_file);
fclose(out_file);
return -1;
}
fwrite(out_buffer, 1, bytes_written, out_file);
EVP_CIPHER_CTX_free(ctx);
fclose(in_file);
fclose(out_file);
return 0;
}
int main(void)
{
FILE *pub = fopen("key.pub", "rb");
EVP_PKEY *pkey = PEM_read_PUBKEY(pub, NULL, NULL, NULL);
evp_aes_encrypt("test.txt", "test.enc", pkey);
return 0;
}
然后使用openssl
命令对加密的文件进行解密:
openssl rsautl -in test.enc -out test.dec -inkey key.pem -decrypt
则会出现此错误:
RSA operation error
407D290301000000:error:0200009F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error:crypto/rsa/rsa_pk1.c:269:
407D290301000000:error:02000072:rsa routines:rsa_ossl_private_decrypt:padding check failed:crypto/rsa/rsa_ossl.c:499:
填充物似乎有问题,但我不知道如何修复它. 先谢谢你.