JSch:从私钥文件创建 public 密钥

JSch: Create public key from private key file

我喜欢通过作为 KeyPair 的一部分创建的 QR 码(除了最佳安全实践)传输私钥,之后需要恢复 KeyPair。因此

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

pub_data.equals(pub_data2)并没有按照你的想法去做。它比较引用,而不是数组内容。你想使用 Arrays.equals(pub_data, pub_data2).

equals vs Arrays.equals in Java


顺便说一句,从技术上讲,您不能从私钥 创建 a public 密钥。但由于 KeyPair.writePrivateKey 实际上写了 整个密钥对 ,而不仅仅是私钥,它自然也包含 public 密钥。