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

你可能感兴趣的:(Java国密SM2/SM3/SM4及证书)