How do I programmatically generate and store an HMacSHA256 key in Java?

I would like to generate and store an HMacSHA256 key for testing in a Java key store.

I usually do this with keytool:

keytool -genseckey -keystore keystore.jceks -storetype jceks -storepass secret -keyalg HMacSHA256 -keysize 2048 -alias HS256 -keypass secret

      

So far I have found that I can generate a key using:

SecretKey key = new SecretKeySpec("secret".getBytes(), "HmacSHA256");   

      

This key, unfortunately, is not an instance PrivateKey

and hence no key persistence is performed:

    KeyStore ks = ...
    ks.setEntry("HS256", new SecretKeyEntry(key), new PasswordProtection("secret".toCharArray()));

      

An exception:

java.security.KeyStoreException: Cannot store non-PrivateKeys
    at sun.security.provider.JavaKeyStore.engineSetKeyEntry(JavaKeyStore.java:258)
    at sun.security.provider.JavaKeyStore$JKS.engineSetKeyEntry(JavaKeyStore.java:56)
    at java.security.KeyStoreSpi.engineSetEntry(KeyStoreSpi.java:550)
    at sun.security.provider.KeyStoreDelegator.engineSetEntry(KeyStoreDelegator.java:179)
    at sun.security.provider.JavaKeyStore$DualFormatJKS.engineSetEntry(JavaKeyStore.java:70)
    at java.security.KeyStore.setEntry(KeyStore.java:1557)
    at com.gentics.mesh.SecretKeyTest.testSHA(SecretKeyTest.java:31)

      

I believe that SecretKey

represents a symmetric key. And it PrivateKey

is part of the pair PublicKey

and Private-Key. Is there a way to keep one symmetric key?

+3


source to share


1 answer


Yes, you can. But until Java 9 arrives, PKCS # 12 keystores will be limited in functionality. JCEKS keystores, as you use on the command line keytool

, still support symmetric keys (HMACs):

public class HMACKeyStore {
    public static void gen( String thePath, String thePassword ) throws Exception {
        KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA256");
        SecretKey key = keygen.generateKey();

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

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

        SecretKey keyRetrieved = (SecretKey) keystore.getKey("theKey", thePassword.toCharArray());
        System.out.println(keyRetrieved.getAlgorithm());
    }

    public static void main(String[] args) throws Exception {
        gen("hmac_store.jceks", "password");
    }
}

      



should work fine in Java 8.

+3


source







All Articles