How to use SSH Public Keys in Java

Introduction

SSH uses public keys for host identification and user authentication. This page provides several examples in the form of snippets for how to use public keys in the Maverick Synergy Java SSH API.

Generating SSH Keys in Java

Generate an ED25519 Private Key:

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

Generate an RSA Private Key:

SshKeyPair rsa = SshKeyPairGenerator.generateKeyPair(SshKeyPairGenerator.RSA, 4096);

Saving SSH Keys in Java

Saving a Private Key to file:

SshKeyUtils.createPrivateKeyFile(ed25519, "passphrase_text", new File(".ssh/id_ed25519"));

Saving a Public Key to file:

SshKeyUtils.createPublicKeyFile(ed25519.getPublicKey(), "Generated by Maverick Synergy", new File(".ssh/id_ed25519.pub"));

Loading SSH Keys in Java

Loading a Private Key from a file, passing the passphrase as a String:

SshKeyPair pair = SshKeyUtils.getPrivateKey(new File(".ssh/id_rsa"), "passphrase_text");

Get the Public Key from the Private Key:

SshPublicKey pub = pair.getPublicKey();

Loading a Public Key from file:

SshPublicKey pub = SshKeyUtils.getPublicKey(new File(".ssh/id_rsa.pub"));

Verifying SSH Keys in Java

Generate the SSH Key Fingerprint of a Public Key:

String fingerprint = SshKeyUtils.getFingerprint(pub);

Generate the Bubblebabble fingerprint of a Public Key:

String bubblebabble = SshKeyUtils.getBubbleBabble(pub);