國(guó)密SM2雙證書(shū)申請(qǐng)

最近在處理國(guó)密SM2雙證書(shū)申請(qǐng),網(wǎng)上查了很多資料零零散散,所以自己寫(xiě)下一點(diǎn)總結(jié)

1.本次需求是移動(dòng)端App上申請(qǐng)雙證書(shū)(加密證書(shū) + 簽名證書(shū)),加密證書(shū)用于數(shù)據(jù)加密,簽名證書(shū)用于簽名。我們只需要生成請(qǐng)求證書(shū)的pkcs10 的 csr,讓后端去CA申請(qǐng)雙證書(shū)

2.前期準(zhǔn)備:引入BC庫(kù)(版本1.6.0)生成公私鑰對(duì),公鑰是橢圓曲線(xiàn)上的點(diǎn)(x,y)

public static KeyPairgenerateBCKeyaPair()throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC",new BouncyCastleProvider());
    keyGen.initialize(new ECNamedCurveGenParameterSpec(AIG_NAME));
    KeyPair keyPair = keyGen.generateKeyPair();
    return keyPair;
}

3.生成申請(qǐng)pkcs10的CSR事例,先設(shè)置DN項(xiàng)

public static String createP10(CertInitBean applyInfo, KeyPair keypair)throws Exception {
    String dnFormat ="CN=%s,C=%s,O=%s";
    String c = applyInfo.getTenantName() +"@" + applyInfo.getCardNo();
    String o = !applyInfo.isPersonal() ? applyInfo.getTenantName() :"";
    String dn = String.format(dnFormat,c,applyInfo.getCountry(),o);

    //1. 創(chuàng)建簽名
    ContentSigner signer =new JcaContentSignerBuilder("SM3WITHSM2")
        .setProvider(new BouncyCastleProvider()).build(keypair.getPrivate());
    //2. 創(chuàng)建證書(shū)請(qǐng)求
    PKCS10CertificationRequestBuilder pkcs10CertificationRequestBuilder =new JcaPKCS10CertificationRequestBuilder(new X500Name(dn),keypair.getPublic());
    PKCS10CertificationRequest pkcs10CertificationRequest = pkcs10CertificationRequestBuilder.build(signer);
    return Base64Utils.encode(pkcs10CertificationRequest.getEncoded());
}

4.請(qǐng)求CA申請(qǐng)證書(shū)事例以及返回?cái)?shù)據(jù)格式

image
image

5.我們需要主要拿到三個(gè)數(shù)據(jù)(加密證書(shū)/簽名證書(shū)/加密證書(shū)的私鑰),加密證書(shū)的私鑰是經(jīng)過(guò)簽名證書(shū)私鑰加密的對(duì)稱(chēng)密鑰加密過(guò)的,所以接下來(lái)需要解密數(shù)字信封 獲取加密證書(shū)的私鑰

處理encPrivateKey_shecaSM2    
public static String decryptECB(CertDBEntity certDBEntity) {
    String enc_envelope = certDBEntity.getEncEnvelope();
    //簽名證書(shū)私鑰
    PrivateKey sign_privateKey = GmUtil.getPrivatekeyFromD(new BigInteger(certDBEntity.getD()));

    byte[] decode = Base64Utils.decode(enc_envelope);
    System.out.println(Arrays.toString(decode));
    System.out.println(decode.length);
    byte[] version = new byte[4];
    byte[] ulSymmAlgID = new byte[4];
    byte[] ulBits = new byte[4];
    byte[] encryptedPriKey = new byte[64];
    byte[] pubKey = new byte[132];
    byte[] pairCipher = new byte[180];

    System.arraycopy(decode, 0, version, 0, version.length);
    System.arraycopy(decode, version.length, ulSymmAlgID, 0, ulSymmAlgID.length);
    System.arraycopy(decode, version.length+ulSymmAlgID.length, ulBits, 0, ulBits.length);
    System.arraycopy(decode, version.length+ulSymmAlgID.length+ulBits.length, encryptedPriKey, 0, encryptedPriKey.length);
    System.arraycopy(decode, version.length+ulSymmAlgID.length+ulBits.length+encryptedPriKey.length, pubKey, 0, pubKey.length);
    System.arraycopy(decode, version.length+ulSymmAlgID.length+ulBits.length+encryptedPriKey.length+pubKey.length, pairCipher, 0, pairCipher.length);
    byte[] priBytes = new byte[32];
    System.arraycopy(encryptedPriKey, 64-priBytes.length, priBytes, 0, priBytes.length);

    //轉(zhuǎn)換公鑰密文
    byte[] encDataToDer = encDataToDer(pairCipher);
    //獲取公鑰加密的對(duì)稱(chēng)密鑰
    //uu7X9qbPO+UTqmWchIZfxw==
    byte[] sm4Key = GmUtil.sm2Decrypt(encDataToDer, sign_privateKey);

    String decryptECB = SM4.decryptECB(Base64Utils.encode(priBytes), Base64Utils.encode(sm4Key));
    return decryptECB;
}
private static byte[] encDataToDer(byte[] encryptData){
    byte[] XCoordinate = new byte[32];
    System.arraycopy(encryptData, 32, XCoordinate, 0, 32);
    byte[] YCoordinate = new byte[32];
    System.arraycopy(encryptData, 96, YCoordinate, 0, 32);
    byte[] C3_hash = new byte[32];
    System.arraycopy(encryptData, 128, C3_hash, 0, 32);
    byte[] C2_cipher = new byte[encryptData.length - 4 - 32 - 128];
    System.arraycopy(encryptData, 4 + 32 + 128, C2_cipher, 0, C2_cipher.length);
    encryptData = new byte[1 + XCoordinate.length + YCoordinate.length + C3_hash.length + C2_cipher.length];
    System.arraycopy(XCoordinate, 0, encryptData, 1, XCoordinate.length);
    System.arraycopy(YCoordinate, 0, encryptData, 1 + XCoordinate.length, YCoordinate.length);
    System.arraycopy(C3_hash, 0, encryptData, 1 + XCoordinate.length + YCoordinate.length, C3_hash.length);
    System.arraycopy(C2_cipher, 0, encryptData, 1 + XCoordinate.length + YCoordinate.length + C3_hash.length, C2_cipher.length);

    Sm2CipherParser sm2Cipher = new Sm2CipherParser(encryptData);
    return sm2Cipher.decode();
}

6.得到加密證書(shū)的私鑰就可以用來(lái)加解密了

公鑰加密

public static byte[] encode(PublicKey publicKey, byte[] encodeData) {
    return changeC1C2C3ToC1C3C2(sm2EncryptOld(encodeData, publicKey));
}

private static byte[] changeC1C2C3ToC1C3C2(byte[] c1c2c3) {
    final int c1Len = (x9ECParameters.getCurve().getFieldSize() + 7) / 8 * 2 + 1; //sm2p256v1的這個(gè)固定65??煽碐MNamedCurves、ECCurve代碼。
    final int c3Len = 32; //new SM3Digest().getDigestSize();
    byte[] result = new byte[c1c2c3.length];
    System.arraycopy(c1c2c3, 0, result, 0, c1Len); //c1
    System.arraycopy(c1c2c3, c1c2c3.length - c3Len, result, c1Len, c3Len); //c3
    System.arraycopy(c1c2c3, c1Len, result, c1Len + c3Len, c1c2c3.length - c1Len - c3Len); //c2
    return result;
}

私鑰解密

public static byte[] decode(PrivateKey privateKey, byte[] decodeData) {
    return sm2DecryptOld(changeC1C3C2ToC1C2C3(decodeData), privateKey);
}

private static byte[] changeC1C3C2ToC1C2C3(byte[] c1c3c2) {
    final int c1Len = (x9ECParameters.getCurve().getFieldSize() + 7) / 8 * 2 + 1; //sm2p256v1的這個(gè)固定65??煽碐MNamedCurves、ECCurve代碼。
    final int c3Len = 32; //new SM3Digest().getDigestSize();
    byte[] result = new byte[c1c3c2.length];
    System.arraycopy(c1c3c2, 0, result, 0, c1Len); //c1: 0->65
    System.arraycopy(c1c3c2, c1Len + c3Len, result, c1Len, c1c3c2.length - c1Len - c3Len); //c2
    System.arraycopy(c1c3c2, c1Len, result, c1c3c2.length - c3Len, c3Len); //c3
    return result;
}

7.使用簽名證書(shū)簽名,公鑰驗(yàn)簽

簽名

public static byte[] sign(PrivateKey privateKey, byte[] signData) throws Exception {
    byte[] result = null;
    try {
        Signature signature = Signature.getInstance(GMObjectIdentifiers.sm2sign_with_sm3.toString(),new BouncyCastleProvider());
        signature.initSign(privateKey);
        signature.update(signData);
        result = signature.sign();
    }catch (Exception e) {
        throw new Exception("簽名失敗:"+e.getMessage());
    }
    return result;
}

驗(yàn)簽

public static boolean verify(PublicKey publicKey, byte[] srcData, byte[] signedData) throws Exception {
    Boolean result = null;
    try {
        Signature signature = Signature.getInstance(GMObjectIdentifiers.sm2sign_with_sm3.toString(),new BouncyCastleProvider());
        signature.initVerify(publicKey);
        signature.update(srcData);
        result = signature.verify(signedData);
    }catch (Exception e) {
        throw new Exception("簽名失敗:"+e.getMessage());
    }
    return result;
}

8.以上是基礎(chǔ)用法,可以使用EC SM2進(jìn)行PDF簽名,以及驗(yàn)簽,后續(xù)再補(bǔ)充

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 概述 ? 密碼學(xué)是研究如何保護(hù)信息安全性的一門(mén)科學(xué),涉及數(shù)學(xué)、物理、計(jì)算機(jī)、信息論、編碼學(xué)、通訊技術(shù)等學(xué)科,已經(jīng)在...
    卿酌南燭_b805閱讀 1,860評(píng)論 0 0
  • HTTPS 的誕生 可先參考網(wǎng)絡(luò)協(xié)議、HTTPS協(xié)議等文章 明文傳輸 對(duì)稱(chēng)加密 “加密”和“解密”使用【相同的】密...
    wholegale39閱讀 1,526評(píng)論 0 0
  • GmSSL 是一個(gè)開(kāi)源(遵循 BSD 協(xié)議)的密碼工具箱,支持 SM2 / SM3 / SM4 / SM9 / Z...
    張毅SOHO閱讀 7,018評(píng)論 12 9
  • 一、現(xiàn)狀分析 從1971年第一封用@符號(hào)標(biāo)記的電子郵件誕生,到2021年已經(jīng)有50年歷史的電子郵件是互聯(lián)網(wǎng)的第一個(gè)...
    Mesign閱讀 364評(píng)論 0 0
  • 16宿命:用概率思維提高你的勝算 以前的我是風(fēng)險(xiǎn)厭惡者,不喜歡去冒險(xiǎn),但是人生放棄了冒險(xiǎn),也就放棄了無(wú)數(shù)的可能。 ...
    yichen大刀閱讀 8,212評(píng)論 0 4

友情鏈接更多精彩內(nèi)容