简体   繁体   English

AES在Ruby和Scala(或Java)中解密

[英]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. 我在Ruby中使用AES-CBC-128编码,我正在尝试用Java解码它,但我无法让它工作。

Here is the code I use to decrypt in Ruby : 这是我在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. 如果您运行此代码段,它将输出字符串matt现在我正在尝试使用Java API的实现在Scala中实现相同的功能。 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. 我已经尝试了两个keyBytes,但没有一个正在工作。 I don't see what I'm missing to make it work. 我没有看到我错过了让它发挥作用。

You only want 16 bytes of your key, so the line 您只需要16个字节的密钥,所以该行

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

should be 应该

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

Try "AES/CBC/PKCS5Padding" instead of "AES/CBC/NoPadding" . 尝试"AES/CBC/PKCS5Padding"而不是"AES/CBC/NoPadding" OpenSSL defaults to PKCS#7 padding, which is implemented by "PKCS5Padding" in Java. OpenSSL默认使用PKCS#7填充,它由Java中的"PKCS5Padding"实现。 Note that PKCS#5 padding and PKCS#7 padding are more or less equivalent . 请注意,PKCS#5填充和PKCS#7填充或多或少相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM