OpenSSL是一个强大的加密库,它实现了许多加密算法,包括对称加密、非对称加密和哈希算法。在Linux系统中,OpenSSL被广泛用于加密和解密数据。
以下是一个简单的OpenSSL AES加密和解密的示例:
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <stdio.h>
#include <string.h>
void encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext) {
AES_KEY enc_key;
AES_set_encrypt_key(key, 128, &enc_key);
AES_cbc_encrypt(plaintext, ciphertext, plaintext_len, &enc_key, iv, AES_ENCRYPT);
}
void decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
unsigned char *iv, unsigned char *plaintext) {
AES_KEY dec_key;
AES_set_decrypt_key(key, 128, &dec_key);
AES_cbc_encrypt(ciphertext, plaintext, ciphertext_len, &dec_key, iv, AES_DECRYPT);
}
int main() {
unsigned char key[16] = "0123456789abcdef"; // 128-bit key
unsigned char iv[AES_BLOCK_SIZE] = {0}; // Initialization vector
unsigned char plaintext[] = "Hello, World!";
int plaintext_len = strlen((char *)plaintext);
unsigned char ciphertext[128];
unsigned char decryptedtext[128];
encrypt(plaintext, plaintext_len, key, iv, ciphertext);
decrypt(ciphertext, sizeof(ciphertext), key, iv, decryptedtext);
printf("Decrypted text is: %s\n", decryptedtext);
return 0;
}
请注意,这只是一个简单的示例,实际应用中需要考虑更多的安全性和错误处理措施。