Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store symmetric secret key in Java PKCS12 keystore

I need a secure store for symmetric keys that works for both .NET and Java. I need to be able to store and retrieve HmacSha* keys from the same store in both languages, programmatically, not via command line tools.

My first attempt at this was generating and storing a key from Java using the PKCS12 keystore, which is a portable format, and one which I would have thought supports storing secret keys as well as private keys for X.509 certs.

My experience so far, though, is that it does not (NOTE: Java SE 6), throwing an exception on calls to java.security.KeyStore.setKeyEntry(), complaining that the key I'm trying to store is not a PrivateKey.

I found one article claiming that this should be possible: http://www.pixelstech.net/article/1420427307-Different-types-of-keystore-in-Java----PKCS12

But, if I pull the example code from that article (the example under the section titled "Store secret key"), I get the same exception on the same call to setKeyEntry().

Does anyone know whether what I can meet these requirements using the PKCS12 keystore in Java?

FWIW, here's the code:

public void gen( String thePath, String thePassword ) throws Exception {
    KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA1");
    Key key = keygen.generateKey();

    KeyStore keystore = KeyStore.getInstance("PKCS12");
    keystore.load(null, null);

    // This call throws an exception
    keystore.setKeyEntry("theKey", key, thePassword.toCharArray(), null);
    keystore.store( new FileOutputStream(thePath), thePassword.toCharArray() );
}

EDIT: Hmmm - looking into this on the .NET side reveals that there is also no direct programmatic support for importing/exporting symmetric keys using the PKCS12 format. It seems like the best supported approach would be to have an X.509 key pair that is used to encrypt the symmetric key, and to store/transport that pair in a PKCS12 file, together with the encrypted symmetric key, to any other system that needs to use the symmetric key.

Anyone encountered this same problem found a workable solution?

like image 727
Hoobajoob Avatar asked Sep 28 '22 16:09

Hoobajoob


1 Answers

The KeyStore implementations of Java SE have gained a lot of attention in the later releases. Your code should run fine on Java SE 8 for JCEKS key stores, but not on Java SE 7.

You probably need to wait for Java 9 for PKCS#12 support. Java 9 will focus on support for PKCS#12 key stores.

like image 123
Maarten Bodewes Avatar answered Dec 23 '22 19:12

Maarten Bodewes