gpt4 book ai didi

java - X509 RSA bouncy caSTLe 在 Java 中签署和验证纯文本

转载 作者:太空宇宙 更新时间:2023-11-03 13:23:38 27 4
gpt4 key购买 nike

我目前正在使用 BouncyCaSTLe 编写一个 Java 程序,该程序生成一个带有 RSA key 对的 X509 SSL 证书。

我已经能够成功创建 SSL 证书,但我还希望能够对任意纯文本进行签名,并使用该签名通过针对纯文本验证签名来验证 key 的所有权。

方法应该是这样的:

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);

关于java - X509 RSA bouncy caSTLe 在 Java 中签署和验证纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40877488/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com