java读取jks证书获取私钥和公钥/签名和验签

环境

WINDOWS OS
jdk 1.8_64

获取公钥和私钥

String jksPath = ""; //jks file path
String jksPassword = ""; // jks keyStore password
String certAlias = ""; // cert alias
String certPassword = ""; // cert password
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream(jksPath), jksPassword.toCharArray());
PriateKey privateKey = (PrivateKey) keyStore.getKey(certAlias, certPassword.toCharArray());
PublicKey publicKey = keyStore.getCertificate(certAlias).getPublicKey();

签名

String signData = ""; //需要签名的内容
String signAlg = "SHA256withRSA"; //签名类型
Signature signature = Signature.getInstance(signAlg);
signature.initSign(privateKey);
signature.update(signData.getBytes());
String signedData = Base64.getEncoder().encodeToString(signature.sign().replace("\r\n","").replace("\n",""));

验签

String signData = ""; //需要签名的内容
String signedData = ""; //签名后的内容
String signAlg = "SHA256withRSA"; //签名类型
Signature signature = Signature.getInstance(signAlg);
signature.initVerify(publicKey);
signature.update(signData.getBytes());
boolean isVerify = signature.verify(Base64.getDecoder().decode(signedData));

你可能感兴趣的:(java读取jks证书获取私钥和公钥/签名和验签)