2017-04-12 2 views
3

Je voudrais générer et stocker une clé HMacSHA256 à des fins de test dans le magasin de clés Java.Comment générer et stocker par programme la clé HMacSHA256 en Java?

je normalement faire via l'outil clé:

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

Jusqu'à présent, je trouve que je peux générer la clé en utilisant:

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

Cette clé est malheureusement pas une instance de PrivateKey et donc le stockage de la clé échoue:

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

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) 

Je crois que SecretKey représente une clé symétrique. Et PrivateKey fait partie d'une paire de clés privées et PublicKey. Y a-t-il un moyen de stocker une seule clé symétrique?

Répondre

3

Oui, vous pouvez. Mais jusqu'à la sortie de Java 9, les magasins de clés PKCS # 12 auront des fonctionnalités limitées. JCEKS magasins clés que vous utilisez dans la ligne de commande keytool ne supportent cependant les clés symétriques (HMAC):

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"); 
    } 
} 

devrait fonctionner correctement sur Java 8.