A. AES-128算法c++
时间: 2024-05-16 10:17:25 浏览: 16
以下是使用openssl库实现AES-128算法的C++代码:
```c++
#include <openssl/aes.h>
#include <cstring>
#include <iostream>
using namespace std;
void encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) {
AES_KEY aes_key;
AES_set_encrypt_key(key, 128, &aes_key);
AES_cbc_encrypt(plaintext, ciphertext, plaintext_len, &aes_key, iv, AES_ENCRYPT);
}
void decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext) {
AES_KEY aes_key;
AES_set_decrypt_key(key, 128, &aes_key);
AES_cbc_encrypt(ciphertext, plaintext, ciphertext_len, &aes_key, iv, AES_DECRYPT);
}
int main() {
// 128-bit key
unsigned char key[] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c};
// 128-bit initialization vector
unsigned char iv[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
// plaintext
unsigned char plaintext[] = "Hello, world!";
int plaintext_len = strlen(reinterpret_cast<const char *>(plaintext));
// ciphertext buffer
unsigned char ciphertext[plaintext_len];
// encrypt
encrypt(plaintext, plaintext_len, key, iv, ciphertext);
// print ciphertext
cout << "Ciphertext: ";
for (int i = 0; i < plaintext_len; i++) {
printf("%02x", ciphertext[i]);
}
cout << endl;
// plaintext buffer
unsigned char decrypted_plaintext[plaintext_len];
// decrypt
decrypt(ciphertext, plaintext_len, key, iv, decrypted_plaintext);
// print plaintext
cout << "Plaintext: " << decrypted_plaintext << endl;
return 0;
}
```
需要注意的是,此代码依赖于openssl库,需要在编译时链接该库。在Linux环境下,可以使用以下命令编译:
```bash
g++ filename.cpp -lcrypto
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)