RyanSoper
RyanSoper

Reputation: 231

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?

Upvotes: 8

Views: 20679

Answers (3)

Sanjeev
Sanjeev

Reputation: 1575

Not clear on a couple of things: how you're generating the key, and what format you have the key in. If you don't have the key you can use keytool (a utility which comes with jdk) to generate it and put it into a file called a keystore. You can also use the KeyGenerator class and the KeyStore class to programmatically do the same thing (both are documented pretty well and the KeyStore javadoc has an example which does exactly what you seem to want.)

A much less secure but easy way you can generate the key and put it into a text file as clear text. Then you can just access it using a BufferedReader. This is less secure because anyone with access to this file will know your key, but it's a little easier.

Upvotes: 2

Mike Samuel
Mike Samuel

Reputation: 120576

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.

Upvotes: 10

Bruno
Bruno

Reputation: 122749

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).

Upvotes: 7

Related Questions