国密SM2,SM3,SM4在BC上的实现(一)

SM2,SM3,SM4算法的实现在网络上实现有不少,但是实现只是加解密,签名等,如果说要生成国密数字证书就麻烦了,还有最近银行的项目上需要用ITEXT对pdf进行国密跟RSA证书数字签名,这个用SM2单独的签名是不能实现的,因为ITEXT签名是基于BC框架的,这里就是在BC框架上添加SM2,SM4算法,以及SM3摘要算法,在这里跟大家分享一下。
BC框架是基于JCA,JCE来实现的,关于JCA,JCE这里就不详述了。既然我们要添加这几种算法,我们要实现那几步呢?
1,实现MAC
2,实现SM2,SM3,SM4算法
3,SM2,SM4算法的密钥(KeyPairGenerator)
4,加解密(Cipher);
5,签名(Signature);
6,数字证书(Certificate)
话不多说,先上几张效果图。
一 ,SM2加解密
国密SM2,SM3,SM4在BC上的实现(一)_第1张图片

 public static String SM2_Cipher(boolean all,String enData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        StringBuilder sb = new StringBuilder();
        byte[] sourceData = enData.getBytes();
        KeyPair keyPair = generateKeyPair(all?sb:null);
        Cipher cp1 = Cipher.getInstance("SM2");
        sb.append("public key = ");
        sb.append(bytesToHexString(keyPair.getPublic().getEncoded()));
        sb.append("\nprivate key = ");
        sb.append(bytesToHexString(keyPair.getPrivate().getEncoded()));

        cp1.init(1, keyPair.getPublic());
        byte[] encrypted = cp1.doFinal(sourceData);
        sb.append("\nEncrypted: ");
        sb.append(bytesToHexString(encrypted));
        Cipher cp2 = Cipher.getInstance("SM2");
        cp2.init(2, keyPair.getPrivate());
        byte[] decrypted = cp2.doFinal(encrypted);
        sb.append("\nDecrypted: ");
        sb.append(bytesToHexString(decrypted));
        sb.append("\nDecryptString: ");
        sb.append(new String(decrypted));
        boolean equ = Arrays.equals(decrypted, sourceData);
        sb.append("\nEncrypt/Decrypt ").append(equ?"Passed.":"Failed.");
        return sb.toString();
    }
    public static KeyPair generateKeyPair(StringBuilder sb) throws NoSuchAlgorithmException {
        addProvider((StringBuilder)null);
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("SM2");
        return kpg.generateKeyPair();
    }

二,SM4加解密
国密SM2,SM3,SM4在BC上的实现(一)_第2张图片

public static String SM4_Cipher(boolean all,String enData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        StringBuilder sb = new StringBuilder();
        byte[] sourceData = enData.getBytes();
        byte[] sorData_16 = new byte[16];
        System.arraycopy(sourceData,0,sorData_16,0,sourceData.length);
        addProvider(all?sb:null);
        KeyGenerator kg = KeyGenerator.getInstance("SM4");
        kg.init(new SecureRandom());
        SecretKey keye = kg.generateKey();
        byte[] sm4k = keye.getEncoded();
        sb.append("\nKey:");
        sb.append(bytesToHexString(sm4k));
        SecretKeySpec keyd = new SecretKeySpec(sm4k, "SM4");
        Cipher cp1 = Cipher.getInstance("SM4");
        cp1.init(1, keye);
        byte[] encrypted = cp1.doFinal(sorData_16);
        sb.append("\nEncrypted: ");
        sb.append(bytesToHexString(encrypted));
        Cipher cp2 = Cipher.getInstance("SM4");
        cp2.init(2, keyd);
        byte[] decrypted = cp2.doFinal(encrypted);
        sb.append("\nDecrypted: ");
        sb.append(bytesToHexString(decrypted));
        sb.append("\nDecryptString: ");
        sb.append(new String(decrypted));
        if(Arrays.equals(sorData_16, decrypted)) {
            sb.append("\nSM4 Ok.");
        }

        return sb.toString();
    }

三,SM2证书以及签名
国密SM2,SM3,SM4在BC上的实现(一)_第3张图片

“`
public static String testSM2() throws NoSuchAlgorithmException, OperatorCreationException, CertificateException, CertIOException, CertException {
StringBuilder sb = new StringBuilder();
SecureRandom apRandom = new SecureRandom();
NameBuilder nb = new NameBuilder(RDN.INSTANCE);
nb.addRDN(RDN.E, “[email protected]”);
nb.addRDN(RDN.CN, “gongkan”);
nb.addRDN(RDN.T, “CEO”);
nb.addRDN(RDN.OU, “unipad”);
nb.addRDN(RDN.O, “科技园”);
nb.addRDN(RDN.L, “深圳”);
nb.addRDN(RDN.ST, “广东”);
BigInteger serial = (new BigInteger(31, apRandom)).abs();
Date notBefore = new Date();
Date notAfter = new Date(notBefore.getTime() + 259200000L);
KeyPair keyPair = genSM2KeyPair();
PublicKey publicKey = keyPair.getPublic();
X500Principal me = nb.toName();
X509v3CertBuilder x3b = new X509v3CertBuilder(me, serial, notBefore, notAfter, me, publicKey);
x3b.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
x3b.addExtension(Extension.keyUsage, false, new KeyUsage(184));
x3b.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_emailProtection, KeyPurposeId.id_kp_clientAuth}));
PrivateKey privateKey = keyPair.getPrivate();
ContentSigner signer = (new SM2SignerBuilder(“1234567812345678”)).build(privateKey);
X509CertificateHolder xchd = x3b.build(signer);
X509CertificateConverter xcvt = (new X509CertificateConverter()).setProvider(“SM”);
X509Certificate cert = xcvt.getCertificate(xchd);
CertificateFactory factory = CertificateFactory.getInstance(“X509/SM2”);
X509Certificate cer = (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));
sb.append(cer);
sb.append(“\nVerify Certificate “);

    try {
        cer.verify(publicKey);
        sb.append("Passed.");
    } catch (GeneralSecurityException var18) {
        var18.printStackTrace();
        sb.append("Failed.");
    }

    return sb.toString();
}

四,项目结构图
国密SM2,SM3,SM4在BC上的实现(一)_第4张图片

你可能感兴趣的:(java,加密)