混合加密方法失败

时间:2015-06-06 21:17:59

标签: java security encryption aes rsa

我在尝试使用AES和RSA的混合加密创建小程序时遇到了麻烦。它只使用我尝试的对称加密AES工作得很好,但是当我尝试实现RSA来包装AES加密消息和密钥时,我只是无法让它工作。

我已经明白这样的程序可以使用outputstreams或cipherstreams来完成,但如果可能的话,我想用这种方式解决它。换句话说,id就像用户在JOptionInputDialog中输入任何字符串并使用AES密钥加密,然后使用RSA公钥加密AES密钥,然后使用私有RSA密钥解密。

我希望答案显示在同一个JOptionPane窗口中。例如:

加密文字:jfjfjh 解密文本:Hello

我现在有些问题了解如何使用私有RSA密钥解密该字符串。我不知道我错过了什么或做错了什么。从任何一个例子,谷歌搜索过去一周半,我认为它看起来很好。我必须错过一些正确在我眼前的东西,但我无法看到它,因为我坐了太多时间试图找到一种不同的方法(我想我已经改变了一百万次,但我不能告诉你我所有的方法所以这个是我与你分享的。我真的非常感谢任何帮助。所以这是我的代码:(希望你能理解,因为有些单词是我的语言)

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.swing.JOptionPane;

/**
 *
 * @author Patricia
 */
public class EncryptionDecryption {

    /**
     * @param args the command line arguments
     * @throws java.lang.Exception
     */
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, 
            InvalidKeyException, IllegalBlockSizeException, BadPaddingException{

                //Creating assymmetric keys RSA ( A public Key and Private Key )
                KeyPairGenerator gen2 = KeyPairGenerator.getInstance("RSA");
                gen2.initialize(1024);

               KeyPair keyPair = gen2.genKeyPair();
               PrivateKey privatnyckel = keyPair.getPrivate();
               PublicKey publiknyckel = keyPair.getPublic();



              //Create assymmetric key AES //Create key generator
              KeyGenerator gen = KeyGenerator.getInstance("AES"); //Returns keygenerator object that generates key  for specified algorithm in this case AES

       SecureRandom random = new SecureRandom();
       gen.init(random);
              // create a key
             SecretKey AES = gen.generateKey();
             //get the raw key bytes
             byte[] symmetriskNyckel =AES.getEncoded(); //Returns copy of the key bytes

              //Create cipher based upon AES, encrypt the message with AES key
    Cipher cipher = Cipher.getInstance("AES");
    //Initialize cipher with secret key AES
  cipher.init(Cipher.ENCRYPT_MODE, AES);

   // get the text to encrypt with AES key
  String inputText1 = JOptionPane.showInputDialog(" Enter the secret message");
 //Encrypt the plaintext message you wanna send with the symmetric key AES;
            byte[] kryptera = cipher.doFinal(inputText1.getBytes());

//encrypt AES key with RSA
    Cipher pipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    pipher.init(Cipher.WRAP_MODE, publiknyckel);
    byte[] krypteradAESNyckel = cipher.wrap(AES); 

    JOptionPane.showMessageDialog(null, "AES key encrypted with RSA public key " + krypteradAESNyckel);

// re-initialise the cipher to be in decrypt mode 
    Cipher flipher = Cipher.getInstance("RSA");
             flipher.init(Cipher.UNWRAP_MODE, privatnyckel );
 // decrypt message
          byte [] dekryptera =  flipher.unwrap(kryptera);



      JOptionPane.showMessageDialog
        (null, "AES symmetrisk nyckel " +symmetriskNyckel );





    // and display the results // 
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                        "Texten krypterad " + new String(kryptera) + "\n"
                                    + "Text dekrypterat: " + new String(dekryptera));




            JOptionPane.showMessageDialog(null, "\n RSA assymmetrisk privat nyckel " + privatnyckel
        + "RSA assymmetrisk publik nyckel" + publiknyckel);




            // end example
            System.exit(0);






    }

}

1 个答案:

答案 0 :(得分:1)

我认为你的变量名和评论都可以。使用新内容时,请在代码中为自己写笔记。你可以在它工作后再回来,并用丰富,有意义的名字重构,并为了清晰起见修改评论,以便他们在六个月或一年后与你交谈,以提醒你在你的时候你在想什么写了这个。 (我认为瑞典名字和英语一样好。)

正如JB Nizet指出的那样,当你打开krypteradAESNyckel中包含的对称密钥时,你正在展开kryptera。接下来,您将使用恢复的对称密钥解密kryptera。 (你的代码只输出早期的symmetriskNyckel而没有从krypteradAESNyckel中新解包它。)

我还注意到在一个案例中你

Cipher.getInstance("RSA/ECB/PKCS1Padding"); 

但稍后你

Cipher.getInstance("RSA"); 

我会让它们保持一致,两者都是" RSA / ECB / PKCS1Padding"。这种对细节的关注与清晰的变量名称和有意义的评论同样重要。