JDK 1.6 实现 AEAD_AES_256_GCM 解密

背景

微信支付最新的 V3 版本接口,微信返回的报文中,如果涉及敏感信息,是需要基于 AEAD_AES_256_GCM 进行解密的。而 AEAD_AES_256_GCM 从 JDK1.7 开始才支持。如果你和我一样,因为各种历史原因,导致必须在 JDK 1.6 的环境,完成这件事情,那么下面的代码就是解决方案,希望能够帮到你。

PS:该代码实现是在 GitHub Copilot 的帮助下,结合 AEAD_AES_256_GCM 规范 调整完成。

代码实现

package org.use.be.util;

import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.KeyParameter;

import java.io.IOException;

/**
 * 支持 JDK 1.6 的 AEAD_AES_256_GCM 加解密工具类
 *
 * @author vladosama
 * @since 2023/12/18
 */
public class AesUtil {
    static final int KEY_LENGTH_BYTE = 32;
    static final int TAG_LENGTH_BIT = 128;

    /**
     * 解密
     * @param associatedData
     * @param nonce
     * @param ciphertext
     * @return
     * @throws IOException
     */
    public static String decryptToString(byte[] privateKey, byte[] associatedData, byte[] nonce, String ciphertext)
            throws IOException {
        if (privateKey.length != KEY_LENGTH_BYTE) {
            throw new IllegalArgumentException("无效的ApiV3Key,长度必须为32个字节");
        }
        final byte[] aesKey = privateKey;
        try {
            GCMBlockCipher cipher = new GCMBlockCipher(new org.bouncycastle.crypto.engines.AESEngine());
            KeyParameter key = new KeyParameter(aesKey);
            AEADParameters parameters = new AEADParameters(key, TAG_LENGTH_BIT, nonce); // 128 is the tag length
            cipher.init(true, parameters);
            cipher.processAADBytes(associatedData, 0, associatedData.length);

            byte[] encryptedText = Base64Util.decode(ciphertext); // Base64 Decode,大家选择任意合适的 Base64 工具即可,我这里使用的是自己写的工具类
            byte[] decryptedText = new byte[cipher.getOutputSize(encryptedText.length)];
            int len = cipher.processBytes(encryptedText, 0, encryptedText.length, decryptedText, 0);
            len += cipher.doFinal(decryptedText, len);
            len -= KEY_LENGTH_BYTE; // 去掉 authentication tag 的长度
            String decryptedString = new String(decryptedText, 0, len, "utf-8");
            return decryptedString;
        } catch (InvalidCipherTextException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * 测试
     */
    public static void main(String[] args) throws IOException {
        String a = "..."; // 待解密密文
        String key = "..."; // 密钥
        String non = "..."; // nonce
        String aso = "..."; // associatedData
        String b = AesUtil.decryptToString(key.getBytes("utf-8"), aso.getBytes("utf-8"), non.getBytes("utf-8"), a); // 解密后的明文结果
        System.out.println(b);
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容