我究竟做错了什么?我希望Java程序打印“专用”。我的目标是尝试用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
这是问题-或至少 是一个 问题:
byte[] result = cipher.doFinal(encryptedData); return result.toString();
您正在调用toString()字节数组。数组不覆盖toString()。如您所见,那根本不会给您您想要的东西。相反,你需要写 的东西 ,如:
toString()
return new String(result, "UTF-8");
…但是您需要知道在加密之前使用什么 编码 将原始字符串转换为字节。从Ruby代码对我来说还不清楚使用什么编码,但是如果您可以明确地使用它(最好使用UTF-8),它将使您的生活变得更加轻松。
简而言之,我 怀疑 这个问题与加密完全无关,它与将文本转换成Ruby中的字节,然后将相同的字节序列转换成Java中的字符串有关。
当然,加密也可能会失败 , 但这是另一回事。