解密AES密钥时无效密钥异常

时间:2015-01-25 01:07:41

标签: 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;
    }

1 个答案:

答案 0 :(得分:1)

您需要撤消加密过程以对解密过程进行编码。目前,您正在使用RSA加密AES密钥,然后使用AES将明文加密为密文。

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