分享我使用的用户解密微信支付APIV3的通知notify,根据微信支付官方的介绍:https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_5.shtml是使用的AEAD_AES_256_GCM加密方式,使用key、nonce和associated_data,对数据密文resource.ciphertext进行解密,得到JSON形式的资源对象。不过看了下,当前页面并没有相关的例子,下面贴出我使用的工具算法。
/**
* AEAD_AES_256_GCM 解密
* @param mchKey 用商户平台上设置的APIv3密钥【微信商户平台—>账户设置—>API安全—>设置APIv3密钥】,记为key
* @param ciphertext 需要解密的字符串
* @return 解密后的字符(JSON字符串,再根据自己的需要转成JSON即可)
*/
public String decryptToString(String mchKey, String associatedData, String nonce, String ciphertext)
throws Exception {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec key = new SecretKeySpec(mchKey.getBytes(StandardCharsets.UTF_8), "AES");
GCMParameterSpec spec = new GCMParameterSpec(128, nonce.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.DECRYPT_MODE, key, spec);
cipher.updateAAD(associatedData.getBytes(StandardCharsets.UTF_8));
return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), StandardCharsets.UTF_8);
}
文章评论