Generating SSH keys

Lee Painter

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.


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-bits which should provide strong security until 2030. If you require keys that will live past 2030 then 3072-bits is recommended.


ECDSA keys provide equal or better security than RSA for a smaller key size. The Maverick Synergy Java SSH API supports ECDSA key sizes of 256, 384 and 521-bits. Simply pass your chosen bit size through to the generateKeyPair function when generating a key. The default size for ECDSA is 256-bits.

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



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.

Because support for ed25519 requires an external third-party dependency you need to ensure you have installed the maverick-ed25519 module in your classpath. 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-ed25519 with the following Maven dependency:


Once installed, just 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 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:

"Generated by Maverick Synergy", new File(""));

To save the private key file:

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