#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <stdio.h>
#include <string.h>
void handleErrors(void) {
ERR_print_errors_fp(stderr);
abort();
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext) {
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
handleErrors();
if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
int main(void) {
unsigned char *key = (unsigned char *)"01234567890123456789012345678901";
unsigned char *iv = (unsigned char *)"0123456789012345";
unsigned char *plaintext =
(unsigned char *)"The quick brown fox jumps over the lazy dog";
unsigned char ciphertext[128];
int ciphertext_len = encrypt(plaintext, strlen((char *)plaintext), key, iv,
ciphertext);
printf("Ciphertext is:n");
BIO_dump_fp(stdout, (const char *)ciphertext, ciphertext_len);
return 0;
1.3 应用场景
对称加密算法适用于需要高效加密和解密的场景,如文件加密、数据库加密、实时通信中的数据加密等。它可以确保数据在传输和存储过程中不被窃取和篡改。
二、使用非对称加密算法
非对称加密算法使用一对密钥进行加密和解密,其中公钥用于加密,私钥用于解密。常见的非对称加密算法有RSA、DSA等。
2.1 非对称加密算法的原理
非对称加密算法的核心思想是使用一对密钥,其中公钥公开,任何人都可以使用它来加密数据,而私钥则需要保密,仅拥有私钥的人才能解密数据。这种方式的优点是密钥管理相对简单,因为不需要共享私钥。其缺点是加密和解密速度较慢,适合加密少量数据。
2.2 使用OpenSSL实现RSA加密
以下是一个使用OpenSSL实现RSA加密的示例代码:
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <stdio.h>
#include <string.h>
void handleErrors(void) {
ERR_print_errors_fp(stderr);
abort();
int main(void) {
int ret = 0;
RSA *rsa = NULL;
BIGNUM *bne = NULL;
BIO *bp_public = NULL, *bp_private = NULL;
unsigned char *plaintext = (unsigned char *)"The quick brown fox jumps over the lazy dog";
unsigned char ciphertext[256];
unsigned char decryptedtext[256];
int decryptedtext_len, ciphertext_len;
int bits = 2048;
unsigned long e = RSA_F4;
bne = BN_new();
ret = BN_set_word(bne, e);
if (ret != 1) handleErrors();
rsa = RSA_new();
ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
if (ret != 1) handleErrors();
bp_public = BIO_new_file("public.pem", "w+");
ret = PEM_write_bio_RSAPublicKey(bp_public, rsa);
if (ret != 1) handleErrors();
bp_private = BIO_new_file("private.pem", "w+");
ret = PEM_write_bio_RSAPrivateKey(bp_private, rsa, NULL, NULL, 0, NULL, NULL);
if (ret != 1) handleErrors();
ciphertext_len = RSA_public_encrypt(strlen((char *)plaintext), plaintext, ciphertext, rsa, RSA_PKCS1_OAEP_PADDING);