我目前正在使用Bouncycastle编写一个Java程序,该程序使用RSA键对生成X509 SSL证书。
我已经能够成功创建SSL证书,但我也希望能够签署任意纯文本,并通过该签名来验证钥匙的所有权,通过验证针对纯文本的签名。
这些方法应该看起来像这样:
protected String SignData(String privateKey, String text)
{
//return a signature
}
和
protected boolean verifySignature(String text, String signature, String pubKey)
{
//return either true or false depending on whether the signature is valid or not
}
我使用以下内容成功生成了自签名的SSL证书:
protected X509Certificate generateCert()
{
try
{
Security.addProvider(new BouncyCastleProvider());
// generate a key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(4096, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// build a certificate generator
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
X500Principal dnName = new X500Principal("cn=example");
// add some options
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setSubjectDN(new X509Name("dc=name"));
certGen.setIssuerDN(dnName); // use the same
// yesterday
certGen.setNotBefore(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000));
// in 2 years
certGen.setNotAfter(new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000));
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));
// finally, sign the certificate with the private key of the same KeyPair
X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");
return cert;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
找到解决方案:
签名:
Signature rsaSign = Signature.getInstance("SHA256withRSA", "BC");
rsaSign.initSign(pair.getPrivate());
rsaSign.update(plaintext.getBytes("UTF-8"));
byte[] signature = rsaSign.sign();
return signature;
验证:
rsaVerify = Signature.getInstance("SHA256withRSA", "BC");
rsaVerify.initVerify(pubKey);
rsaVerify.update(plaintext.getBytes("UTF-8"));
return rsaVerify.verify(signature);