封装签名和验签两个方法验证不成功
// 签名方法
public static String jdkRSASign(String src) {
String result = null;// 签名结果
try {
// 1.初始化秘钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(512);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();// 私钥
// 2.执行签名
PKCS8EncodedKeySpec pkcS8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcS8EncodedKeySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(privateKey);
signature.update(src.getBytes("UTF-8"));
result = new String(signature.sign(),"UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// 验签名方法
public static boolean jdkRSACheck(String src, String sign) {
boolean result = false;
try {
// 1.初始化秘钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(512);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();// 公钥
// 2.验证签名
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initVerify(publicKey);
signature.update(src.getBytes("UTF-8"));
result = signature.verify(sign.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
return result;
}