title: How to store symmetric secret key in Java PKCS12 keystore
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>I found one article claiming that this should be possible: <a href="http://www.pixelstech.net/article/1420427307-Different-types-of-keystore-in-Java----PKCS12" rel="noreferrer">http://www.pixelstech.net/article/1420427307-Different-types-of-keystore-in-Java----PKCS12</a></p>
  
  <p>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().</p>
  
  <p>Does anyone know whether what I can meet these requirements using the PKCS12 keystore in Java? </p>
  
  <p>FWIW, here's the code:</p>
  
  <pre><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() );
  }
  </code></pre>
  
  <p><strong>EDIT:</strong> 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.</p>
  
  <p>Anyone encountered this same problem found a workable solution?</p>