Java下使用BouncyCastle制作证书(RSA/ECC/SM2)

简介

首先简单介绍下什么是数字证书,所谓数字证书,就是互联网通讯中的“身份证”。通常的数字证书是由权威机构CA证书授权中心发行的,能提供在Internet上进行身份验证。数字证书的认证原理基于非对称加密算法。生成证书前首先需要生成一对非对称密钥,将颁发者身份信息、使用者身份信息、公钥、颁发者私钥对基本证书域的签名值以及一些算法标识符oid按照RFC2459所规定的形式组合成符合文档定义的ASN1结构,就完成证书的制作了。但实际的证书生成,标准的流程都是先生成证书请求,这个证书请求中包含自身的身份信息,证书所需公钥,私钥对证书请求信息域的签名值,扩展项信息和一些算法标识oid,证书请求的数据格式定义在RFC2986中,生成证书时通过解析证书请求来获取使用者身份信息和使用者公钥。BouncyCastle是一种用于 Java 平台的开放源码的轻量级密码包,它支持大量的密码算法,同时抽象包装了各种ASN1数据类型以及ASN1结构相关的解析和组装。使用BC包可以很方便的组装生成证书。我使用的JDK版本1.8,BC版本为1.59,BC对于SM2算法的集成于版本1.57,组装国密证书部分的代码需要至少BC1.57的支持,之前版本的sm2签名写法与1.59的略有差异。完整代码在我的Github,希望可以帮助到你。


一. 生成自签发根证书

为了方便,自签发根证书就不走证书请求了,直接使用传入的使用者身份信息(Subject)和生成的密钥对(Keypair)来制作证书。

 public static Certificate selfSignedCertGen(X500Name subject, KeyPair keyPair, Date notBefore, Date notAfter) throws Exception{
        SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        BcX509ExtensionUtils extUtils = new BcX509ExtensionUtils();
        ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
        extensionsGenerator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));    //ca cert
        extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
        extensionsGenerator.addExtension(Extension.subjectKeyIdentifier,false,extUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo));
        extensionsGenerator.addExtension(Extension.authorityKeyIdentifier,false,extUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo));
        V3TBSCertificateGenerator   tbsGen = new V3TBSCertificateGenerator();
        tbsGen.setSerialNumber(new ASN1Integer(UUID.randomUUID().getMostSignificantBits()&Long.MAX_VALUE));
        tbsGen.setIssuer(subject);  //自签证书颁发者等于使用者
        tbsGen.setStartDate(new Time(notBefore, Locale.CHINA));
        tbsGen.setEndDate(new Time(notAfter,Locale.CHINA));
        tbsGen.setSubject(subject);
        tbsGen.setSubjectPublicKeyInfo(subjectPublicKeyInfo);
        tbsGen.setExtensions(extensionsGenerator.generate());
        tbsGen.setSignature(getSignAlgo(subjectPublicKeyInfo.getAlgorithm()));   //签名算法标识等于密钥算法标识
        TBSCertificate tbs = tbsGen.generateTBSCertificate();
        byte[] signature = null;
        if(issuerPrivateKey.getAlgorithm().equalsIgnoreCase("ECDSA")) {
            if(issuerSubjectPublicKeyInfo.getAlgorithm().getParameters().equals(GMObjectIdentifiers.sm2p256v1)) {
                signature = Signers.SM2Sign(tbsCertificate.getEncoded(),issuerPrivateKey);
            } else if(issuerSubjectPublicKeyInfo.getAlgorithm().getParameters().equals(SECObjectIdentifiers.secp256k1)) {  //项目中ecdsa签名使用的曲线为secp256k1
                signature = Signers.ECDSASign(tbsCertificate.getEncoded(),issuerPrivateKey);
            } else
                throw new IllegalArgumentException("不支持的曲线");
        } else if(issuerPrivateKey.getAlgorithm().equalsIgnoreCase("RSA")) {
            signature = Signers.RSASign(tbsCertificate.getEncoded(),issuerPrivateKey);
        } else
            throw new IllegalArgumentException("不支持的密钥算法");
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCertificate);
        v.add(getSignAlgo(issuerSubjectPublicKeyInfo.getAlgorithm())); //根据公钥算法标识返回对应签名算法标识
        v.add(new DERBitString(signature));
        return Certificate.getInstance(new DERSequence(v));
    }

二. 生成证书请求

传入使用者身份信息(Subject),使用者公钥,组装证书请求信息对象(CertificateRequestInfo),并使用传入的使用者私钥进行签名,最终生成P10格式的证书请求。

public static PKCS10CertificationRequest generateCSR(X500Name subject, PublicKey publicKey, PrivateKey privateKey) {
        try {
            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
            CertificationRequestInfo info = new CertificationRequestInfo(subject,subjectPublicKeyInfo,new DERSet());
            byte[] signature;
            AlgorithmIdentifier signAlgo = getSignAlgo(subjectPublicKeyInfo.getAlgorithm());
            if(signAlgo.getAlgorithm().equals(GMObjectIdentifiers.sm2sign_with_sm3)) {
                signature = Signers.SM2Sign(info.getEncoded(ASN1Encoding.DER),privateKey);
            } else if(signAlgo.getAlgorithm().equals(X9ObjectIdentifiers.ecdsa_with_SHA256)) {
                signature = Signers.ECDSASign(info.getEncoded(ASN1Encoding.DER),privateKey);
            } else if(signAlgo.getAlgorithm().equals(PKCSObjectIdentifiers.sha256WithRSAEncryption)) {
                signature = Signers.RSASign(info.getEncoded(ASN1Encoding.DER),privateKey);
            } else
                throw new IllegalArgumentException("密钥算法不支持");
            return new PKCS10CertificationRequest(new CertificationRequest(info,signAlgo,new DERBitString(signature)));
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("密钥结构错误");
        }
    }

三. 签发终端实体证书

终端实体证书有别于CA证书,它无法向下签发任何证书,V3的终端实体证书中使用扩展字段(BasicConstraints=false)来区分该证书是不是CA证书。制作终端实体证书需要颁发者证书(必须是CA证书),颁发者证书的私钥。

public static Certificate certGen(PKCS10CertificationRequest csr, PrivateKey issuerPrivateKey, byte[] issuerCert, Date notBefore, Date notAfter) throws Exception {
        X509CertificateHolder issuer = new X509CertificateHolder(issuerCert);
        if(!verifyCSR(csr))
            throw new IllegalArgumentException("证书请求验证失败");
        X500Name subject = csr.getSubject();
        BcX509ExtensionUtils extUtils = new BcX509ExtensionUtils();
        ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
        extensionsGenerator.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));    //entity cert
        extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
        extensionsGenerator.addExtension(Extension.authorityKeyIdentifier,false,extUtils.createAuthorityKeyIdentifier(issuer)); //授权密钥标识
        extensionsGenerator.addExtension(Extension.subjectKeyIdentifier,false,extUtils.createSubjectKeyIdentifier(csr.getSubjectPublicKeyInfo())); //使用者密钥标识
        V3TBSCertificateGenerator tbsGen = new V3TBSCertificateGenerator();
        tbsGen.setSerialNumber(new ASN1Integer(UUID.randomUUID().getMostSignificantBits()&Long.MAX_VALUE));
        tbsGen.setIssuer(issuer.getSubject());
        tbsGen.setStartDate(new Time(notBefore, Locale.CHINA));
        tbsGen.setEndDate(new Time(notAfter,Locale.CHINA));
        tbsGen.setSubject(subject);
        tbsGen.setSubjectPublicKeyInfo(csr.getSubjectPublicKeyInfo());
        tbsGen.setExtensions(extensionsGenerator.generate());
        tbsGen.setSignature(issuer.getSubjectPublicKeyInfo().getAlgorithm());   //签名算法标识等于颁发者证书的密钥算法标识
        TBSCertificate tbs = tbsGen.generateTBSCertificate();
        byte[] signature = null;
        if(issuerPrivateKey.getAlgorithm().equalsIgnoreCase("ECDSA")) {
            if(issuerSubjectPublicKeyInfo.getAlgorithm().getParameters().equals(GMObjectIdentifiers.sm2p256v1)) {
                signature = Signers.SM2Sign(tbsCertificate.getEncoded(),issuerPrivateKey);
            } else if(issuerSubjectPublicKeyInfo.getAlgorithm().getParameters().equals(SECObjectIdentifiers.secp256k1)) {
                signature = Signers.ECDSASign(tbsCertificate.getEncoded(),issuerPrivateKey);
            } else
                throw new IllegalArgumentException("不支持的曲线");
        } else if(issuerPrivateKey.getAlgorithm().equalsIgnoreCase("RSA")) {
            signature = Signers.RSASign(tbsCertificate.getEncoded(),issuerPrivateKey);
        } else
            throw new IllegalArgumentException("不支持的密钥算法");
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCertificate);
        v.add(getSignAlgo(issuerSubjectPublicKeyInfo.getAlgorithm()));
        v.add(new DERBitString(signature));
        return Certificate.getInstance(new DERSequence(v));
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容

  • 文中首先解释了加密解密的一些基础知识和概念,然后通过一个加密通信过程的例子说明了加密算法的作用,以及数字证书的出现...
    已认证用户阅读 3,813评论 1 4
  • 文中首先解释了加密解密的一些基础知识和概念,然后通过一个加密通信过程的例子说明了加密算法的作用,以及数字证书的出现...
    xiechengfa阅读 1,853评论 4 12
  • 文中首先解释了加密解密的一些基础知识和概念,然后通过一个加密通信过程的例子说明了加密算法的作用,以及数字证书的出现...
    梅_梅阅读 275评论 0 0
  • 数字证书原理 - 无恙 - 博客园 文中首先解释了加密解密的一些基础知识和概念,然后通过一个加密通信过程的例子说明...
    拉肚阅读 1,654评论 0 3
  • 我们一路奋战,不是为了改变这个世界,而是为了不让这个世界改变我们。我们不妥协,不习惯,不漠视,一路奋战。 初三那会...
    荷笠阅读 180评论 0 0