0

I want to encrypt in jsp and decrypt in jquery, i did below code in 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 );

html tag in jsp file :-

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

Jquery Code

I used below two js files for decryption 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);

If I run above code I got exception "Uncaught Error: Malformed UTF-8 data" so please tell me where I went wrong or you can tell me any other gud ways.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Ravi Chothe
  • 180
  • 5
  • 17
  • Please take the time to properly format your code. – Artjom B. Jan 13 '15 at 09:59
  • Does `escapeStr` also decode Base64 into the native format of CryptoJS? – Artjom B. Jan 13 '15 at 10:02
  • This seems like obfuscation. If you serve your page over SSL/TLS then you don't need the encryption and if you don't then the plaintext can be recovered since you're sending the key with it. Also, ECB is a bad idea since it is not semantically secure. You should use an authenticated mode like GCM or use CBC with an HMAC. – Artjom B. Jan 13 '15 at 10:13

1 Answers1

0

The problem is two-fold.

The secret key is not actually encoded when you call secretKey.getEncoded(). You should encode it as Base64 before putting it into the page. Here are some solutions: Converting Secret Key into a String and Vice Versa

On the client side, you parse the key, but not the ciphertext which you actually encoded as Base64. You should parse both from Base64.

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222