Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and Writing a SecretKey to a file

I'm looking to be able to save a DES SecretKey to a file, so you can import and use it later on. I've looked at a few routes, but they all seem a bit long winded, is there no conscise simple way of doing this?

like image 566
RyanSoper Avatar asked May 10 '12 15:05

RyanSoper


2 Answers

The most "natural" way to save a SecretKey into a file in Java is to use a KeyStore: that's exactly what it's for (although you can save certificates too, of course).

The example in the documentation shows how to save a private key and a secret key. It will also encrypt it with a protection parameter (password here).

like image 113
Bruno Avatar answered Sep 18 '22 01:09

Bruno


javax.crypto.SecretKey extends java.security.Key

java.security.Key extends java.io.Serializable

So if you trust the file-system to which you're storing keys, you can write out a key using java.io.ObjectOutputStream and read it in using java.io.ObjectInputStream.

ObjectOutputStream oout = new ObjectOutputStream(outputStream);
try {
  oout.writeObject(myKey);
} finally {
  oout.close();
}

and the input looks similar

Key key;
ObjectInputStream oin = new ObjectInputStream(inputStream);
try {
  key = (Key) oin.readObject();
} finally {
  oin.close();
}

To generate a key, you need a KeyFactory or SecretKeyFactory

SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);

and then to generate a secret

factory.generateSecret(keySpec);

given a key spec that is appropriate to the algorithm. See the KeySpec javadoc for pointers to algorithm specific KeySpec implementations.

For DES, see DESKeySpec though you might want something more modern.

like image 31
Mike Samuel Avatar answered Sep 18 '22 01:09

Mike Samuel