jsp中的加密和使用AES的jQuery中的解密

时间:2015-01-13 06:23:57

标签: jquery jsp encryption aes cryptojs

我想在jsp中加密并在jquery中解密,我在jsp中的代码下面做了

String myKey = "dfslkskfs";
MessageDigest sha = null;
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[]   bytesEncoded = Base64.encodeBase64(cipher.doFinal(json
        .getBytes("UTF-8")));
jsontext =  new String(bytesEncoded );

jsp文件中的html标记: -

<input type="hidden"  id="jsonid" value=<%=jsontext%> />
<input type="hidden" name=secretKey id="secretKey" value=<%=new String(secretKey.getEncoded())%> />

Jquery代码

我在下面用两个js文件进行解密 aes.js,mode-ecb-min.js

jsonString      = $("#jsonid").val();
secretKey       = $("#secretKey").val();
jsonString = escapeStr(jsonString);


var key = CryptoJS.enc.Base64.parse(secretKey);

var decryptedData = CryptoJS.AES.decrypt(jsonString, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
});
var decryptedText = decryptedData.toString(CryptoJS.enc.Utf8);
alert(decryptedText);

如果我运行上面的代码我得到了异常&#34;未捕获错误:格式错误的UTF-8数据&#34;所以请告诉我哪里出错了,或者你可以告诉我任何其他的方法。

1 个答案:

答案 0 :(得分:0)

问题是双重的。

当您致电secretKey.getEncoded()时,密码实际上并未编码。在将其放入页面之前,您应该将其编码为Base64。以下是一些解决方案:Converting Secret Key into a String and Vice Versa

在客户端,您解析密钥,但不解析您实际编码为Base64的密文。你应该从Base64解析它们。

相关问题