java - 解密 AES key 时出现无效 key 异常

标签 java encryption cryptography aes rsa

我有一些加密和解密文件的方法。据我所知,我的加密函数做得很好,而解密通常会抛出 InvalidKeyException,特别是在 Cipher.getInstance("AES"); 位上。我已将其从 RSA 切换到 "RSA/CBC/PKCS5Padding" 但到目前为止没有任何效果。

主要功能:

static String inFile = "";
    static String outFile = "";
    static String hexKey="";
    static String keyStore;
    static String keyName;

    public static void main(String[] args) {

        if (args.length==5 && args[0].equals("-encRSA") ) {
            keyStore = args[1];
            keyName  = args[2];
            inFile   = args[3];
            outFile  = args[4];
            encryptRSA();
        } else if (args.length==5 && args[0].equals("-decRSA") ) {
            keyStore = args[1];
            keyName  = args[2];
            inFile   = args[3];
            outFile  = args[4];
            decryptRSA();
        } else {
            System.out.println("This is a simple program to encrypt and decrypt files");
            System.out.println("Usage: ");
            System.out.println("    -encRSA <keyStore> <keyName> <inputFile> <outputFile>         RSA encrypt");
            System.out.println("    -decRSA <keyStore> <keyName> <inputFile> <outputFile>         RSA decrypt");
    }

加密函数

private static void encryptRSA() {
        try {
            //Get the public key from the keyStore and set up the Cipher object
            PublicKey publicKey = getPubKey(keyStore,keyName);
            Cipher rsaCipher = Cipher.getInstance("RSA");
            rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);

            //Read the plainText
            System.out.println("Loading plaintext file: "+inFile); 
            RandomAccessFile rawDataFromFile = new RandomAccessFile(inFile, "r");
            byte[] plainText = new byte[(int)rawDataFromFile.length()];
            rawDataFromFile.read(plainText);

            // Generate a symmetric key to encrypt the data and initiate the AES Cipher Object
            System.out.println("Generating AES key"); 
            KeyGenerator sKenGen = KeyGenerator.getInstance("AES"); //ECB is fine here
            Key aesKey = sKenGen.generateKey();
            Cipher aesCipher = Cipher.getInstance("AES");
            aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);

            // Encrypt the symmetric AES key with the public RSA key
            System.out.println("Encrypting Data"); 
            byte[] encodedKey = rsaCipher.doFinal(aesKey.getEncoded()); 
            // Encrypt the plaintext with the AES key
            byte[] cipherText = aesCipher.doFinal(plainText);

            //Write the encrypted AES key and Ciphertext to the file.
            System.out.println("Writting to file: "+outFile);
            FileOutputStream outToFile = new FileOutputStream(outFile);
            outToFile.write(encodedKey);
            outToFile.write(cipherText);

            System.out.println("Closing Files");
            rawDataFromFile.close();
            outToFile.close();
        }
        catch (Exception e) { 
            System.out.println("Doh: "+e); 
        }
    }

解密函数(到目前为止):

private static void decryptRSA()
    {
        FileInputStream cipherfile;
        try {
            cipherfile = new FileInputStream(inFile);

        byte[] ciphertext = new byte[cipherfile.available()];

        PrivateKey privatekey = getKeyPair().getPrivate();

        /* Create cipher for decryption. */

        Cipher decrypt_cipher = Cipher.getInstance("AES");
        decrypt_cipher.init(Cipher.DECRYPT_MODE, privatekey);

        /* Reconstruct the plaintext message. */


        byte[] plaintext = decrypt_cipher.doFinal(ciphertext);
        FileOutputStream plainfile = new FileOutputStream(outFile);
        plainfile.write(plaintext);
        plainfile.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

private static KeyPair getKeyPair() throws Exception
    {
        KeyPair keypair = null;
        FileInputStream is = new FileInputStream(keyStore);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(is, password.toCharArray());
        Key key = keystore.getKey(keyName, password.toCharArray());
        if (key instanceof PrivateKey) {
            Certificate cert = keystore.getCertificate(keyName);
            PublicKey publicKey = cert.getPublicKey();
            keypair = new KeyPair(publicKey, (PrivateKey) key);
        }
        return keypair;
    }

最佳答案

您需要逆向加密过程才能对解密过程进行编码。目前,您正在使用 RSA 加密 AES key ,然后使用 AES 将明文加密为密文。

在解密过程中,您仅尝试使用 AES 解密密文。您应该首先提取加密的 AES key ,对其进行解密,然后使用 AES 解密(其余的)密文以检索明文。

关于java - 解密 AES key 时出现无效 key 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28132124/

相关文章:

java - 类加载与类初始化

java - iOS中的视频文件解密

java - 从 ANSI X9.62 编码字节构造 ECPublicKey

java - Eclipse 不更新 JSP scriptlet 中的自定义方法

java - 如何将数组中的项目添加到 SortedSet 中?

java - 如何在 apache BasicDataSource 中使用加密密码?

cryptography - 为什么应该避免基于时间的随机数?

php - JavaScript 中的 AES 匹配 PHP 的 mcrypt

java - 将值显式乘以 long

c# - 在c#中加密大文件