encryptedData无法被正确解码
发布于 6 年前 作者 napan 8361 次浏览 来自 问答

java语言,写的解码方法,可以正确解析demo中的数据,但是在项目中 自己用的时候 解析后总是有乱码(很偶尔能正确解析)。

有遇到过的大神么?

4 回复

打印一下小程序里发送到服务器之前的 encryptedData,和你服务器上收到的是否一直。

要加URI转码。

您好,请问解决了么?能不能分享一下解码代码和jar包

时间过去太久了,我都忘记了还在这里问过。。。

贴一下代码吧,虽然,现在这个代码很容易找

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);
    }
}

看看是否是这个原因:

数据传输时的问题,+号自动转换为空格了,要对数据编码

回到顶部