計算和驗證數字簽名
要計算簽名:
final PrivateKey privateKey = keyPair.getPrivate();
final byte[] data = "FOO BAR".getBytes();
final Signature signer = Signature.getInstance("SHA1withRSA");
signer.initSign(privateKey);
signer.update(data);
final byte[] signature = signer.sign();
請注意,簽名演算法必須與用於生成金鑰對的演算法相容。
驗證簽名:
final PublicKey publicKey = keyPair.getPublic();
final Signature verifier = Signature.getInstance("SHA1withRSA");
verifier.initVerify(publicKey);
verifier.update(data);
System.out.println("Signature: " + verifier.verify(signature));
生成此輸出:
Signature: true