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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With