微信解密工具 - encryptedData

public class WeChartUtil {

    public static void main(String[] args) {
        String decrypt = WeChartUtil.decrypt("3xNSLy94VbU6J3dxC0C6H6KIzDo6auEfWMNFy5HELALmIjFwZ7UWXguNPnE3rtx/MLqdUn5Aym6cLyDPldO12q8lRfilWOMZDaLwghz+aFi5yzaATr1/W4YvXZyUD9yGAEsYYxVd6WUMv8qVyJhSYmcdaTN/jmkfKqO87w8VZmW8j+5w9WUGZN9l4fSQYQNfhyPD9TvXVRmw+h6meUYZ4g==",
                "eI5VWDM/ZbrxCPeBtAktFg==", "mGMaVRbs6bY2cMoapBC37g==");
        System.out.println(decrypt);
    }

    /**
     * 解密 微信密文
     * @param encryptedData 密文
     * @param sessionKey sessionKey
     * @param iv iv
     * @return 明文
     */
    public static String decrypt(String encryptedData, String sessionKey, String iv) {
        String result = "";
        // 被加密的数据
        byte[] dataByte = Base64.decodeBase64(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decodeBase64(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decodeBase64(iv);
        try {
            // 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + 1;
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters
                    .getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                result = new String(resultByte, StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

如果你出现了这种错误:

javax.crypto.BadPaddingException: pad block corrupted
	at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$BufferedGenericBlockCipher.doFinal(Unknown Source)
	at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source)
	at javax.crypto.Cipher.doFinal(Cipher.java:2164)
	at com.tongli.system.util.WeChartUtil.decrypt(WeChartUtil.java:61)
	at com.tongli.system.util.WeChartUtil.main(WeChartUtil.java:22)

说明你三个参数不匹配,也就是说sessionKey过期了, 需要获取最新的三个参数进行解密
剩下不管是什么问题,只需要检查参数是否完全一直,请相信此代码是经过测试的

成功页面:

{"phoneNumber":"19901663425","purePhoneNumber":"19901663425","countryCode":"816","watermark":{"timestamp":1588217611,"appid":"wx5955af24754306b6"}}

进程完成,退出码 0

你可能感兴趣的:(微信解密工具 - encryptedData)