I was going through an IBM tutorial on encrypting using Private key. And I wrote the code as below
import java.security.*;
import javax.crypto.*;
// encrypt
Here's how you write your key to a file:
//Write your key to an output file.
byte[] keyAsByte = key.getEncoded();
FileOutputStream keyfos = new FileOutputStream("key.txt");
keyfos.write(keyAsByte);
keyfos.close();
I wouldn't recommend putting the key with the encrypted text in the same file.
Here's how you read the encrypted text and the key back and decrypt:
//Read your key
FileInputStream keyFis = new FileInputStream("key.txt");
byte[] encKey = new byte[keyFis.available()];
keyFis.read(encKey);
keyFis.close();
Key keyFromFile = new SecretKeySpec(encKey, "DES");
//Read your text
FileInputStream encryptedTextFis = new FileInputStream("test.txt");
byte[] encText = new byte[encryptedTextFis.available()];
encryptedTextFis.read(encText);
encryptedTextFis.close();
//Decrypt
Cipher decrypter = Cipher.getInstance("DES/ECB/PKCS5Padding");
decrypter.init(Cipher.DECRYPT_MODE, keyFromFile);
byte[] decryptedText = decrypter.doFinal(encText);
//Print result
System.out.println("Decrypted Text: " + new String(decryptedText));
Note: I didn't use the same path as you for writing the information.