私钥计算
public static PrivateKey getPrivateKey(String key) {
byte[] keyBytes;
keyBytes = java.util.Base64.getDecoder().decode(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory;
try {
keyFactory = KeyFactory.getInstance("RSA");
PrivateKey priKey;
priKey = keyFactory.generatePrivate(keySpec);
return priKey;
} catch (InvalidKeySpecException e) {
System.out.println("InvalidKeySpecException[私钥]:" + e.getStackTrace());
}catch (NoSuchAlgorithmException e) {
System.out.println("NoSuchAlgorithmException[私钥]:" + e.getStackTrace());
}
return null;
}
公钥计算
public static PublicKey getPublicKey(String key) {
byte[] keyBytes;
keyBytes = java.util.Base64.getDecoder().decode(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory;
try {
keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey;
pubKey = keyFactory.generatePublic(keySpec);
return pubKey;
} catch (InvalidKeySpecException e) {
System.out.println("InvalidKeySpecException[公钥]:" + e.getStackTrace());
}catch (NoSuchAlgorithmException e) {
System.out.println("NoSuchAlgorithmException[公钥]:" + e.getStackTrace());
}
return null;
}
用md5生成内容摘要,再用RSA的私钥加密,进而生成数字签名
static String getMd5Sign(String content , PrivateKey privateKey) throws Exception {
byte[] contentBytes = content.getBytes("utf-8");
// 返回MD5withRSA签名算法的 Signature对象
Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(privateKey);
signature.update(contentBytes);
byte[] signs = signature.sign();
return Base64.encodeBase64String(signs);
}
对用md5和RSA私钥生成的数字签名进行验证
static boolean verifyWhenMd5Sign(String content, String sign, PublicKey publicKey) throws Exception {
byte[] contentBytes = content.getBytes("utf-8");
Signature signature = Signature.getInstance("MD5withRSA");
signature.initVerify(publicKey);
signature.update(contentBytes);
return signature.verify(Base64.decodeBase64(sign));
}
测试
public static void main(String[] args) throws Exception {
String content = "ZGF0YT17ImJhdGNoTnVtYmVyIjoiMjAyMTA0MjUxMzM3MDExMTAxMD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ZxZpyFNMiF4B14pVzPTuNMTTbu4Jqt2g0I6QoAes/y+WRAc65z6CTAkEAo733B3m15KPybX3NbrlXyBArce+hQkpJ0369M4X70J3imMj9hotuS4bQO2F2kSEBrdAVWxC4hYZ11DRTlwe9CQJBAK3LEmKPNbXsSAbkSbc6d2U1cY9CEZR8WLkwfeVPGQ70gxcyFMa8F1wVB63VojpQCXkpRmUma25XLkT8kczRzPsCQQD130tvHXHd0YQw0qhBRZyO/ZbWUrWhFhl/MJwKOL+xAWhwA27dv7DyLkEFIImHiVK1vlwClt6NrQpOupNHOsrL");
String md5Sign = getMd5Sign(content,privateKey);
System.out.println("MD5withRSA算法的签名 :"+ md5Sign);
boolean md5Verifty = verifyWhenMd5Sign(content,md5Sign,publicKey);
System.out.println("MD5withRSA算法的签名验签结果 :"+ md5Verifty);
}