AES-GCM

OpenSSL 官方提供的 AES-GCM 加解密示例

下例是基于 openssl-3.0.13 编码
gcc -o aes_gcm aes_gcm.c -I/xxx/openssl/openssl-3.0.13/include -L/xxx/openssl/openssl-3.0.13/lib64 -lssl -lcrypto

#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>

#define AES_KEY_SIZE 256
#define GCM_IV_SIZE  12
#define GCM_TAG_SIZE 16

void handleErrors(void)
{
  fprintf(stderr, "An error occurred\n");
  exit(1);
}

int encrypt_data(const unsigned char *plaintext, int plaintext_len
               , unsigned char *key, unsigned char *iv, int iv_len
               , unsigned char *ciphertext, unsigned char *tag)
{
  EVP_CIPHER_CTX *ctx;
  int             len;
  int             ciphertext_len;

  if (!(ctx = EVP_CIPHER_CTX_new()))
    handleErrors();

  if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
    handleErrors();

  if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv_len, NULL))
    handleErrors();

  if (1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
    handleErrors();

  if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
    handleErrors();
  ciphertext_len = len;

  if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
    handleErrors();
  ciphertext_len += len;

  if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, GCM_TAG_SIZE, tag))
    handleErrors();

  EVP_CIPHER_CTX_free(ctx);

  return ciphertext_len;
}

int decrypt_data(const unsigned char *ciphertext, int ciphertext_len
               , unsigned char *key, unsigned char *iv, int iv_len
               , unsigned char *decryptedtext, unsigned char *tag)
{
  EVP_CIPHER_CTX *ctx;
  int             len;
  int             plaintext_len;

  if (!(ctx = EVP_CIPHER_CTX_new()))
    handleErrors();

  if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
    handleErrors();

  if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, GCM_IV_SIZE, NULL))
    handleErrors();

  if (1 != EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv))
    handleErrors();

#if 0
  if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, GCM_TAG_SIZE, tag))
    handleErrors();
#endif

  if (1 != EVP_DecryptUpdate(ctx, decryptedtext, &len, ciphertext, ciphertext_len))
    handleErrors();
  plaintext_len = len;

  if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, GCM_TAG_SIZE, tag))
    handleErrors();

  if (1 != EVP_DecryptFinal_ex(ctx, decryptedtext + len, &len))
    handleErrors();
  plaintext_len += len;

  EVP_CIPHER_CTX_free(ctx);

  return plaintext_len;
}

int main()
{
  unsigned char *plaintext = "Hello, AES-GCM";
  unsigned char  key[AES_KEY_SIZE/8];
  unsigned char  iv[GCM_IV_SIZE];
  unsigned char  ciphertext[128];
  int            ciphertext_len;
  unsigned char  tag[GCM_TAG_SIZE];
  unsigned char  decryptedtext[128];
  int            decryptedtext_len;
  int            i;

  RAND_bytes(key, sizeof(key));
  RAND_bytes(iv, sizeof(iv));

  ciphertext_len = encrypt_data(plaintext, strlen((char *)plaintext)
                     , key, iv, GCM_IV_SIZE, ciphertext, tag);

  printf("Plaintext: %s\n", plaintext);

  printf("Ciphertext: ");
  for (i = 0; i < ciphertext_len; i++)
    printf("%02X", ciphertext[i]);
  printf("\n");

  decryptedtext_len = decrypt_data(ciphertext, ciphertext_len
                        , key, iv, GCM_IV_SIZE, decryptedtext, tag);

  decryptedtext[decryptedtext_len] = '\0';
  printf("Decrypted text: %s\n", decryptedtext);

  return 0;
}

对于大多数需要认证加密的应用程序,GCM 应该被认为优于 CCM

AES-GCM(Advanced Encryption Standard Galois/Counter Mode)是一种广泛使用的对称加密算法,结合了AES的加密能力和Galois模式提供的认证功能。它不仅提供数据机密性,还确保数据完整性与真实性。AES-GCM在TLS、IPsec、无线通信等领域有广泛应用。 ### 加密流程 AES-GCM的基本操作包括: - **加密(Encryption)**:使用AES对明文进行加密。 - **认证(Authentication)**:通过Galois字段运算生成消息认证码(GMAC),用于验证数据完整性和来源真实性。 其输入参数通常包括: - **明文(Plaintext)** - **密钥(Key)**:支持128位、192位或256位长度 - **初始向量(IV)**:通常是96位,用于初始化计数器模式 - **附加认证数据(Additional Authenticated Data, AAD)**:可选数据,不加密但参与认证 输出包括: - **密文(Ciphertext)** - **认证标签(Authentication Tag)** ### Java实现示例 以下是一个基于Java的AES-GCM实现示例,使用`javax.crypto`包: ```java import javax.crypto.Cipher; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.SecureRandom; public class AESGCMExample { private static final int GCM_TAG_LENGTH = 128; // bits private static final int GCM_IV_LENGTH = 12; // bytes public static byte[] encrypt(byte[] plaintext, byte[] key, byte[] iv, byte[] aad) throws Exception { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv); cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec); if (aad != null) { cipher.updateAAD(aad); } return cipher.doFinal(plaintext); } public static byte[] decrypt(byte[] ciphertext, byte[] key, byte[] iv, byte[] aad) throws Exception { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv); cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec); if (aad != null) { cipher.updateAAD(aad); } return cipher.doFinal(ciphertext); } public static void main(String[] args) throws Exception { String plainText = "Hello, World!"; String keyStr = "1234567890123456"; // 16 bytes for AES-128 String ivStr = "123456789012"; // 12 bytes IV byte[] key = keyStr.getBytes(); byte[] iv = ivStr.getBytes(); byte[] data = plainText.getBytes(); byte[] encryptedData = encrypt(data, key, iv, null); System.out.println("Encrypted: " + new String(encryptedData)); byte[] decryptedData = decrypt(encryptedData, key, iv, null); System.out.println("Decrypted: " + new String(decryptedData)); } } ``` ### 使用场景 AES-GCM适用于需要高性能和安全性的场景,例如: - **网络通信安全**:如TLS 1.2及以上版本中用于保护HTTPS流量[^1] - **数据库加密**:保护存储在数据库中的敏感信息 - **物联网设备通信**:低延迟和高吞吐量需求下的加密传输 ### 安全注意事项 - **IV唯一性**:每次加密必须使用唯一的IV,重复使用可能导致密钥泄露风险 - **认证标签长度**:推荐使用128位认证标签以提高安全性 - **密钥管理**:应采用安全机制存储和分发密钥,防止密钥泄露 AES-GCM作为一种高效且安全的加密方案,在现代信息安全体系中占据重要地位。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值