网上关于国密算法的资料较单一,大部分代码都是写的怎么通过java代码生成公私钥串。
实际项目中对方已经给了他们的公钥证书,这里记录如何通过代码解析获得Ecpoint对象并输出
关键代码
String cerPath="E:\\test.cer";
X509Certificate x509Certificate = null;
#国密证书使用了自有的椭圆曲线,无法使用JDK自带的java.security解析证书,需要引入BouncyCastle的BC库支持国密算法
Security.addProvider(new BouncyCastleProvider());
#如果不引入BC库这里会报java.security.NoSuchProviderException: no such provider: BC错误
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509","BC");
FileInputStream fileInputStream = new FileInputStream(cerPath);
x509Certificate = (X509Certificate) certificateFactory.generateCertificate(fileInputStream);
fileInputStream.close();
System.out.println("证书序列号:"+ x509Certificate.getSerialNumber());
#这里有个坑,bcprov-jdk15on需1.59以上的版本,之前引的是1.54版一直报错
System.out.println("证书公钥:"+ x509Certificate.getPublicKey());
输出
证书序列号:534384516521
证书公钥:EC Public Key [de:38:a5:b6:6f:8b:f7:34:5f:72:1c:af:0c:14:e5:a2:84:fa:e2:c3]
X: 2f05a01e62336c889009b4174d1ec550de327db602ae49a29ebaa4c258633556
Y: cea688f06328d4616685d5cfd575de8e5e8b6de7f5bfc1d273c3562159a5f3f
依赖库
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.59</version>
</dependency>
原创类文章未经允许请勿转载:39点博客 » 【国密SM2算法】通过公钥证书获取JAVA对象