2015-01-25 3 views
0

У меня есть несколько способов шифрования и дешифрования файлов. насколько я знаю, моя функция шифрования делает свою работу отличной, в то время как дешифрование обычно генерирует InvalidKeyException, особенно на бит Cipher.getInstance("AES");. Я переключился с RSA на "RSA/CBC/PKCS5Padding", но пока ничего не получилось.Недопустимое ключевое исключение при дешифровании ключа AES

Основная функция:

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"); 
    } 

Encrypt функция

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

Вы должны полностью изменить процесс шифрования для кодирования процесса расшифровки. В настоящее время вы шифруете ключ AES, используя RSA, а затем шифруете открытый текст для шифрования с использованием AES.

В процессе дешифрования вы только пытаетесь и расшифровываете зашифрованный текст с помощью AES. Сначала вы должны извлечь зашифрованный ключ AES, расшифровать его и затем расшифровать (остальную часть) зашифрованного текста с помощью AES для извлечения открытого текста.

Смежные вопросы