Java双向认证的签名与验签
MUEDSA,•Development
使用证书进行验签
Signature sign = Signature.getInstance(certificate.getSigAlgName());
sign.initVerify(certificate);
sign.update(被签名的数据);
boolean success = sign.verify(数据的签名);
使用私钥进行签名
Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(privateKey);
sign.update(要签名的数据);
byte[] signData = sign.sign();
加载PKC12文件并获取私钥
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(fileInputStream, PRIVATE_KEY_STORE_PASSWORD);
if(keyStore.getKey(alias, PRIVATE_KEY_PASSWORD) instanceof PrivateKey privateKey){
//todo privateKey something
}
加载PEM文件(base64)获取私钥
// inputStream read to string var base64Str
base64Str = base64Str.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").replaceAll("\\s+", "");
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64Str)));
加载证书
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Certificate certificate = factory.generateCertificate(inputStream);
if(certificate instanceof X509Certificate x509Certificate) {
//todo x509Certificate something
}