最近在處理國(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ǔ)充