Generating SSH keys

Generating an SSH key pair is a simple operation with the SshKeyPairGenerator class.

There are currently four types of public/private keys supported by the API. This article outlines the options available to create keys with the API’s SshKeyPairGenerator class.

There are two versions of the method generateKeyPair. Once takes a bit size parameter that allows you to pass the required bit size of the key. The other does not and will generate the default key size for you.

RSA

To generate an RSA key execute the following code

SshKeyPair pair = SshKeyPairGenerator.generateKeyPair(SshKeyPairGenerator.SSH2_RSA, 2048); 

The API will generate an RSA key as large as the JVM/JCE allows. The default key size is 2048, which should provide strong security until 2030. If you require keys that will live past 2030, 3072 bits are recommended.

ECDSA

To generate an RSA key, execute the following code

SshKeyPair pair = SshKeyPairGenerator.generateKeyPair(SshKeyPairGenerator.ECDSA, 256); 

The API will generate a 256-bit ECDSA key. You can also use 384 bits and 521 bits as arguments to generate higher bit lengths.

ED25519

ed25519 keys are ECDSA keys that are implemented using the Twisted Edwards curve. They are much smaller and faster than RSA keys, containing only 68 characters and offer better security.

Support for ed25519 may require an external third-party dependency. They will be supported if you have installed the maverick-bc module in your classpath or are using a Java version that supports them (Java 15+). Failure to do so will result in the following error at runtime:

Exception in thread "main" com.sshtools.common.ssh.SshException: ed25519 is not supported

You can install the maverick-bc with the following Maven dependency:

   <dependency>
      <groupId>com.sshtools</groupId>
       <artifactId>maverick-bc</artifactId>
       <version>3.1.0</version>
   </dependency>

Once installed, use the SskKeyPairGenerator.ED25519 algorithm type when generating keys. These keys only support a single-bit size, so the value passed is ignored. You can also use the generateKeyPair method that does not require a bit size to be passed. 

SshKeyPair pair = SshKeyPairGenerator.generateKeyPair(SshKeyPairGenerator.ED25519);

DSA

DSA keys are deprecated in the Maverick Synergy API. DSA keys are considered unsafe and are no longer supported with OpenSSH since version 7.

Storing Key Files

Once you have generated a key pair, you will want to store it somewhere. There are some handy methods available in SshKeyUtils to make this easy.

To save the public key file:

SshKeyUtils.createPublicKeyFile(pair.getPublicKey(),
       "Generated by Maverick Synergy", new File("key.pub"));

To save the private key file:

SshKeyUtils.createPrivateKeyFile(pair, "xxxxxx", new File("key"));