I need to encrypt values in my Java code with user choice key and decrypt the values in Java script module.
Below is my Java code to encrypt the values. Here I am generating 128 bit key value from the user choice key and same is using to encrypt the values.
String plainText = "Hello, World! This is a Java/Javascript AES test.";
try {
byte[] rawKey = getRawKey("12345".getBytes());
SecretKey key = new SecretKeySpec(rawKey, "AES");
AlgorithmParameterSpec iv = new IvParameterSpec(
Base64.decodeBase64("5D9r9ZVzEYYgha93/aUK2w=="));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
System.out.println(Base64.encodeBase64String(cipher
.doFinal(plainText.getBytes("UTF-8"))));
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception in crypto...");
}
public static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
String s = new String(raw);
System.out.println("raw key.." + raw);
return raw;
}
Above code printing the below values:
raw key..[B@45b9ce4b
vN2GouJcVli/rFMDHEwCNZejraO5cQxBtlo5D64qkaRTkxxRTIo+Vm38H4fUZp7ABxj7ul0Ha6bO5aFxMzMY0g==
When I use the above values to decrypt in JS code , I am not getting any response.
<html>
<head>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script >
var encrypted = CryptoJS.enc.Base64.parse('vN2GouJcVli/rFMDHEwCNZejraO5cQxBtlo5D64qkaRTkxxRTIo+Vm38H4fUZp7ABxj7ul0Ha6bO5aFxMzMY0g==');
var key = CryptoJS.enc.Base64.parse('[B@45b9ce4b');
var iv = CryptoJS.enc.Base64.parse('5D9r9ZVzEYYgha93/aUK2w==');
document.write(CryptoJS.enc.Utf8.stringify(CryptoJS.AES.decrypt(
{ ciphertext: encrypted },
key,
{ mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv: iv, })));
</script>
</head>
<body>
<h1>hsd h </h1>
</body>
</html>
Please point me If there's anything missing from my code or please suggest me if any alternative to produce the same result.