AES-128 padded encryption/decryption with Railo, Java and AS3

I’ve recently been working on text file decryption using Railo server. My files were encrypted in ActionScript 3 with the powerful AES-128 algorithm. For more info on AS3 encryption see Hurlant Crypto demo.

My challenge was to decypt this heavily encrypted content on a different platform, i.e. Railo with underlying Java Cipher capabilities.

The 6 things I knew about the encrypted content were:
1. Encryption Method – AES
2. Mode – CBC (Cipher-block chaining)
3. Padding – PKCS5
4. Initialisation Vector (IV) – given hex string
5. Passphrase – given hex string
6. Encrypted text file saved in base64 encoded string.

For my records, this is how I went about decrypting on Railo:


// Create some java objects
IvParameterSpec = createObject("java", "javax.crypto.spec.IvParameterSpec");
Cipher = createObject("java", "javax.crypto.Cipher");
SecretKeySpec = createObject("java", "javax.crypto.spec.SecretKeySpec");
BASE64Decoder = createObject("java", "sun.misc.BASE64Decoder");
Str = createObject("java", "java.lang.String");
MessageDigest = createObject("java", "java.security.MessageDigest");

encryptedFileContent = "base64encodedcontent";
password = binarydecode("somehexpassphrase", "hex");
iv = binarydecode("somehexivstring", "hex");

skeySpec = SecretKeySpec.init(password, "AES");
ivSpec = IvParameterSpec.init(iv);
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

encryptedContent = BASE64Decoder.decodeBuffer(encryptedFileContent);
cipher.init(Cipher.DECRYPT_MODE,skeySpec,ivSpec);
decryptedBytes = cipher.doFinal(encryptedContent);
decryptedString = Str.init(decryptedBytes);

Now that we know how the decryption works, encrypting data on Railo should be a piece of cake. For example:


password = "somepassphrase";
stringToEncrypt = "stringToEncrypt";
md = MessageDigest.getInstance("MD5");
md.update(password.getBytes("UTF-8"), 0, password.length());
rawKey = md.digest();
	
skeySpec = SecretKeySpec.init(rawKey, "AES");
ivSpec = IvParameterSpec.init(rawKey);
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);

encryptedbytes = cipher.doFinal(stringToEncrypt.getBytes());

The only thing you need to be aware of is the format of parameters passed into encryption/decryption logic, and convert them appropriately. These parameters can be either plain, base64 or hex strings.

Who would’ve thought that reverse engineering could be som much fun 🙂

Cheers
Marko