背景
微信支付最新的 V3 版本接口型诚,微信返回的報文中燕少,如果涉及敏感信息黎休,是需要基于 AEAD_AES_256_GCM 進行解密的辰妙。而 AEAD_AES_256_GCM 從 JDK1.7 開始才支持糜工。如果你和我一樣颂斜,因為各種歷史原因为迈,導(dǎo)致必須在 JDK 1.6 的環(huán)境,完成這件事情箩兽,那么下面的代碼就是解決方案津肛,希望能夠幫到你。
PS:該代碼實現(xiàn)是在 GitHub Copilot 的幫助下汗贫,結(jié)合 AEAD_AES_256_GCM 規(guī)范 調(diào)整完成身坐。
代碼實現(xiàn)
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個字節(jié)");
}
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); // 解密后的明文結(jié)果
System.out.println(b);
}
}