AES-GCM算法 Java与Python互相加解密

1. AES

AES加密算法全称是Advanced Encryption Standard(高级加密标准),是美国NIST在2001年发布的,旨在代替DES称为广泛使用的标准。AES是一种对称分组密码算法。

2. AES的分组长度和秘钥长度

AES的明文分组长度为128位(16字节),密钥长度可以为128位(16字节)、192位(24字节)、256位(32字节),根据密钥长度的不同,AES分为AES-128、AES-192、AES-256三种。

不同的秘钥长度带来的不同是什么?
AES加密体制也是由多轮加密构成,除了结尾的一轮,其他轮都是由四个步骤组成——字节代替、行移位、列混淆、轮密钥加。而最后一轮仅包括字节代替、行移位、轮密钥加这三步。AES迭代的轮数与密钥的长度相关,16字节的密钥对应着迭代10轮,24字节的密钥对应着迭代12轮,32字节的密钥对应着迭代14轮。在开始所有轮迭代之前,需要进行一次初始变换——一次轮密钥加,这一步往往被称为第0轮。

3.AES加密模式

模式优点缺点用途
ECB(Electronic Mode 电子密码本模式)简单、可并行计算、误差不传递不能隐藏明文模式(比如图像加密轮廓仍在)、主动攻击(改明文,后续内容不影响,只要误差不传递该缺点就存在)需要并行加密的应用
CFB(CipherFeedback,密码反馈)不容易主动攻击(误差传递)、适合长报文,是SSL、IPSec标准无法并行、误差传递长报文传输,SSL和IPSec
OFB (OutputFeedback,输出反馈)不容易主动攻击(误差传递),分组转变为流模式,可加密小于分组数据无法并行、误差传递
CTR(Counter,计数器模式)并行、一次一密、不传递误差主动攻击(改明文,后续内容不影响,只要误差不传递该缺点就存在)

4.AES-GCM

GCM即Galois/Counter Mode,指的是加密采用Counter模式,并且带有GMAC消息认证码。
这个Counter模式,粗略概括来说,就是对一个逐次累加的计数器进行加密,然后用加密后的比特序列与明文分组进行异或得到密文。GMAC消息认证码的作用就是为了验证数据的完整性。

由于本文不是密码学相关,只是单纯使用这个算法,故不做深入探究如何加密的过程。接下来,演示Java中如何使用AES-GCM算法。

5. JAVA应用

5.1 生成密钥

 public void generateSecret() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(256);

        SecretKey key = keyGenerator.generateKey();
        byte[] bytes = key.getEncoded();
        System.out.println(Base64.getEncoder().encodeToString(bytes));
    }

这里生成256位长度的密钥,然后将密钥使用base64编码成字符串。

5.2 加密

public String encrypt(String plaintext, String secretString) throws Exception {
        byte[] IV = new byte[12];
        SecureRandom random = new SecureRandom();
        random.nextBytes(IV);

        byte[] secretKey = Base64.getDecoder().decode(secretString);
        SecretKeySpec keySpec = new SecretKeySpec(secretKey, "AES");
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, IV);

        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);

        byte[] cipherText = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        ByteBuffer byteBuffer = ByteBuffer.allocate(IV.length + cipherText.length);
        byteBuffer.put(IV);
        byteBuffer.put(cipherText);
        return Base64.getEncoder().encodeToString(byteBuffer.array());
    }

这里使用了随机向量IV,IV的作用是保证即使是相同的明文,使用相同的密钥进行加密,也会使每次加密得到的密文结果不相同。
这里要做几点说明:

96-bit IV values can be processed more efficiently, so that [ed: this] length is recommended for situations in which efficiency is critical.

    1. 消息验证器MAC在哪里?MAC在加密好的密文之中,在密文的最后16个字节里。由于JAVA做了封装,很多人会忽略这一点,以为dofinal得出的就是密文,这个ciphertext当中包含了MAC。

5.3 解密

public String decrypt(String ciphertext, String secretString) throws Exception {
        byte[] encrypted = Base64.getDecoder().decode(ciphertext);
        byte[] IV = Arrays.copyOfRange(encrypted, 0, 12);
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, IV);
        byte[] secretKey = Base64.getDecoder().decode(secretString);
        SecretKeySpec keySpec = new SecretKeySpec(secretKey, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);

        byte[] plaintext = cipher.doFinal(Arrays.copyOfRange(encrypted, 12, encrypted.length));
        return new String(plaintext);
    }

由于我把IV也保存在了密文当中,因此要先把IV的内容取出来,拿剩下的内容进行解密。

6. Python应用

JAVA有的,我大Python也要有!(更主要的原因是,有不同语言加解密的场景)
Python3这里使用了一个库pycryptodome,没有的需要安装一下:

pip3 install pycryptodome

Python程序如下:

from Crypto.Cipher import AES
import base64
import os
import sys

encoding_utf8 = 'utf-8'

def aes_gcm_encrypt(plaintext, secret):
    secret_key = base64.b64decode(secret)
    iv = os.urandom(12)
    aes_cipher = AES.new(secret_key, AES.MODE_GCM, iv)
    ciphertext, auth_tag = aes_cipher.encrypt_and_digest(plaintext.encode(encoding_utf8))
    result = iv + ciphertext + auth_tag
    return base64.b64encode(result).decode(encoding_utf8)


def aes_gcm_decrypt(encrypted, secret_key):
    res_bytes = base64.b64decode(encrypted.encode(encoding_utf8))
    nonce = res_bytes[:12]
    ciphertext = res_bytes[12:-16]
    auth_tag = res_bytes[-16:]
    aes_cipher = AES.new(base64.b64decode(secret_key), AES.MODE_GCM, nonce)
    return aes_cipher.decrypt_and_verify(ciphertext, auth_tag).decode(encoding_utf8)


def aes_gcm_generate_secret():
    random_bytes = os.urandom(32)
    return base64.b64encode(random_bytes).decode(encoding_utf8)

7. 测试一下

public static void main(String[] args) throws Exception {
        AESGCM util = new AESGCM();
        String ciphertext = util.encrypt("hello world", "lLbIsDo9GmxgKbjzsjzDWS7EiLOiXKAdhaaQIhCpKao=");
        System.out.println(util.decrypt(ciphertext, "lLbIsDo9GmxgKbjzsjzDWS7EiLOiXKAdhaaQIhCpKao="));
    }

这里使用Python生成里密钥,并使用JAVA密钥加密解密。可以得到准确的密文。Python和JAVA可以互相使用密钥进行加解密。

  • 6
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
iOS中可以使用OpenSSL库来实现AES-GCMAES-ECB加密解密操作。下面给出一个示例代码: ```objc #include <openssl/evp.h> #include <openssl/rand.h> // AES-GCM加密解密 void aes_gcm_encrypt_decrypt() { // 定义key和iv unsigned char key[16] = {0x0}; unsigned char iv[12] = {0x0}; // 随机生成nonce unsigned char nonce[12]; RAND_bytes(nonce, sizeof(nonce)); // 待加密的明文 unsigned char plaintext[] = "Hello, World!"; int plaintext_len = strlen(plaintext); // 分配内存 unsigned char *ciphertext = malloc(plaintext_len + EVP_GCM_TLS_EXPLICIT_IV_LEN); unsigned char *decryptedtext = malloc(plaintext_len); // 创建并初始化EVP_CIPHER_CTX EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL); EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, sizeof(nonce), NULL); EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv); EVP_EncryptUpdate(ctx, NULL, &plaintext_len, nonce, sizeof(nonce)); // 加密 int len; EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len); int ciphertext_len = len; EVP_EncryptFinal_ex(ctx, ciphertext + len, &len); ciphertext_len += len; EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, ciphertext + ciphertext_len); ciphertext_len += 16; // 解密 EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL); EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, sizeof(nonce), NULL); EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv); EVP_DecryptUpdate(ctx, NULL, &plaintext_len, nonce, sizeof(nonce)); EVP_DecryptUpdate(ctx, decryptedtext, &len, ciphertext, ciphertext_len - 16); int decryptedtext_len = len; EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, ciphertext + ciphertext_len - 16); EVP_DecryptFinal_ex(ctx, decryptedtext + len, &len); decryptedtext_len += len; // 打印结果 printf("AES-GCM Ciphertext is:\n"); for (int i = 0; i < ciphertext_len; i++) { printf("%02x", ciphertext[i]); } printf("\n"); printf("AES-GCM Decryptedtext is:\n"); for (int i = 0; i < decryptedtext_len; i++) { printf("%c", decryptedtext[i]); } printf("\n"); // 释放内存 free(ciphertext); free(decryptedtext); EVP_CIPHER_CTX_free(ctx); } // AES-ECB加密解密 void aes_ecb_encrypt_decrypt() { // 定义key和iv unsigned char key[16] = {0x0}; unsigned char iv[16] = {0x0}; // 待加密的明文 unsigned char plaintext[] = "Hello, World!"; int plaintext_len = strlen(plaintext); // 分配内存 unsigned char *ciphertext = malloc(plaintext_len + 16); unsigned char *decryptedtext = malloc(plaintext_len); // 创建并初始化EVP_CIPHER_CTX EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, iv); // 加密 int len; EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len); int ciphertext_len = len; EVP_EncryptFinal_ex(ctx, ciphertext + len, &len); ciphertext_len += len; // 解密 EVP_DecryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, iv); EVP_DecryptUpdate(ctx, decryptedtext, &len, ciphertext, ciphertext_len); int decryptedtext_len = len; EVP_DecryptFinal_ex(ctx, decryptedtext + len, &len); decryptedtext_len += len; // 打印结果 printf("AES-ECB Ciphertext is:\n"); for (int i = 0; i < ciphertext_len; i++) { printf("%02x", ciphertext[i]); } printf("\n"); printf("AES-ECB Decryptedtext is:\n"); for (int i = 0; i < decryptedtext_len; i++) { printf("%c", decryptedtext[i]); } printf("\n"); // 释放内存 free(ciphertext); free(decryptedtext); EVP_CIPHER_CTX_free(ctx); } ``` 使用示例: ```objc aes_gcm_encrypt_decrypt(); aes_ecb_encrypt_decrypt(); ``` 输出结果: ``` AES-GCM Ciphertext is: 9a0c9e714a7f48c8bdf7ce70d2c5b6b801efb4c6a2f8d0c0e1c9e38d8d0e AES-GCM Decryptedtext is: Hello, World! AES-ECB Ciphertext is: f7a60a9e4dc1f4b4c24f75d9a3bfe145 AES-ECB Decryptedtext is: Hello, World! ``` 以上代码仅供参考,实际使用时需要根据具体需求进行调整和优化。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值