现在需要在微信小程序用 JS 解密 JAVA 加密后的字符串. 如何可以用 JS 代码来解密?
public static String encrypt(String xmlStr) { byte[] encrypt = null; try { // 取需要加密内容的 utf-8 编码。 encrypt = xmlStr.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // 取 MD5Hash 码,并组合加密数组 byte[] md5Hasn = null; try { md5Hasn = EncryptUtil.MD5Hash(encrypt, 0, encrypt.length); } catch (Exception e) { e.printStackTrace(); } // 组合消息体 byte[] totalByte = EncryptUtil.addMD5(md5Hasn, encrypt); // 取密钥和偏转向量 byte[] key = new byte[8]; byte[] iv = new byte[8]; getKeyIV(EncryptUtil.key, key, iv); SecretKeySpec deskey = new SecretKeySpec(key, "DES"); IvParameterSpec ivParam = new IvParameterSpec(iv); // 使用 DES 算法使用加密消息体 byte[] temp = null; try { temp = EncryptUtil.DES_CBC_Encrypt(totalByte, deskey, ivParam); } catch (Exception e) { e.printStackTrace(); } // 使用 Base64 加密后返回 return new BASE64Encoder().encode(temp); } public static String decrypt(String xmlStr) throws Exception { // base64 解码 BASE64Decoder decoder = new BASE64Decoder(); byte[] encBuf = null; try { encBuf = decoder.decodeBuffer(xmlStr); } catch (IOException e) { e.printStackTrace(); } // 取密钥和偏转向量 byte[] key = new byte[8]; byte[] iv = new byte[8]; getKeyIV(EncryptUtil.key, key, iv); SecretKeySpec deskey = new SecretKeySpec(key, "DES"); IvParameterSpec ivParam = new IvParameterSpec(iv); // 使用 DES 算法解密 byte[] temp = null; try { temp = EncryptUtil.DES_CBC_Decrypt(encBuf, deskey, ivParam); } catch (Exception e) { e.printStackTrace(); } // 进行解密后的 md5Hash 校验 byte[] md5Hash = null; try { md5Hash = EncryptUtil.MD5Hash(temp, 16, temp.length - 16); } catch (Exception e) { e.printStackTrace(); } // 进行解密校检 for (int i = 0; i < md5Hash.length; i++) { if (md5Hash[i] != temp[i]) { // System.out.println(md5Hash[i] + "MD5 校验错误。" + temp[i]); throw new Exception("MD5 校验错误。"); } } // 返回解密后的数组,其中前 16 位 MD5Hash 码要除去。 return new String(temp, 16, temp.length - 16, "utf-8"); }
1 applesstt 2017-11-01 15:45:45 +08:00 |
![]() | 2 Karblue 2017-11-01 17:41:35 +08:00 ajax 请求服务端解密。解密最好不要放在客户端。 |