AES128 GCM C代码
时间: 2024-12-26 10:14:04 浏览: 15
AES128-GCM是一种高级加密标准(Advanced Encryption Standard)与 Galois/Counter Mode (GCM) 加密模式的组合,它提供了一种既安全又高效的对称加密方案。GCM不仅能保护数据,还能同时实现认证功能。
以下是一个简单的C语言示例,展示如何使用OpenSSL库实现AES-128-GCM加解密:
```c
#include <openssl/aes.h>
#include <openssl/gcm.h>
// AES key and IV lengths in bytes
#define KEY_LEN 16
#define IV_LEN 12
void aes_gcm_encrypt(const unsigned char* key, const unsigned char* iv,
const unsigned char* plaintext, size_t pt_len,
unsigned char* ciphertext, size_t ct_len,
unsigned char* tag) {
AES_GCM_CTX gcm;
int ret;
// Initialize the GCM context with a key
if ((ret = AES_GCM_init(&gcm, key, KEY_LEN)) != 0) {
printf("AES-GCM initialization failed: %d\n", ret);
return;
}
// Set the initial counter value
gcm_ctr(&gcm, iv, IV_LEN);
// Encrypt the data
if ((ret = AES_GCM_encrypt(&gcm, ciphertext, &ct_len, plaintext, pt_len)) != 1) {
printf("AES-GCM encryption failed: %d\n", ret);
AES_GCM_cleanup(&gcm);
return;
}
// Generate and store the authentication tag
if ((ret = AES_GCM_final(&gcm, tag, NULL)) != 1) {
printf("AES-GCM finalization failed: %d\n", ret);
AES_GCM_cleanup(&gcm);
return;
}
}
void aes_gcm_decrypt(const unsigned char* key, const unsigned char* iv,
const unsigned char* ciphertext, size_t ct_len,
const unsigned char* tag, size_t tag_len,
unsigned char* plaintext) {
AES_GCM_CTX gcm;
int ret;
// Initialize the GCM context with a key
if ((ret = AES_GCM_init(&gcm, key, KEY_LEN)) != 0) {
printf("AES-GCM initialization failed: %d\n", ret);
return;
}
// Set the initial counter value from the ciphertext
if ((ret = AES_GCM_processAAD(&gcm, ciphertext, ct_len - AES_GCM_TAG_LEN)) != 1) {
printf("AES-GCM AAD processing failed: %d\n", ret);
AES_GCM_cleanup(&gcm);
return;
}
// Verify and decrypt the data
if ((ret = AES_GCM_verify_tag(&gcm, tag, tag_len)) == 0) {
if ((ret = AES_GCM_decrypt(&gcm, plaintext, &plaintext[ct_len], ciphertext + AES_GCM_TAG_LEN, ct_len - AES_GCM_TAG_LEN)) != 1) {
printf("AES-GCM decryption failed: %d\n", ret);
} else {
printf("Decryption successful.\n");
}
} else {
printf("AES-GCM tag verification failed.\n");
}
AES_GCM_cleanup(&gcm);
}
阅读全文