Re: public/private key

Jan Luehe (Jan.Luehe@Eng)
Tue, 21 Oct 1997 09:51:21 -0700 (PDT)

Date: Tue, 21 Oct 1997 09:51:21 -0700 (PDT)
From: Jan Luehe <Jan.Luehe@Eng>
Subject: Re: public/private key
To: java-security@web2.javasoft.com,

Harish:

> It is possible to store instances of PublicKey/PrivateKey in files
> since these interfaces are serializable. But when I read these objects again
> from the file, using readObject method of ObjectInputStream and then
> typecasting the object returned to public/private key, then I get a Cast
> exception.

Hmm, I tried the same (see test program below), and do not get any errors.
(I am using JDK1.2beta1. Which version are you using?)

> Is it possible to store public/private keys into persistent storage
> and then retrieve it again.

Use the following sample program to serialize a PrivateKey,
store it in a file, and retrieve it from there.

Run the program as follows:

java Test <filename>

The program's output should be:

"privKey = DSA"


Please let me know if this works for you.

Thanks,

Jan

------------------------------------------------------------------

import java.io.*;
import java.security.*;

public class Test {
public static void main(String[] args) {
try {
// create and initialize key pair generator
KeyPairGenerator kGen = KeyPairGenerator.getInstance("DSA");
kGen.initialize(512, new SecureRandom());

// generate key pair
KeyPair kp = kGen.generateKeyPair();

// get the private key
PrivateKey privKey = (PrivateKey)kp.getPrivate();

// serialize private key, and store it in file
FileOutputStream fos = new FileOutputStream(args[0]);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(privKey);
oos.flush();
oos.close();

// read serialized key from file, and de-serialize it
FileInputStream fis = new FileInputStream(args[0]);
ObjectInputStream ois = new ObjectInputStream(fis);
privKey = (PrivateKey)ois.readObject();

// print out the key's algorithm
System.out.println("privKey = "+privKey.getAlgorithm());
} catch (Exception e) {
System.err.println("Error" + e);
}
}
}