Search code examples
javakeystore

How can I store a program password in the OS keystore?


I am currently developing a Java application on a Mac. I know that there is the keystore from Apple and I want to securely store a password within that keystore.

According to Apple developers I can get the keystore with keyStore = KeyStore.getInstance("KeychainStore", "Apple");

Now my question is: How can I store the password and how can I get the password back again? I have read a lot about keystores but I do not know, how an implementation would look like.

And how can I get the built-in keystore from Windows / Linux?


Solution

  • java.security.KeyStore was not created to deal with passwords. It is a storage facility for cryptographic keys and certificates. While you can try to use it to store passwords since it can for example store private keys, I would advise you against that, because KeyStore's API is cumbersome and was not designed for your use case. https://docs.oracle.com/javase/8/docs/api/java/security/KeyStore.html

    How to store passwords in Windows, Linux or macOS

    What you need instead is Keychain in macOS and similar tools in other operating systems. Since you are also asking about Windows and Linux, you might be interested in the Java Keyring library. It stores passwords in:

    1. Keychain on macOS
    2. Credential Manager on Windows
    3. DBus Secret Service on GNOME

    Here's how to use it:

    public static void main(String[] args) throws Exception {
        Keyring keyring = Keyring.create();
        String serviceName = "test-app";
        String accountName = "test-account";
        keyring.setPassword(serviceName, accountName, "test-password");
        String password = keyring.getPassword(serviceName, accountName);
        System.out.println(password);
    }
    

    Gradle

    implementation 'com.github.javakeyring:java-keyring:1.0.1'
    

    Maven

    <dependency>
      <groupId>com.github.javakeyring</groupId>
      <artifactId>java-keyring</artifactId>
      <version>1.0.1</version>
    </dependency>
    

    If you want to support desktop environments other than GNOME you would probably have to come up with your own solution or search for a different library, but this should get you started.