encryptedData无法被正确解码
java语言,写的解码方法,可以正确解析demo中的数据,但是在项目中 自己用的时候 解析后总是有乱码(很偶尔能正确解析)。
有遇到过的大神么?
java语言,写的解码方法,可以正确解析demo中的数据,但是在项目中 自己用的时候 解析后总是有乱码(很偶尔能正确解析)。
有遇到过的大神么?
时间过去太久了,我都忘记了还在这里问过。。。
贴一下代码吧,虽然,现在这个代码很容易找
import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import java.nio.charset.StandardCharsets; /** * Created by martyHou on 2018/11/9. */public class WXBizDataCrypt { private String sessionKey; public WXBizDataCrypt(String sessionKey) { this.sessionKey = sessionKey; } public String decryptData(String encryptedData, String ivData) throws Exception { if (this.sessionKey == null || this.sessionKey.length() != 24) { throw new Exception("invliad sessionKey"); } byte[] aesKey = base64Decode(this.sessionKey); if (ivData == null || ivData.length() != 24) { throw new Exception("invliad iv"); } byte[] aesIV = base64Decode(ivData); try { SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(aesIV); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 = MyBase64.getDecodedBase64(encryptedData);//先用base64解密 byte[] original = cipher.doFinal(encrypted1); return new String(original, StandardCharsets.UTF_8); } catch (Exception ex) { ex.printStackTrace(); } return null; } private byte[] base64Decode(String base64Code) { byte[] decoded = null; try { byte[] bytes =base64Code.getBytes(StandardCharsets.UTF_8); decoded = Base64.getDecoder().decode(bytes); } catch (Exception e) { // TODO: handle exception } return decoded; } public static void main(String[] args) throws Exception { String appId = "myappid"; String sessionKey = "mysessionkey"; String encryptedData = "asdfafasdf"; String iv = "r7BXXKkLb8qrSqiA=="; String res = new WXBizDataCrypt(sessionKey).decryptData(encryptedData, iv); System.out.println(res); }} |