java读取sm2证书
时间: 2023-09-18 08:07:04 浏览: 172
读取SM2证书需要使用Bouncy Castle库,以下是Java代码示例:
```java
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import java.io.FileReader;
import java.security.KeyFactory;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECNamedCurveParameterSpec;
import java.security.spec.ECPublicKeySpec;
public class SM2CertReader {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
// 读取证书
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new FileReader("sm2_cert.pem"));
// 读取公钥
SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(cert.getPublicKey().getEncoded());
AlgorithmIdentifier algId = spki.getAlgorithm();
ASN1ObjectIdentifier oid = algId.getAlgorithm();
if (!oid.getId().equals("1.2.840.10045.2.1")) {
throw new IllegalArgumentException("Expecting SM2 public key");
}
byte[] publicKeyBytes = spki.getPublicKeyData().getBytes();
PemObject pemObject = new PemObject("PUBLIC KEY", publicKeyBytes);
PemReader pemReader = new PemReader(new FileReader("sm2_pub_key.pem"));
pemObject = pemReader.readPemObject();
pemReader.close();
publicKeyBytes = pemObject.getContent();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
ECPublicKey publicKey = (ECPublicKey) converter.getPublicKey(spki);
// 打印公钥参数
ECNamedCurveParameterSpec spec = (ECNamedCurveParameterSpec) publicKey.getParams();
System.out.println("Curve: " + spec.getName());
System.out.println("X: " + publicKey.getW().getAffineX());
System.out.println("Y: " + publicKey.getW().getAffineY());
}
}
```
其中,`sm2_cert.pem`是SM2证书文件,`sm2_pub_key.pem`是SM2公钥文件。在读取公钥时,需要先解析SubjectPublicKeyInfo,再读取PEM格式的公钥文件,最后使用JcaPEMKeyConverter转换为ECPublicKey类型。打印公钥参数时,需要使用ECPublicKey的getParams()方法获取椭圆曲线参数。
阅读全文