Reading and writing SecretKey file to file

I am looking to save a DES SecretKey file in a file so that you can subsequently import and use it. I looked through several routes, but they all seem a bit long, is there an easy way to do this?

+5
source share
3 answers

It is not clear for several things: what do you consider to be a “long coiler”, how do you generate a key and what format do you have. If you don't have a key, you can use keytool (the utility that comes with jdk) to generate it and put it in a file called a keystore. You can also use the KeyGenerator class and the KeyStore class to do the same programmatically (both documents are well-documented, and KeyStore javadoc has an example that does exactly what you think is needed.)

If it is a long branch, you can generate a key and put it in a text file as clear text. Then you can just access it using BufferedReader. This is less secure, because anyone who has access to this file will know your key, but it's a little easier.

+2

"" SecretKey Java - a KeyStore: , ( , ).

, . ( ).

+4

javax.crypto.SecretKey extends java.security.Key

java.security.Key extends java.io.Serializable

, , , java.io.ObjectOutputStream java.io.ObjectInputStream.

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

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

, KeyFactory SecretKeyFactory

SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);

factory.generateSecret(keySpec);

, . . KeySpec javadoc KeySpec.

DES . DESKeySpec, - more .

+3

All Articles