I like to transmit a private key via QR code (best security practices aside) that was created as part of a KeyPair
and need to recover the KeyPair
afterwards. Thus
JSch jsch = new JSch();
KeyPair keypair = KeyPair.genKeyPair(jsch, KeyPair.RSA, 4096);
ByteArrayOutputStream prvstream = new ByteArrayOutputStream();
keypair.writePrivateKey(prvstream);
prvstream.close();
ByteArrayOutputStream pubstream = new ByteArrayOutputStream();
keypair.writePublicKey(pubstream, null /* key comment */);
pubstream.close();
byte[] prv_data = prvstream.toByteArray();
byte[] pub_data = pubstream.toByteArray();
// prv_data is transferred via QR-Code here
KeyPair keypair2 = KeyPair.load(jsch, prv_data, null);
ByteArrayOutputStream prvstream2 = new ByteArrayOutputStream();
keypair2.writePrivateKey(prvstream2);
prvstream2.close();
ByteArrayOutputStream pubstream2 = new ByteArrayOutputStream();
keypair2.writePublicKey(pubstream2, null /* key comment */));
pubstream2.close();
byte[] prv_data2 = prvstream2.toByteArray();
byte[] pub_data2 = pubstream2.toByteArray();
if (pub_data.equals(pub_data2) {
// success
} else {
// we hit failure here every time.
}