C++ builder 如何使用openssl进行AES加密
时间: 2023-12-13 07:05:42 浏览: 36
以下是使用 OpenSSL 库进行 AES 加密的示例代码:
```c++
#include <openssl/evp.h>
#include <openssl/rand.h>
void aes_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 initialize the context */
ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);
/* Encrypt the plaintext */
EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len);
ciphertext_len = len;
/* Finalize the encryption */
EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);
ciphertext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
}
int main() {
unsigned char plaintext[] = "Hello, world!";
unsigned char key[EVP_MAX_KEY_LENGTH];
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char ciphertext[1024];
/* Generate a random key and IV */
RAND_bytes(key, 32);
RAND_bytes(iv, 16);
/* Encrypt the plaintext */
aes_encrypt(plaintext, strlen((const char *)plaintext), key, iv, ciphertext);
/* Print the ciphertext */
for (int i = 0; i < strlen((const char *)ciphertext); i++) {
printf("%02x", ciphertext[i]);
}
return 0;
}
```
在上述代码中,我们使用了 OpenSSL 库中的 `EVP_CIPHER_CTX` 和 `EVP_Encrypt*` 函数进行 AES 加密。首先,我们要生成一个随机的密钥和 IV,然后使用 `EVP_EncryptInit_ex` 函数来初始化加密上下文。接着,我们使用 `EVP_EncryptUpdate` 函数将明文加密,最后使用 `EVP_EncryptFinal_ex` 函数完成加密。最后,我们将密文输出到控制台。
需要注意的是,上述代码中的密钥和 IV 都是随机生成的,实际应用中需要使用安全的方式生成密钥和 IV,并确保它们的安全性。