My goal is to write a Java program to encrypt a text file ( cipher text ) using the AES algorithm . Then write another program to decrypt this encrypted file ( cipher text ) to return plain text. I want to use the same key (the same key, generate it once, save it somewhere and use it both in the encryption program and for decryption) for encryption and decryption. If I generate a key and perform encryption and decryption line by line in the same program, then it works fine. Here is a working code snippet for this:
String strDataToEncrypt = new String(); String strCipherText = new String(); String strDecryptedText = new String(); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); Cipher aesCipher = Cipher.getInstance("AES"); aesCipher.init(Cipher.ENCRYPT_MODE,secretKey); strDataToEncrypt = "any text input"; byte[] byteDataToEncrypt = strDataToEncrypt.getBytes(); byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt); strCipherText = new BASE64Encoder().encode(byteCipherText); System.out.println("cipher text: " +strCipherText); aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters()); byte[] byteDecryptedText = aesCipher.doFinal(new BASE64Decoder().decodeBuffer(strCipherText)); strDecryptedText = new String(byteDecryptedText); System.out.println("plain text again: " +strDecryptedText);
But for encryption and decryption, I need to have two different programs (java files). So, I have to somehow generate the key and save it somewhere. Then use the same key for the encryption and decryption program. How can i do this?
EDIT_1
KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); byte[] encoded = secretKey.getEncoded(); System.out.println("key: "+encoded);
I can get the value of the encoded key using the above program. But my question is how to generate SecretKey using this value in my decryption program?
java cryptography aes secret-key
KM Rakibul Islam Nov 27 '13 at 4:14 2013-11-27 04:14
source share