如何用c语言 写出cyptoJS aes 128 一样的结果
时间: 2024-03-09 15:44:22 浏览: 21
好的,下面是示例代码,使用 OpenSSL 库进行 AES 加密和解密:
加密:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
void aes_encrypt(const unsigned char *plaintext, int plaintext_len,
const unsigned char *key, unsigned char *ciphertext) {
AES_KEY aes_key;
AES_set_encrypt_key(key, 128, &aes_key);
AES_ecb_encrypt(plaintext, ciphertext, &aes_key, AES_ENCRYPT);
}
int main() {
const unsigned char *plaintext = (const unsigned char *)"待加密的明文";
const unsigned char *key = (const unsigned char *)"密钥";
unsigned char ciphertext[AES_BLOCK_SIZE * ((strlen((const char *)plaintext) + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE)];
memset(ciphertext, 0, sizeof(ciphertext));
aes_encrypt(plaintext, strlen((const char *)plaintext), key, ciphertext);
printf("加密结果:");
for (int i = 0; i < sizeof(ciphertext); i++) {
printf("%02x", ciphertext[i]);
}
printf("\n");
return 0;
}
```
解密:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
void aes_decrypt(const unsigned char *ciphertext, int ciphertext_len,
const unsigned char *key, unsigned char *plaintext) {
AES_KEY aes_key;
AES_set_decrypt_key(key, 128, &aes_key);
AES_ecb_encrypt(ciphertext, plaintext, &aes_key, AES_DECRYPT);
}
int main() {
const unsigned char *ciphertext = (const unsigned char *)"待解密的密文";
const unsigned char *key = (const unsigned char *)"密钥";
unsigned char plaintext[AES_BLOCK_SIZE * ((strlen((const char *)ciphertext) + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE)];
memset(plaintext, 0, sizeof(plaintext));
aes_decrypt(ciphertext, strlen((const char *)ciphertext), key, plaintext);
printf("解密结果:%s\n", plaintext);
return 0;
}
```
需要注意的是,以上代码使用的是 ECB 模式和 PKCS7 填充方式,与 CryptoJS 中使用的一致。同时,需要在编译时链接 OpenSSL 库,可以使用以下命令进行编译:
```
gcc aes_encrypt.c -o aes_encrypt -lcrypto
gcc aes_decrypt.c -o aes_decrypt -lcrypto
```
其中,`-lcrypto` 参数表示链接 OpenSSL 库。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)