能写上一段调用openssl库的代码吗,包括加密,解密
时间: 2023-12-27 12:02:55 浏览: 28
以下是一个使用 OpenSSL 库进行 AES 对称加密和解密的示例代码,使用的是 CBC 模式:
```c
#include <openssl/evp.h>
#include <string.h>
#define AES_BLOCK_SIZE 16
void 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;
/* Create and initialise the context */
if (!(ctx = EVP_CIPHER_CTX_new())) {
/* Handle error */
}
/* Initialise the encryption operation */
if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) {
/* Handle error */
}
/* Provide the message to be encrypted, and obtain the encrypted output */
if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
/* Handle error */
}
ciphertext_len = len;
/* Finalise the encryption */
if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
/* Handle error */
}
ciphertext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
}
void decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
unsigned char *iv, unsigned char *plaintext) {
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
/* Create and initialise the context */
if (!(ctx = EVP_CIPHER_CTX_new())) {
/* Handle error */
}
/* Initialise the decryption operation */
if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) {
/* Handle error */
}
/* Provide the message to be decrypted, and obtain the plaintext output */
if (1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) {
/* Handle error */
}
plaintext_len = len;
/* Finalise the decryption */
if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) {
/* Handle error */
}
plaintext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
}
int main() {
unsigned char *key = (unsigned char *)"01234567890123456789012345678901";
unsigned char *iv = (unsigned char *)"0123456789012345";
unsigned char plaintext[] = "The quick brown fox jumps over the lazy dog";
unsigned char ciphertext[128];
unsigned char decryptedtext[128];
int decryptedtext_len, ciphertext_len;
/* Encrypt the plaintext */
encrypt(plaintext, strlen((char *)plaintext), key, iv, ciphertext);
/* Decrypt the ciphertext */
decrypt(ciphertext, ciphertext_len, key, iv, decryptedtext);
/* Add a NULL terminator. We are expecting printable text */
decryptedtext[decryptedtext_len] = '\0';
printf("Ciphertext is:\n");
BIO_dump_fp(stdout, (const char *)ciphertext, ciphertext_len);
printf("Decrypted text is:\n");
printf("%s\n", decryptedtext);
return 0;
}
```
请注意,这只是一个示例代码,仅用于演示如何使用 OpenSSL 库进行加密和解密。您需要根据自己的需求对代码进行修改。同时,为了确保安全性,请务必注意密钥的生成和存储,以及加密和解密的数据完整性。