AES decrypt in Ruby and Scala (or Java)

I’m encoding using AES-CBC-128 in Ruby and I’m trying to decode it in Java but I can’t get it to work.

Here is the code I use to decrypt in Ruby :

require 'openssl'

iv = "x30xd2xffx5dx08xacx83x95x02x0fx23x20x81xc9xc1xe4"
key = "1234567890ABCDEF1234567890ABCDEF"
message = "xb8x9fx27x30xe5x4dx81xf3xa9x3dx0bxe3xaax52x50x15"


openssl_cipher = OpenSSL::Cipher.new('aes-128-cbc')
openssl_cipher.decrypt
openssl_cipher.key = key
openssl_cipher.iv = iv
result = openssl_cipher.update(message)
result << openssl_cipher.final

puts result

If you run this snippet it will output the string matt Now I’m trying to achieve the same thing in Scala, using the implementation of the Java API. Here is my non-working code :

import javax.crypto.Cipher
import javax.crypto.spec.{SecretKeySpec, IvParameterSpec}

object Main {
    def main(argv: Array[String]) {
        val iv = Array(0x30,0xd2,0xff,0x5d,0x08,0xac,0x83,0x95,0x02,0x0f,0x23,0x20,0x81,0xc9,0xc1,0xe4).map { _.toByte }
        val keyBytes = "1234567890ABCDEF1234567890ABCDEF".getBytes("UTF-8")
        //val keyBytes = Array(0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF).map { _.toByte }
        val message = Array(0xb8,0x9f,0x27,0x30,0xe5,0x4d,0x81,0xf3,0xa9,0x3d,0x0b,0xe3,0xaa,0x52,0x50,0x15).map { _.toByte }
        val key = new SecretKeySpec(keyBytes, "AES")
        val cipher = Cipher.getInstance("AES/CBC/NoPadding")
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv))
        val result = cipher.doFinal(message)

        println(new String(result, "UTF-8"))
    }
}

I’ve tried both keyBytes, but none is working. I don’t see what I’m missing to make it work.

Answer

You only want 16 bytes of your key, so the line

val key = new SecretKeySpec(keyBytes, "AES")

should be

val key = new SecretKeySpec(keyBytes.take(16), "AES")

Leave a Reply

Your email address will not be published. Required fields are marked *