How to store a simple key string inside Java KeySt

2019-02-09 17:49发布

I have a file on my FS (a S3 AWS key) that contains a string that is a key I use for encryption process.

I would like to move it a Java KeyStore.

I know how to import a certificate into a KeyStore with keytool but I can't find the way to import a simple string key.

Can you help?

标签: java keystore
3条回答
ら.Afraid
2楼-- · 2019-02-09 18:10

You can not import in the key store arbitrary strings. In the key store you import certification keys that java libraries are using for authentication of remote hosts.

查看更多
Anthone
3楼-- · 2019-02-09 18:21

I don't see a way to do it with keytool, but some poking about, I wonder if you could store and retrieve it in code as a PasswordBasedEncryption (PBE) SecretKey. (Disclaimer: I haven't tried this myself).

The resources that drove this thought: PBEKeySpec javadoc and CryptoSpec - Using Password Based Encryption example

查看更多
劳资没心,怎么记你
4楼-- · 2019-02-09 18:30

You can do this with PBE and JCEKS. I don't think you can do it with JKS. Solution:

Create a keystore to store and get entries from:

keytool -keystore clientkeystore -genkey -alias client -storetype jceks

Now some code to test it out.

   public static String getPasswordFromKeystore(String entry, String keystoreLocation, String keyStorePassword) throws Exception{

        KeyStore ks = KeyStore.getInstance("JCEKS");
        ks.load(null, keyStorePassword.toCharArray());
        KeyStore.PasswordProtection keyStorePP = new KeyStore.PasswordProtection(keyStorePassword.toCharArray());

        FileInputStream fIn = new FileInputStream(keystoreLocation);

        ks.load(fIn, keyStorePassword.toCharArray());

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE");

        KeyStore.SecretKeyEntry ske =
                (KeyStore.SecretKeyEntry)ks.getEntry(entry, keyStorePP);

        PBEKeySpec keySpec = (PBEKeySpec)factory.getKeySpec(
                ske.getSecretKey(),
                PBEKeySpec.class);

        char[] password = keySpec.getPassword();

        return new String(password);

    }

    public static void makeNewKeystoreEntry(String entry, String entryPassword, String keyStoreLocation, String keyStorePassword)
            throws Exception {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE");
        SecretKey generatedSecret =
                factory.generateSecret(new PBEKeySpec(
                        entryPassword.toCharArray()));

        KeyStore ks = KeyStore.getInstance("JCEKS");
        ks.load(null, keyStorePassword.toCharArray());
        KeyStore.PasswordProtection keyStorePP = new KeyStore.PasswordProtection(keyStorePassword.toCharArray());

        ks.setEntry(entry, new KeyStore.SecretKeyEntry(
                generatedSecret), keyStorePP);

        FileOutputStream fos = new java.io.FileOutputStream(keyStoreLocation);
        ks.store(fos, keyStorePassword.toCharArray());
    }
查看更多
登录 后发表回答