Get private key from MacOS X keystore using Java
I'm trying to access my personal MacOS X keychain store to retrieve specific private keys to encrypt and sign some data using Java. The encrypting and signing part are functional, but I cannot retrieve the private keys I want. The following is some code I've wrote to present the issue I have:
KeyStore myKeyStore;
myKeyStore = KeyStore.getInstance("KeychainStore", "Apple");
myKeyStore.load(null, null);
// Get all the aliases in a list (I thought that calling the KeyStore
// methods during the iteration was the reason why getKey wasn't responding properly!)
// ... it wasn't actually!
ArrayList<String> aliases = new ArrayList<String>();
Enumeration<String> e = myKeyStore.aliases();
while (e.hasMoreElements()) {
aliases.add(e.nextElement());
}
for (String alias : aliases) {
try {
// I read on the Internet that any ASCII password is required
// to get the getKey method working.
Key k = myKeyStore.getKey(alias, "TEST".toCharArray());
if (k == null) {
System.out.println(alias + ": <null> (cannot retrieve the key)");
} else {
System.out.println(alias + ":");
System.out.println(k);
}
} catch (Exception ex) {
System.out.println(alias + ": " + ex.getMessage());
}
}
After executing that piece of code, I could see all the certificates in my personal keystore. However, I can only retrieve one private key, even though there are a bunch of them in the keystore. (the output of the code just shows multiple trusted certificates + one private key only)
And when I remove that private key from the keystore and execute that code again, another private key is returned, while all the others remain inaccessible. Importing the private key back in the keystore and executing that code one last time, it gets returned by Java, and the last private key that was previously returned becomes inacessible.
I've stumbl开发者_运维技巧ed upon a mailing list on that subject: http://lists.apple.com/archives/java-dev/2007/aug/msg00134.html. Unfortunately, it doesn't seem like that problem was resolved, and I cannot contact the persons involved (no e-mail addresses).
Has anyone tried to retrieve multiple private keys from the MacOS keychain store, and succeeded?
My configuration:
- MacOS X 10.6
- Jva JRE 1.6.0_15 (32 and 64bits)
- Safari 4.0.3
- Firefox 3.6.3
Thanks in advance,
Unfortunately this is a known limitation of the Apple KeyChain KeyStore implementation. There is an opened ticket in the OpenJDK MacOSX port bug tracker (MACOSX_PORT-464) and a patch has been submitted.
However either you will have to recompile OpenJDK from scratch (it takes a while but it is straightforward procedure) or you will have to extract the Keychain Cryptographic Service Provider from OpenJDK sources and build a new jar containing the standalone JCA provider (but it since it contains native code it is probably a much more complex task).
精彩评论