Search code examples
ssh-keysapache-sshd

How to add public key identity from String?


I have a Spring Boot application with Apache SSHD. The application should use SSH Public Key Authentication. Therefore, the application needs a private key. How to provide this private key?

For security reasons, the private key should not be saved in the

  • source code (in Git)
  • classpath (in JAR)
  • image (in Docker Registry)
  • host/volume (with Docker Mount)

Instead the private key should be provided as an environment variable (with GitLab).

Documentation

In the documentation is only an example for private keys saved in the filesystem, see Loading key files:

Loading key files

In order to use password-less authentication the user needs to provide one or more KeyPair-s that are used to "prove" the client's identity for the server. The code supports most if not all of the currently used key file formats. See SshKeyDumpMain class for example of how to load files - basically:

KeyPairResourceLoader loader = SecurityUtils.getKeyPairResourceParser();
Collection<KeyPair> keys = loader.loadKeyPairs(null, filePath, passwordProvider);

Research

I could create the the KeyPair as described in create java PrivateKey and PublicKey from a String of file, but then I would reimplement an existing part of Apache SSHD. I have to support all of the currently used key file formats.

Question

How to load private key from String instead of filesystem?


Solution

  • I found a way to use a String instead of a file, see KeyPairResourceLoader#loadKeyPairs:

    default Collection<KeyPair> loadKeyPairs(SessionContext session,
                                        NamedResource resourceKey,
                                        FilePasswordProvider passwordProvider,
                                        String data)
                                 throws IOException,
                                        GeneralSecurityException
    

    Throws:
    IOException
    GeneralSecurityException

    My changed code:

    KeyPairResourceLoader loader = SecurityUtils.getKeyPairResourceParser();
    Collection<KeyPair> keyPairCollection = loader.loadKeyPairs(null, null, null, pem);