用X509证书签名 java代码
时间: 2023-12-21 15:07:18 浏览: 129
以下是使用 Java 进行 X.509 证书签名的示例代码:
```java
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
public class X509CertSigner {
public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// 生成密钥对
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 读取证书文件
InputStream inStream = new FileInputStream("cert.crt");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
inStream.close();
// 签名原始数据
byte[] data = "Hello, world!".getBytes();
Signature signature = Signature.getInstance("SHA256withRSA", "BC");
signature.initSign(keyPair.getPrivate());
signature.update(data);
byte[] signedData = signature.sign();
// 验证签名
signature.initVerify(cert);
signature.update(data);
boolean verified = signature.verify(signedData);
System.out.println("Signature verified: " + verified);
}
}
```
在此示例中,我们使用了 Bouncy Castle 作为加密提供程序。首先,我们生成一个 RSA 密钥对,然后读取一个 X.509 证书文件。接下来,我们使用 SHA256withRSA 签名算法对数据进行签名,并使用证书进行验证。
阅读全文