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可以互相使用密钥进行加解密。

猜你喜欢

转载自blog.csdn.net/Apple_wolf/article/details/127894455