Import org.apache.commons.codec.binary.Base64;
Import javax.crypto.Cipher;
Import javax.crypto.KeyGenerator;
Import javax.crypto.spec.IvParameterSpec;
Import javax.crypto.spec.SecretKeySpec;
Import java.security.AlgorithmParameters;
Import java.security.Key;
Import java.security.Security;
/**
*@authorclunt
*<p>微信手機號解密</p>
**/
public class WxUtils{
/**
**微信數據解密<br/>
**對稱解密使用的算法爲AES-128-CBC,數據採用PKCS#7填充<br/>
**對稱解密的目標密文:encrypted=Base64_Decode(encryptData)<br/>
**對稱解密祕鑰:key=Base64_Decode(session_key),aeskey是16字節<br/>
**對稱解密算法初始向量:iv=Base64_Decode(iv),同樣是16字節<br/>
**
**@paramencrypted目標密文
**@paramsession_key會話ID
**@paramiv加密算法的初始向量
*
*/
public static String wxDecrypt(Stringencrypted,Stringsession_key,Stringiv){
Stringresult=null;
byte[]encrypted64=Base64.decodeBase64(encrypted);
byte[]key64=Base64.decodeBase64(session_key);
byte[]iv64=Base64.decodeBase64(iv);
try{
i nit();
result=newString(decrypt(encrypted64,key64,generateIV(iv64)));
}catch(Exceptione){
e.printStackTrace();
}
return result;
}
/**
**初始化密鑰
*
*/
public static void init()throws Exception{
Security.addProvider(neworg.bouncycastle.jce.provider.BouncyCastleProvider());
KeyGenerator.getInstance(WechatAccountConfig.AES).init(128);
}
/**
**生成iv
*
*/
public static AlgorithmParameters generateIV(byte[]iv)throws Exception{
//iv爲一個16字節的數組,這裏採用和iOS端一樣的構造方法,數據全爲0
AlgorithmParametersparams=AlgorithmParameters.getInstance(WechatAccountConfig.AES);
params.init(new IvParameterSpec(iv));
return params;
}
/**
**生成解密
*
*/
public static byte[]decrypt(byte[]encryptedData,byte[]keyBytes,AlgorithmParameters iv)throws Exception{
Keykey=newSecretKeySpec(keyBytes,WechatAccountConfig.AES);
Ciphercipher=Cipher.getInstance(WechatAccountConfig.AES_CBC_PADDING);
//設置爲解密模式
cipher.init(Cipher.DECRYPT_MODE,key,iv);
return cipher.doFinal(encryptedData);
}
}