AES密钥解密不起作用

时间:2014-06-10 11:26:18

标签: java cryptography

我需要使用RSA的公钥加密AES密钥,我读了几篇文章和堆栈溢出的一些问题,我设法做了算法,但我不是java程序员,虽然我需要在java,所以我认为我的问题可能更多是语法问题。 我的代码正在加密AES密钥(不知道它是否正在加密它)但是当我解密时,它不一样,我的输出:

原始AES密钥:[B @ 48e5707f

带RSA的加密AES密钥:[B @ adea215

解密的AES密钥:[B @ 7b4b5d3f

另外,每次编译和运行时,AES密钥总是相同的,与RSA相同,不应该不同?

我的代码:

public class Rsa {
    public static void main(String[] args) throws Throwable {
    //RSA init
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(512);
    KeyPair keyPair = keyGen.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    //AES init
    KeyGenerator keyGen2 = KeyGenerator.getInstance("AES");
    keyGen2.init(192);
    SecretKey secretKey = keyGen2.generateKey();
    byte[] encoded = secretKey.getEncoded(); 
    System.out.println("Original  AES key:"+ encoded);

    //Encrypting AES with RSA
    Cipher cipher  = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] encryptedMsg = cipher.doFinal(encoded);
    System.out.println("Encrypted AES Key with RSA:" + encryptedMsg);

    //Decrypting AES with RSA
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] decryptedMsg = cipher.doFinal(encryptedMsg);
    System.out.println("Decrypted AES Key:" + decryptedMsg);

}   

1 个答案:

答案 0 :(得分:1)

您看到的输出不是字节数组的内容,而是其内存地址(或其表示)。您可能希望将字节数组十六进制编码为字符串,然后输出该字符串以便能够比较内容。

您的输出是不同的,因为它是两个不同的字节数组对象,但这并不代表它们的内容不相同。