mwarning
mwarning

Reputation: 771

JSch: Create public key from private key file

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.
}

Upvotes: 1

Views: 423

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202292

pub_data.equals(pub_data2) does not do what you think. It compares the references, not the array contents. You want to use Arrays.equals(pub_data, pub_data2).

See equals vs Arrays.equals in Java.


Btw, technically you cannot create a public key from a private key. But as KeyPair.writePrivateKey actually writes a whole key pair, not the private key only, it naturally contains the public key too.

Upvotes: 1

Related Questions