39点博客

39点博客
像小蜜蜂一样生活

【国密SM2算法】创建密钥对、通过base64密钥串生成PublicKey和PrivateKey

   

 一:创建密钥对


System.out.println("----------生成秘钥对start----------------");
// 引入BC库
Security.addProvider(new BouncyCastleProvider());
// 获取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 pk = keyPair.getPublic();
PrivateKey privk= keyPair.getPrivate();
System.out.println("公钥串:"+new BASE64Encoder().encode(keyPair.getPublic().getEncoded()));
System.out.println("私钥串:"+new BASE64Encoder().encode(keyPair.getPrivate().getEncoded()));
System.out.println("公钥对象:"+pk);
System.out.println("----------生成秘钥对end----------------");


   二:解析公钥串生成publickey

        System.out.println("------通过公钥串获取对象------");
        // 引入BC库
        Security.addProvider(new BouncyCastleProvider());
        String base64String =
"MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAELTzwAJ1gWaUoBTm56qEKDwbwVlqMH8FSVqe2zfgajYK3w5gkq5MJAij3lODus99nWl/a9GnZC0HMC0Notc/RAw==";
        byte[] publicBytes = new BASE64Decoder().decodeBuffer(base64String);
        X509EncodedKeySpec eks = new X509EncodedKeySpec(publicBytes);
        KeyFactory kf = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
        ECPublicKey bce2 = (BCECPublicKey) kf.generatePublic(eks);
        System.out.println(java.util.Base64.getEncoder().encodeToString(bce2.getEncoded()));
        System.out.println(hex16(publicBytes));


   三:解析私钥串生成privatekey

         System.out.println("------通过私钥串获取对象------");
        // 引入BC库
        Security.addProvider(new BouncyCastleProvider());
        String  prvString =
            "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgL5WougHVEKajECwDbW38fiDJMStq\n" +
            "Bn3VwxPxhZZPqvegCgYIKoEcz1UBgi2hRANCAASZZ6IKukES6ICKJYwZ9KeiUnMvJudW4+tyn2fl\n" +
            "xMMg0Urq8abPxXnIWGhIQvvjJZS/EcWwvKQQirzA7NVq4LYe";
        byte[] prvBytes22 = new BASE64Decoder().decodeBuffer(prvString);
        PKCS8EncodedKeySpec eks2 = new PKCS8EncodedKeySpec(prvBytes22);
        KeyFactory kf22= KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
        PrivateKey pvk= kf22.generatePrivate(eks2);
        BCECPrivateKey bpve = (BCECPrivateKey) pvk;
        System.out.println("私钥:"+ bpve.getS()+":::16hex:::"+bpve.getS().toString(16));
        System.out.println(hex16(prvBytes22));
        bpve.getEncoded();
        System.out.println(hex16(bpve.getEncoded()));
        System.out.println(pvk);

     

原创类文章未经允许请勿转载:39点博客 » 【国密SM2算法】创建密钥对、通过base64密钥串生成PublicKey和PrivateKey

分享到: +More

评论 抢地板

换个身份

取消评论
  1. #1
    访客
    java.security.InvalidAlgorithmParameterException: unknown curve name: sm2p256v1 这是因为缺什么
    访客 5个月前 (05-18)回复