我目前正在使用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;
}
}
答案 0 :(得分:0)
找到解决方案:
签署:
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);