用Ruby加密,在Java中解密——为什么不起作用?

8

我做错了什么?我期望这个Java程序打印出"private"。我的目标是尝试用Java编写MessageEncryptor.decrypt ruby方法。

Ruby加密(大部分代码来自MessageEncryptor,但修改为不使用Marshal),但我已经提取出来,以便更容易看到正在发生的事情:

require 'openssl'
require 'active_support/base64'

@cipher = 'aes-256-cbc'
d = OpenSSL::Cipher.new(@cipher)
@secret = OpenSSL::PKCS5.pbkdf2_hmac_sha1("password", "some salt", 1024, d.key_len)
cipher = OpenSSL::Cipher::Cipher.new(@cipher)

iv = cipher.random_iv

cipher.encrypt
cipher.key = @secret
cipher.iv = iv

encrypted_data = cipher.update("private")
encrypted_data << cipher.final

puts [encrypted_data, iv].map {|v| ::Base64.strict_encode64(v)}.join("--")

打印出:

tzFUIVllG2FcYD7xqGPmHQ==--UAPvdm3oN3Hog9ND9HrhEA==

Java 代码:

package decryptruby;

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class DecryptRuby {    
    public static String decrypt(String encrypted, String pwd, byte[] salt)
            throws Exception {

        String[] parts = encrypted.split("--");
        if (parts.length != 2) return null;

        byte[] encryptedData = Base64.decodeBase64(parts[0]);
        byte[] iv = Base64.decodeBase64(parts[1]);

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(pwd.toCharArray(), salt, 1024, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey aesKey = new SecretKeySpec(tmp.getEncoded(), "AES");


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

        byte[] result = cipher.doFinal(encryptedData);
        return result.toString();
    }


    public static void main(String[] args) throws Exception {
        String encrypted = "tzFUIVllG2FcYD7xqGPmHQ==--UAPvdm3oN3Hog9ND9HrhEA==";

        System.out.println("Decrypted: " + decrypt(encrypted, "password", "some salt".getBytes()));
    }
}

需要打印的内容

解密后的内容:[B@432a0f6c

1个回答

19

这是问题 - 或者至少是一个问题:

byte[] result = cipher.doFinal(encryptedData);
return result.toString();
你正在调用一个字节数组的 toString() 方法。数组没有重写 toString(),所以这不会给你想要的结果,正如你所看到的那样。相反,你需要编写类似于下面的代码:
return new String(result, "UTF-8");

... 但在加密前,您需要知道将原始字符串转换为字节时使用了什么编码。从 Ruby 代码中并不清楚使用了哪种编码方式,但如果您能明确指出它(最好使用 UTF-8),那么将会使您的生活变得更加轻松。

简而言之,我怀疑这个问题与加密无关 - 它完全与在 Ruby 中将文本转换为字节,然后在 Java 中将相同序列的字节再次转换回字符串有关。

当然,加密也可能失败,但这是另一回事。


谢谢,Jon。就是这个了。还需要等7分钟才能标记为答案。 - Bradford

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接