失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > java sm_Java国密SM2/SM3/SM4及证书

java sm_Java国密SM2/SM3/SM4及证书

时间:2023-05-28 08:22:11

相关推荐

java sm_Java国密SM2/SM3/SM4及证书

1. 使用BC库1.59版本已经可以支持国密算法SM2/SM3/SM4,某大神写的详细测试例子:/ZZMarquis/gmhelper

2.制作证书参考网上资料简单例子;

``` java

public static void genSM2CertBySelf() throws OperatorCreationException, IOException, CertificateException {

String dn = "CN=dfg, OU=aert, O=45y, L=sdfg, ST=fg, C=CN";

long year = 360 * 24 * 60 * 60 * 1000;

Date notBefore = new Date();

Date notAfter = new Date(notBefore.getTime() + year);

//证书的名称

String fileName = "self"+new Date().getTime()/1000;

String path = "/test/gmhelper/";

String rootCertPath = path+fileName+".der";

AsymmetricCipherKeyPair kp = Sm2Util.generateKeyPair();

ECPrivateKeyParameters bcecPrivateKey = (ECPrivateKeyParameters)kp.getPrivate();

ECPublicKeyParameters bcecPublicKey = (ECPublicKeyParameters)kp.getPublic();

BcX509v3CertificateBuilder build = new BcX509v3CertificateBuilder(

new X500Name(dn),

BigInteger.probablePrime(64, new Random()),

notBefore,

notAfter,

new X500Name(dn),

bcecPublicKey);

AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SM3withSM2");//即"1.2.156.10197.1.501"

AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find("SHA256");

ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(bcecPrivateKey);

X509CertificateHolder x509certHolder = build.build(sigGen);

FileOutputStream outputStream = new FileOutputStream(rootCertPath);

outputStream.write(x509certHolder.getEncoded());

outputStream.close();

}

```

3. 使用上面介绍的制作证书方法如果跟GMSSL生成的证书比对缺少“公钥参数”对象,因为BC库公钥是采用X9.62格式,见rfc5349/html/rfc5349 ; 如果一定要带公钥参数对象,代码去处理下ASN.1,把BcX509v3CertificateBuilder修改为X509v3CertificateBuilder,公钥通过createSubjectECPublicKeyInfo做下转换

``` java

public static SubjectPublicKeyInfo createSubjectECPublicKeyInfo(ECPublicKeyParameters pub)

{

ASN1OctetString p = (ASN1OctetString)new X9ECPoint(pub.getQ()).toASN1Primitive();

return new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, GMObjectIdentifiers.sm2p256v1), p.getOctets());

}

```

4. 自己如何构造公钥参数ECPublicKeyParameters参考:/blog/2389904 如果要构造私钥参数类似如此操作,更简单,因为私钥参数ECPrivateKeyParameters只有一个大数BigInteger

5.证书解析参考:/qq_32221419/article/details/59111828

6、证书请求及其它:参考/?post=54 和

/jinhill/article/details/17612273

如果觉得《java sm_Java国密SM2/SM3/SM4及证书》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。