无法在Scala中解密Ruby加密的字符串

时间:2017-10-04 16:47:45

标签: ruby scala encryption

我正在使用ActiveSupport :: MessageEncryptor来加密Ruby中的字符串,如下所示:

salt = SecureRandom.random_bytes(64)
// => "s\x90L\xB8\xEF\x8BBp\xB6\xF5A\x95\xA8]+\x94\xF3\xA7\x9A\x84+jC\xBF\xB0\x15\xEF*\x8C\xDD.\xE5\xC7Y\xCE\xE1\xAA\xA4I/%.\x9E\x14\xC1\xA8\x9E\x122\xE0\x19.\x19\xD8\xB6\xE8\x83\xE1\xFE\x16\xB5\x11N\x18"

key = ActiveSupport::KeyGenerator.new('password').generate_key(salt)
// => "\x12\xBD1\xA0Q\xBF)\\\x89\xDF\x95\xD0\f\x03\x17P'\x87\xAD\x92b\xB5%\xC7X\x01\x9Ar\xCB\xC9\x1A\x10'\xC4\x95w\xBF\xED]\x17\xEB\x9F#\xC6\xEE8S\xE1^\x18\xE2^\x85Z\rJ\x9A\xEE\xA5\xEC|\xA2\xA9\x8E"

crypt = ActiveSupport::MessageEncryptor.new(key)
encrypted_username = crypt.encrypt_and_sign("daniel")
// => "N0dHcFM3MnQrcW1HUk9UTGwxeUJsZmlCNzcwUGhrdUdtbE9YWnUxamZFST0tLUVUcUlIU2k1ZHIvTmlDRUgzM2FsS0E9PQ==--1ede80eb2b498ddf5133f8f3a45a82db2476c740"

然后在Scala中我试图像这样解密:

var encrypted_str = "N0dHcFM3MnQrcW1HUk9UTGwxeUJsZmlCNzcwUGhrdUdtbE9YWnUxamZFST0tLUVUcUlIU2k1ZHIvTmlDRUgzM2FsS0E9PQ==--1ede80eb2b498ddf5133f8f3a45a82db2476c740"

val parts = encrypted_str.split("--");

val encryptedData = Base64.decodeBase64(parts(0))

val iv = Base64.decodeBase64(parts(1))

val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv.take(16)));

val result = cipher.doFinal(encryptedData);
println(new String(result, "UTF-8"))

但是我遇到了这个错误:

javax.crypto.IllegalBlockSizeException:使用填充密码解密时输入长度必须是16的倍数

1 个答案:

答案 0 :(得分:0)

我认为问题可能在这里:

val iv = Base64.decodeBase64(parts(1))

邮件的第二部分是1ede80eb2b498ddf5133f8f3a45a82db2476c740,它不是基本的64位编码字符串,它是十六进制编码的字符串。试试这个:

Hex.decodeHex(parts(1))