As I understand it, if I do:

keytool -genkeypair -alias foo

it creates, in one step, certificate, a private key, and a public key.

That's great. Now I can export the public portions of the certificate (the information about the subject of the certificate, and the public key), in a 'Privacy Enhanced Mail' (PEM) format as per RFC 1421 by doing:

keytool -exportcert -alias foo -rfc > mycert.cer

I can now give mycert.cer to the party that needs to verify signatures I generate with the private key. That private key remains private in the keystore (both the key and the store can be encrypted with a passphrase).

Finally, it just remains to obtain the private key from the keystore at runtime in my program so that I can sign stuff such that the other party can verify I signed it.

The guts of that (relying on the KeyStore doc as cheered along by Dr Heron Yang) is:

// load the keystore, supplying the store password
KeyStore jks = KeyStore.getInstance("JKS");
jks.load(new FileInputStream(jksFile), jksPass);

// get the 'entry'
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(password);
KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)
    ks.getEntry("foo", protParam);

// grab the bits from the private key
PrivateKey myPrivateKey = pkEntry.getPrivateKey();

Now I could hand myPrivateKey (assuming it was the right sort of key, of course), to something like:

  // import java.security.*
  Signature sig = Signature.getInstance("SHA1withRSA");
  sig.initSign(myPrivateKey);
  sig.update(mybytes);
  return sig.sign();

and I thus generate a signature which my other party (assuming they trust the certificate I supplied them before and can associate it with stuff I send them) can use to verify that it was really me who gave them the data.

(Yes, I glossed over key types generating the cert with keytool earlier).

Is this how it is done? So many other examples are extraordinarily zealous to get the certificate and the private key out of the java keystore so they can:

  • paste the plain-text of the private key into their code (in PEM format)
  • include the plain-text of the private key (in PEM format) as a file to be checked-in to the source code repository
  • otherwise publish their private key

OR if the developer has some kind of clue, they are now faced with the problem of protecting the private key, now that they've managed to get it out of the keystore! (This is where I was before I had a lightbulb moment!).

1

There are 1 answers

0
David Bullock On

Yes! The above process works a charm and feels right to boot.