Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Problems with PrivateKey

843811Apr 24 2007 — edited Apr 26 2007
Hi all,

I'm really struggling here and I'm hoping someone can help. I'm no security expert so please forgive any obvious errors.

I want to create a public and private key pair, then use a KeyStore to store them so other objects can access them. However, I'm having a problem and here is the code I'm working with:
 // Generate and get the public and private keys
  keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(512);
  keypair = keyGen.genKeyPair();
  thisPrivateKey = keypair.getPrivate();
  thisPublicKey = keypair.getPublic();

  // Create a empty keystore object
  KeyStore keystore = KeyStore.getInstance("JCEKS");

  // store the public key
  keystore.load(null,"PublicPass".toCharArray());
  keystore.setKeyEntry("PublicKeys", thisPublicKey, "PublicPass".toCharArray(), null);
  FileOutputStream out = new FileOutputStream("Keys\\Public.key");
  keystore.store(out, "PublicPass".toCharArray());
  out.close();

  // store the private key
  keystore.setKeyEntry("PrivateKeys", thisPrivateKey, "PrivatePass".toCharArray(), null);
  FileOutputStream out = new FileOutputStream("Keys\\Private.key");
  keystore.store(out, "PrivatePass".toCharArray());
  out.close();
This fails when run because it says it need a Certificate chain in the setKeyEntry routine (fourth parameter). Okay, so then I started trying to create a certificate chain and this is what I've come up with.
  // Get and test the certificate chain
  java.security.cert.Certificate[] chain = keystore.getCertificateChain("PublicKeys");
  String theType = chain.getType();
  System.out.println("theType="+theType);
 
  // store the private key
  keystore.setKeyEntry("PrivateKeys", thisPrivateKey, "PrivatePass".toCharArray(), chain);
  FileOutputStream out = new FileOutputStream("Keys\\Private.key");
  keystore.store(out, "PrivatePass".toCharArray());
  out.close(); 
However, this fails because the certificate chain always comes back as null. Why? I'm not sure I fully understand what kind of alias it's looking for in the getCertificateChain call. Or perhaps it's returning null because there's no chain to get as it hasn't been assigned yet. If so, how does one generate a certificate so that it can be assigned to an alias (via setCertificateEntry) and then getCertificateChain will work. All examples of setCertificateEntry I've been able to find are reading the keys in from a KeyStore, but how does one get an initial certificate?

Thanks to anyone who can help.

Robert

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 24 2007
Added on Apr 24 2007
4 comments
682 views