How to create Java Key Store (.jks) file with AES encryption

后端 未结 4 1345
栀梦
栀梦 2021-02-03 16:12

Reading Oracle documentation, I see that by default JKS files are encrypted using PBEWithMD5AndTripleDES. While DES alone makes me feel uneasy, MD5 lights a big red

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-03 17:02

    Since Java 8, you can create a PKCS#12 keystore and pass an explicit PasswordProtection parameter when storing a key to specify the encryption algorithm to use:

    import java.io.FileOutputStream;
    import java.security.KeyStore;
    import java.security.KeyStore.PasswordProtection;
    import java.security.KeyStore.PrivateKeyEntry;
    import java.security.PrivateKey;
    import java.security.SecureRandom;
    import java.security.cert.Certificate;
    
    import javax.crypto.spec.PBEParameterSpec;
    
    public class scratch {
        public static void main(String... args) throws Exception {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(null, null); // Initialize a blank keystore
    
            // Your key to store
            PrivateKey key = ...;
            Certificate[] chain = new Certificate[] { ... };
    
            char[] password = "changeit".toCharArray();
            byte[] salt = new byte[20];
            new SecureRandom().nextBytes(salt);
            keyStore.setEntry("test", new PrivateKeyEntry(key, chain),
                              new PasswordProtection(password,
                                                     "PBEWithHmacSHA512AndAES_256",
                                                     new PBEParameterSpec(salt, 100_000)));
    
            keyStore.store(new FileOutputStream("/tmp/keystore.p12"), password);
        }
    }
    

    You can read a bit more on the details in this article (dislaimer: I wrote that article).

提交回复
热议问题