All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.founder.mip.utils.SM2SignAndVerifySignDemo Maven / Gradle / Ivy

There is a newer version: 3.6.1.9
Show newest version
//package com.founder.core.utils.smcode;
//
//import java.io.ByteArrayInputStream;
//import java.lang.reflect.Field;
//import java.lang.reflect.Method;
//import java.math.BigInteger;
//import java.nio.charset.StandardCharsets;
//import java.security.InvalidKeyException;
//import java.security.KeyFactory;
//import java.security.KeyPair;
//import java.security.KeyPairGenerator;
//import java.security.NoSuchAlgorithmException;
//import java.security.PrivateKey;
//import java.security.PublicKey;
//import java.security.SecureRandom;
//import java.security.Signature;
//import java.security.SignatureException;
//import java.security.cert.X509Certificate;
//import java.security.spec.ECGenParameterSpec;
//import java.security.spec.InvalidKeySpecException;
//import java.security.spec.PKCS8EncodedKeySpec;
//import java.security.spec.X509EncodedKeySpec;
//import java.text.SimpleDateFormat;
//import java.util.Date;
//
//import org.bouncycastle.asn1.gm.GMObjectIdentifiers;
//import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
//import org.bouncycastle.crypto.params.ECPublicKeyParameters;
//import org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory;
//import org.bouncycastle.jce.provider.BouncyCastleProvider;
//import org.bouncycastle.math.ec.ECPoint;
//import org.bouncycastle.util.encoders.Base64;
//
//import com.alibaba.fastjson.JSONObject;
//
//import iih.haycrmh.mi.d.onlinehp.MobileInputDataParam;
//import iih.haycrmh.mi.d.onlinehp.MobileInputParam;
//import iih.haycrmh.mi.d.onlinehp.TestDto;
//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;
//
//public class SM2SignAndVerifySignDemo {
//
//    public void tt() throws Exception {
//
//        // 获取SM2椭圆曲线的参数
//        final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
//        // 获取一个椭圆曲线类型的密钥对生成器
//        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
//        // 使用SM2参数初始化生成器
//        kpg.initialize(sm2Spec);
//
//        // 使用SM2的算法区域初始化密钥生成器
//        kpg.initialize(sm2Spec, new SecureRandom());
//        // 获取密钥对
//        KeyPair keyPair = kpg.generateKeyPair();
//
//		/*
//		获取公私钥
//		 */
//        PublicKey publicKey = keyPair.getPublic();
//        PrivateKey privateKey = keyPair.getPrivate();
//
//        // 生成SM2sign with sm3 签名验签算法实例
//        Signature signature = Signature.getInstance(
//                GMObjectIdentifiers.sm2sign_with_sm3.toString()
//                , new BouncyCastleProvider());
//
//        /*
//         * 签名
//         */
//        // 签名需要使用私钥,使用私钥 初始化签名实例
//        signature.initSign(privateKey);
//        // 签名原文
//        byte[] plainText = "Hello world".getBytes(StandardCharsets.UTF_8);
//        // 写入签名原文到算法中
//        signature.update(plainText);
//        // 计算签名值
//        byte[] signatureValue = signature.sign();
//        System.out.println("signature: \n" + Hex.toHexString(signatureValue));
//
//        /*
//         * 验签
//         */
//        // 签名需要使用公钥,使用公钥 初始化签名实例
//        signature.initVerify(publicKey);
//        // 写入待验签的签名原文到算法中
//        signature.update(plainText);
//        // 验签
//        System.out.println("Signature verify result: " + signature.verify(signatureValue));
//        // 证书串,通常通过读取证书文件获取到,这里是一张SM2证书。
//        String certStr = "MIICCTCCAay....t5H";
//
//        // 签名原文
//        String plaintext = "signdata";
//
//        // 签名产生签名值,此处的签名值实际上就是 R和S的sequence
//        String signValueStr = "MEUCI...DOeFE=";
//        byte[] signValue = Base64.decode(signValueStr);
//        /*
//         * 解析证书
//         */
//        CertificateFactory factory = new CertificateFactory();
//        X509Certificate certificate = (X509Certificate) factory.engineGenerateCertificate(new ByteArrayInputStream(Base64.decode(certStr)));
//
//        System.out.println(certificate.getSigAlgName());
//
//        // 验证签名
//        Signature signature1 = Signature.getInstance(certificate.getSigAlgName(), new BouncyCastleProvider());
//        signature1.initVerify(certificate);
//        signature1.update(plaintext.getBytes(StandardCharsets.UTF_8));
//
//        System.out.println(signature1.verify(signValue));
//
//    }
//
//    public static void main(String[] args) throws Exception {
//        final BouncyCastleProvider bc = new BouncyCastleProvider();
//        // 获取SM2椭圆曲线的参数
//        final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
//        // 获取一个椭圆曲线类型的密钥对生成器
//        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", bc);
//        // 使用SM2参数初始化生成器
////		kpg.initialize(sm2Spec);
////
////		// 使用SM2的算法区域初始化密钥生成器
////		kpg.initialize(sm2Spec, new SecureRandom());
////		// 获取密钥对
////		KeyPair keyPair = kpg.generateKeyPair();
////
////		/*
////		获取公私钥
////		 */
////		PublicKey publicKey = keyPair.getPublic();
////		PrivateKey privateKey = keyPair.getPrivate();
//
//
//        // 生成SM2sign with sm3 签名验签算法实例
//        Signature signature = Signature.getInstance(
//                GMObjectIdentifiers.sm2sign_with_sm3.toString()
//                , new BouncyCastleProvider());
//
//        KeyFactory keyFact = KeyFactory.getInstance("EC", bc);
//        //MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEIbPDPXNnPrxLRQnb9JPL2gQpShZjfpdnuDnRnIFK
//        //iHbk65REhzYwg+EgyZRDDqPO7LbWAp5G5UPMY2LtxsUQ/Q==
//        //String aappy = new BASE64Encoder().encode(publicKey.getEncoded());
//        String aappy = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEIbPDPXNnPrxLRQnb9JPL2gQpShZjfpdnuDnRnIFKiHbk65REhzYwg+EgyZRDDqPO7LbWAp5G5UPMY2LtxsUQ/Q==";
//        //MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgJxEanaDYYhYECSDaHfdMn34Xq4Ee
//        //nMQdDbuXawUTk6GgCgYIKoEcz1UBgi2hRANCAAQhs8M9c2c+vEtFCdv0k8vaBClKFmN+l2e4OdGc
//        //gUqIduTrlESHNjCD4SDJlEMOo87sttYCnkblQ8xjYu3GxRD9
//        //String aapprivate = new BASE64Encoder().encode(privateKey.getEncoded());
//        String aapprivate = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgJxEanaDYYhYECSDaHfdMn34Xq4EenMQdDbuXawUTk6GgCgYIKoEcz1UBgi2hRANCAAQhs8M9c2c+vEtFCdv0k8vaBClKFmN+l2e4OdGc" +
//                "gUqIduTrlESHNjCD4SDJlEMOo87sttYCnkblQ8xjYu3GxRD9";
//
//        MobileInputDataParam oi = new MobileInputDataParam();
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
//        Date date = new Date(System.currentTimeMillis());
//        String rtime = formatter.format(date);
//        oi.setTimestamp(rtime);
//        oi.setEncType("SM4");
//        oi.setSignType("SM2");
//        oi.setAppId("43AF047BBA47FC8A1AE8EFB2XXXXXXXX");
//        oi.setVersion("2.0.1");
//        TestDto ooi = new TestDto();
//        ooi.setAppId("43AF047BBA47FC8A1AE8EFB2XXXXXXXX");
//        ooi.setAppUserId("o8z4C5avQXqC0aWFPf1Mzu6D7WCQ_bd");
//        ooi.setIdNo("410184199110215011");
//        ooi.setIdType("01");
//        ooi.setPhoneNumber("15622163006");
//        ooi.setUserName("左旭栋");
//        oi.setData(ooi);
//        String ooooo = JSONObject.toJSONString(ooi, true);
//        String jsonString = "appId" + oi.getAppId() + "&data=" + ooooo + "&encType=" + oi.getEncType() + "&signType=" + oi.getSignType() + "×tamp=" + oi.getTimestamp() + "&version=" + oi.getVersion();
//
//        //SM2
//        //签名
//        //获取私钥
//        PrivateKey privateKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(aapprivate)));
//
//        // 签名需要使用私钥,使用私钥 初始化签名实例
//        signature.initSign(privateKey);
//        String json = jsonString + "&key=4117E877F5FA0A0188891283E4B617D5";
//        // 签名原文
//        byte[] plainText = json.getBytes(StandardCharsets.UTF_8);
//        // 写入签名原文到算法中
//        signature.update(plainText);
//        // 计算签名值
//        byte[] signatureValue = signature.sign();
//        System.out.println("signature: \n" + new String(Base64.encode(signatureValue)));
//        System.out.println("signature: \n" + Hex.toHexString(signatureValue));
//        oi.setSignData(new String(Base64.encode(signatureValue)));
//
//        PublicKey pub = keyFact.generatePublic(new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(aappy)));
//        /*
//         * 验证结果
//         */
//        signature.initVerify(pub);
//        // 写入待验签的签名原文到算法中
//        signature.update(plainText);
//        // 验签
//        System.out.println("Signature verify result: " + signature.verify(signatureValue));
//
//
//    }
//
//    /**
//     * 获取属性名数组
//     */
//    private static String[] getFieldName(Object o) {
//        Field[] fields = o.getClass().getDeclaredFields();
//        String[] fieldNames = new String[fields.length];
//        for (int i = 0; i < fields.length; i++) {
//            fieldNames[i] = fields[i].getName();
//        }
//        return fieldNames;
//    }
//
//    /**
//     * 根据属性名获取属性值
//     *
//     * @param fieldName 属性名称
//     * @param o         对象
//     * @return
//     */
//    private static Object getFieldValueByName(String fieldName, Object o) {
//        try {
//            String firstLetter = fieldName.substring(0, 1).toUpperCase();
//            String getter = "get" + firstLetter + fieldName.substring(1);
//            Method method = o.getClass().getMethod(getter, new Class[]{});
//            Object value = method.invoke(o, new Object[]{});
//            return value;
//        } catch (Exception e) {
//            System.out.println("根据属性名获取属性值异常:" + e.getMessage());
//            return null;
//        }
//
//    }
//
//}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy