Question

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 = "\x30\xd2\xff\x5d\x08\xac\x83\x95\x02\x0f\x23\x20\x81\xc9\xc1\xe4"
key = "1234567890ABCDEF1234567890ABCDEF"
message = "\xb8\x9f\x27\x30\xe5\x4d\x81\xf3\xa9\x3d\x0b\xe3\xaa\x52\x50\x15"


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.

Was it helpful?

Solution

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")

OTHER TIPS

Try "AES/CBC/PKCS5Padding" instead of "AES/CBC/NoPadding". OpenSSL defaults to PKCS#7 padding, which is implemented by "PKCS5Padding" in Java. Note that PKCS#5 padding and PKCS#7 padding are more or less equivalent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top