Java国密SM2/SM3/SM4及证书

1. 使用BC库1.59版本已经可以支持国密算法SM2/SM3/SM4,某大神写的详细测试例子:https://github.com/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 https://tools.ietf.org/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参考:http://linuxgao.iteye.com/blog/2389904  如果要构造私钥参数类似如此操作,更简单,因为私钥参数ECPrivateKeyParameters只有一个大数BigInteger

5. 证书解析参考:https://blog.csdn.net/qq_32221419/article/details/59111828

6、证书请求及其它:参考 http://www.sitcoder.com/?post=54 和

https://blog.csdn.net/jinhill/article/details/17612273

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在光阴的无情中,给爱情以抚慰。 人可以滥情至此,也可以专情至此。艰难困苦中的爱情是那么坚定与纯粹,一辈子换来的只是...
    染唯尘arowlamb阅读 319评论 0 0
  • 2011年3月10日 发烧,39.3度。 身体在燃烧,人却感觉很冷,只想钻在厚厚的被子里。 原来肌肉和关节可以这样...
    高小花0218阅读 334评论 0 0
  • 有人阴差阳错,有人机缘巧合。 二娃四岁那年,元芬又生了一个儿子,排行老三。老三是农历五月出生的,正是青黄不接的时节...
    话唠的二娃阅读 502评论 0 0
  • 开心, 今天外婆和妈妈都来接你放学,原因是妈妈把外婆旅游的日期搞错了,最近类似事件搞错好多次啦,自省自省。 不过两...
    蔡敏_Michelle阅读 259评论 0 2