Java 用于ChainMaker国密

直接上代码


/**
 * bcprov-jdk15on 版本适用(1.61-1.68)
 * @author dashou
 * @date 2021-4-13
 */
public class HelloWorld {
   static  String PrivateKey = "-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgxNMRgCS9b79Epc1p\niSPs+Xs1Nxqmwv+Qh7fhrqABN5qgCgYIKoEcz1UBgi2hRANCAAST9ZM+KsiZeVXh\nETzuftpbSOUaUiLirS+ei8nP4uI6LJMHFjr5SqjVFYUS5Xvu9uryvuDnIxv8faR6\n4nGEXFNU\n-----END PRIVATE KEY-----";
   static  String PublicKey ="-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEk/WTPirImXlV4RE87n7aW0jlGlIi\n4q0vnovJz+LiOiyTBxY6+Uqo1RWFEuV77vbq8r7g5yMb/H2keuJxhFxTVA==\n-----END PUBLIC KEY-----";


    public static PrivateKey getPrivateKeyFromBytes(byte[] pemKey) throws ChainMakerCryptoSuiteException {
        PrivateKey pk = null;
        try {
            PemReader pr = new PemReader(new StringReader(new String(pemKey)));
            PemObject po = pr.readPemObject();
            PEMParser pem = new PEMParser(new StringReader(new String(pemKey)));

            if (po.getType().equals("PRIVATE KEY")) {
                pk = new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) pem.readObject());
            } else {
                PEMKeyPair kp = (PEMKeyPair) pem.readObject();
                pk = new JcaPEMKeyConverter().getPrivateKey(kp.getPrivateKeyInfo());
            }
        } catch (Exception e) {
            throw new ChainMakerCryptoSuiteException(e.toString());
        }
        return pk;
    }

    public static PublicKey getPublicKeyFromBytes(byte[] pemKey) throws ChainMakerCryptoSuiteException {
        PublicKey pk = null;
        try {
            PemReader pr = new PemReader(new StringReader(new String(pemKey)));
            PemObject po = pr.readPemObject();
            PEMParser pem = new PEMParser(new StringReader(new String(pemKey)));

            if (po.getType().equals("PUBLIC KEY")) {
                pk = new JcaPEMKeyConverter().getPublicKey((SubjectPublicKeyInfo)pem.readObject());
            } else {
                PEMKeyPair kp = (PEMKeyPair) pem.readObject();
                pk = new JcaPEMKeyConverter().getPublicKey(kp.getPublicKeyInfo());
            }
        } catch (Exception e) {
            throw new ChainMakerCryptoSuiteException(e.toString());
        }
        return pk;
    }

   public static byte[] C1C3C2ToDer(byte[] cipher) throws IOException {
       ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("sm2p256v1");
       final byte[] point = new byte[65];
       System.arraycopy(cipher,0,point,0,65);
       final ECPoint ecPoint = spec.getCurve().decodePoint(point);
       final  byte[] m = new byte[32];
       System.arraycopy(cipher,65,m,0,32);
       final byte[] c = new byte[cipher.length-65-32];
       System.arraycopy(cipher,65+32,c,0,cipher.length-65-32);
       final ASN1EncodableVector vector = new ASN1EncodableVector();
       vector.add(new ASN1Integer(ecPoint.getAffineXCoord().toBigInteger()));
       vector.add(new ASN1Integer(ecPoint.getAffineYCoord().toBigInteger()));
       vector.add(new DEROctetString(m));
       vector.add(new DEROctetString(c));
       final  ASN1Sequence sequence = new DERSequence(vector);
       return sequence.getEncoded();
   }

    public static byte[] derToC1C3C2(byte[] cipher){
        final ASN1Sequence sequence = ASN1Sequence.getInstance(cipher);
        final ASN1Integer x =(ASN1Integer) sequence.getObjectAt(0);
        final ASN1Integer y =(ASN1Integer) sequence.getObjectAt(1);
        final DEROctetString m =(DEROctetString) sequence.getObjectAt(2);
        final DEROctetString c =(DEROctetString) sequence.getObjectAt(3);
        ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("sm2p256v1");
        final ECPoint ecPoint =spec.getCurve().createPoint(x.getPositiveValue(),y.getPositiveValue());
        final byte[] c1 = ecPoint.getEncoded(false);
        final byte[] c3 = m.getOctets();
        final byte[] c2 = c.getOctets();
        return Arrays.concatenate(c1,c3,c2);
    }

    /**
     * 解密
     */
    public static byte[] decrypt(byte[] encode) throws ChainMakerCryptoSuiteException {
        PrivateKey privateKey = getPrivateKeyFromBytes(PrivateKey.getBytes());
        ECPrivateKeyParameters parameters=BCECUtil.convertPrivateKeyToParameters((BCECPrivateKey) privateKey);
        SM2Engine.Mode mode = SM2Engine.Mode.C1C3C2;
        final SM2Engine engine =  new SM2Engine(mode);
        engine.init(false, parameters);
        // 解密测试
        try {
           // String encode="MGoCIBusNdgkzMaGHEgSP5a/3dX98YkwfNuxZt8ORcmG3eaQAiEAtHcS4aDtiMg9b4mW7plzfcGV64rXhbi9UR9aCMOR7lEEIL20vNQjntOfO5jKNzIUtUSHF7MWrsfBM5jlUpFOn49pBAEH";
            byte[] octets = derToC1C3C2(encode);
            return engine.processBlock(octets, 0, octets.length);
        } catch (Exception e) {
            System.out.println("加解密测试错误");
            return null;
        }
    }

    /**
     * 加密
     */
    public static byte[] encrypt(byte[] data) throws ChainMakerCryptoSuiteException {
        PublicKey publicKey = getPublicKeyFromBytes(PublicKey.getBytes());
        BCECPublicKey localECPublicKey = (BCECPublicKey) publicKey;
        ECPublicKeyParameters  localECPublicKeyParameters = BCECUtil.convertPublicKeyToParameters(localECPublicKey);
        SM2Engine.Mode mode = SM2Engine.Mode.C1C3C2;
        SM2Engine localSM2Engine = new SM2Engine(mode);
        return getBytes(data, localECPublicKeyParameters, localSM2Engine);
    }
    public static byte[] getBytes(byte[] data, ECPublicKeyParameters localECPublicKeyParameters, SM2Engine localSM2Engine) {
        localSM2Engine.init(true, new ParametersWithRandom(localECPublicKeyParameters, new SecureRandom()));
        byte[] arrayOfByte2;
        try {
            arrayOfByte2 = C1C3C2ToDer(localSM2Engine.processBlock(data, 0, data.length));
            return arrayOfByte2;
        } catch (InvalidCipherTextException | IOException e) {

            e.printStackTrace();
            return null;
        }
    }

    /**
     * 私钥签名
     */
    public static byte[] signByPrivateKey(byte[] data) throws Exception {
        PrivateKey privateKey = getPrivateKeyFromBytes(PrivateKey.getBytes());
        Signature sig = Signature.getInstance("SM3withSM2", BouncyCastleProvider.PROVIDER_NAME);
        sig.initSign(privateKey);
        sig.update(data);
        return sig.sign();
    }

    /**
     * 公钥验签
     */
    public static boolean verifyByPublicKey(byte[] data, byte[] signature) throws Exception {
        PublicKey publicKey = getPublicKeyFromBytes(PublicKey.getBytes());
        Signature sig = Signature.getInstance("SM3withSM2");
        sig.initVerify(publicKey);
        sig.update(data);
        return sig.verify(signature);
    }

    // 读文件
    public static byte[] getFileBytes(String filePath) throws UtilsException {
        byte[] fileBytes = null;
        try {
            fileBytes = IOUtils.toByteArray(new FileInputStream(new File(filePath)));
        } catch (IOException e) {
            throw new UtilsException("get file by path err : " + e.getMessage());
        }
        return fileBytes;
    }
    // 写文件
    public static void CreateFile(byte[] bfile, String filePath,String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if(!dir.exists() && !dir.isDirectory()){//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) throws Exception {
//        // 加密
//         byte[] ddd= encrypt("s33311dsagewafeer232342swefwr2r2p[kmr2;jfdpwf'pajf[asojfawojf[pawokfa[pojef[awmv'paojf".getBytes());
//         // 解密
//        decrypt(Base64.getEncoder().encodeToString(ddd));
//         // 签名
//        byte[]d= signByPrivateKey("ww".getBytes());
//        String dddddd = "MEQCIEJKU36PEIUv+COsP264CleJ2QlbscTKwngJxPrQD79bAiAAowB4ymhLUaR/VKYiY33l8mb7zsnAttxqZeAckwi9Gg==";
//         // 验证
//        boolean s= verifyByPublicKey("ww".getBytes(),Base64.getDecoder().decode(dddddd));
      // 读取秘钥
       byte[]dd= getFileBytes("/Users/sunbo/Desktop/Haier/地铁集团/sdk-java/src/main/java/8062c89270484193b536af68475acc6a");
       byte[]ee= decrypt(dd);
       CreateFile(ee,"/Users/sunbo/Desktop/Haier/地铁集团/sdk-java/src/main/java/","1.pdf");
    }
}

你可能感兴趣的:(Java 用于ChainMaker国密)