Question

I'm trying to decrypt text in java that is encrypted using CryptoJS. I've read on other posts that they use different default modes and padding so I set them both(java/cryptojs) both to use aes/cbc/nopadding. I no longer get an exception in java, but I am getting a garbled output during decryption

Encryption(JS):

var parsedLogin = JSON.parse(login);
var publicKey = "abcdefghijklmnio";
var publiciv =  "abcdefghijklmnio";
var key = CryptoJS.enc.Hex.parse(publicKey);
var iv = CryptoJS.enc.Hex.parse(publiciv);
var encrypted = CryptoJS.AES.encrypt(parsedLogin.password, publicKey, {iv: publiciv}, { padding: CryptoJS.pad.NoPadding, mode: CryptoJS.mode.CBC});

// send encrypted to POST request 

DECRYPT (Java)

String PUBLIC_KEY = "abcdefghijklmnio";
String PUBLIC_IV = "abcdefghijklmnio";
byte[] byteArr = PUBLIC_KEY.getBytes();
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
final SecretKeySpec secretKey = new SecretKeySpec(byteArr, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(PUBLIC_IV.getBytes()));

byte[] parsed = Base64.decodeBase64(encrypted.getBytes());
//byte[] parsed = DatatypeConverter.parseBase64Binary(encrypted); 

byte[] fin = cipher.doFinal(parsed);
String decryptedString = new String(fin);

The result that I'm getting is like this: Š²Û!aå{’`@"Ûîñ?Œr˜krÆ

I have already tried changing the CHARSET in the getBytes() to US-ASCII, UTF-8 and UTF-16 but all this does is change the garbled text

I have also tried using othe blocking modes and paddings but they failed at the js level. I just need a simple encryption method right now.

NOTE: Ignore the security issues...like having the key exposed in js, etc. I'll be handling those later..

No correct solution

OTHER TIPS

You shouldn't be able to use AES CBC without padding unless the password is always 16 bytes. It probably applies some sort of default padding that may or may not be a good idea.

Anyway: you need to pass your key and iv to CryptoJS as a WordArray; if you give it a string it will assume you're giving it a passphrase and derive a different key from that. As such, your Java decryption code will be using a different key/iv pair. You can create a WordArray from your strings using

var key = CryptoJS.enc.Utf8.parse("abcdefghijklmnio")
var iv = ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top