I am creating a DESede key and writing it to a file, but when I retrieve the value is not the same, so I can't decrypt the ciphertext.
With the following code I write the key to the file "keyFile":
SecretKey key=null;
try {
KeyGenerator generator = KeyGenerator.getInstance("DESede");
generator.init(new SecureRandom());
key = generator.generateKey();
byte[] keyBytes = key.getEncoded();
FileOutputStream keyfos = new FileOutputStream("keyFile");
keyfos.write(keyBytes);
keyfos.close();
} catch(Exception e) {
e.printStackTrace();
}
And with the the following I retrieve it from the file:
SecretKey key = null;
try {
FileInputStream in = new FileInputStream("keyFile");
StringBuffer keyString = new StringBuffer ();
int c = 0;
while((c = in.read ()) != -1)
keyString.append ((char)c);
byte[] keyBytes = keyString.toString().getBytes();
DESedeKeySpec spec = new DESedeKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
key = keyFactory.generateSecret(spec);
in.close();
} catch(Exception e){
e.printStackTrace();
}
Can you help me cope with my problem?
Thanks in advance.