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
    评论
你可以使用Python中的cryptography库来实现AES256_GCM加密。以下是一个例子: ```python from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import hashes from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives import padding as symmetric_padding import base64 def encrypt_aes_gcm(data, key): # 生成随机的12字节IV(Initialization Vector) iv = os.urandom(12) # 创建AES-GCM加密算法实例 cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()) # 创建加密器 encryptor = cipher.encryptor() # 加密数据 ciphertext = encryptor.update(data) + encryptor.finalize() # 获取加密后的认证标签(tag) tag = encryptor.tag # 返回加密后的密文、IV和tag return ciphertext, iv, tag def main(): # 待加密的数据 data = b"{'add':'123','bcs':'456'}" # 密钥(32字节) key = b'your_key_in_bytes' # 使用AES256-GCM加密数据 ciphertext, iv, tag = encrypt_aes_gcm(data, key) # 将密文、IV和tag转换为Base64编码的字符串 ciphertext_b64 = base64.b64encode(ciphertext).decode('utf-8') iv_b64 = base64.b64encode(iv).decode('utf-8') tag_b64 = base64.b64encode(tag).decode('utf-8') print("Ciphertext:", ciphertext_b64) print("IV:", iv_b64) print("Tag:", tag_b64) if __name__ == '__main__': main() ``` 请注意,上述代码中的`your_key_in_bytes`需要替换为您自己的密钥。此外,为了运行此示例,您需要安装cryptography库。可以使用以下命令安装: ``` pip install cryptography ``` 运行上述代码后,您将获得AES256-GCM加密后的密文(ciphertext)、初始化向量(IV)和认证标签(tag)。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值