JAVA⼩程序AES解密数据demo 这个链接是官⽅⽂档的地址,但是demo下载中没有java的demo
正好同事有个要⽤⼩程序拿到⽤户⼿机号的需求,需要AES-BCB进⾏数据解密
AES就不介绍了,⼤家⾃⾏wiki了解
废话不多说,直接上demo吧
下⾯是对数据解密的⼯具类
package com.kilde.util;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
pto.Cipher;
pto.spec.IvParameterSpec;
pto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;
import java.util.Base64;
/**
* ⼩程序 AES 解密⼯具
* @author Kilde
*/
@Data
有趣的java小程序public class WXBizDataCrypt {
private String appId;
private String sessionKey;
public WXBizDataCrypt(String appId, String sessionKey) {
this.appId = appId;
this.sessionKey = sessionKey;
}
/**
* 解密成json
* 解密成json
* @param encryptedData
* @param iv
* @return
*/
public JSONObject decrypt(String encryptedData, String iv) {
byte[] encryptedDataDecode = Decoder().decode(encryptedData);
byte[] sessionKeyDecode = Decoder().decode(this.sessionKey);
byte[] ivDecode = Decoder().decode(iv);
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] decodeData = decode(encryptedDataDecode, sessionKeyDecode, ivDecode); String stringData = new String(decodeData);
JSONObject jsonObject = JSONObject.parseObject(stringData);
return jsonObject;
}
/**
* 解密算法 AES-128-CBC
* 填充模式 PKCS#7
*
* @param encryptedDataDecode ⽬标密⽂
* @return
* @throws Exception
*/
private byte[] decode(byte[] encryptedDataDecode, byte[] sessionKeyDecode, byte[] iv) { try {
Cipher cipher = Instance("AES/CBC/PKCS7Padding");
Key sKeySpec = new SecretKeySpec(sessionKeyDecode, "AES");
cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(iv));// 初始化
byte[] result = cipher.doFinal(encryptedDataDecode);
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 处理iv
*
* @param iv
* @return
* @throws Exception
*/
private AlgorithmParameters generateIV(byte[] iv) throws Exception {
AlgorithmParameters params = Instance("AES");
params.init(new IvParameterSpec(iv));
return params;
}
}
下⾯是使⽤的demo
package com.kilde.demo;
import com.alibaba.fastjson.JSONObject;
public class Demo {
public static void main(String[] args) {
String appId = "wx4f4bc4dec97d474b";
String sessionKey = "tiihtNczf5v6AKRyjwEUhQ==";
String encryptedData = "CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZMQmRzooG2xrDcvSnxIMXFufNstNGTyaGS9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+3hVbJSR String iv = "r7BXXKkLb8qrSNn05n0qiA==";
WXBizDataCrypt pc = new WXBizDataCrypt(appId,sessionKey);
JSONObject decrypt = pc.decrypt(encryptedData, iv);
System.out.String());
}
}
下⾯是运⾏后的返回结果
已经可以成功解密密⽂了。
还有⼀点需要注意,就是去甲⾻⽂官⽹下载 对应你的版本的JCE包,然后更新到你的jdk->jre->lib->security包中
jdk1.8的jce更新包在这⾥,其他的⼤家⾃⾏寻
如果解决了⼤家的问题,⾟苦⼤家打个赏
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论