39点博客

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

【国密SM2算法】通过公钥坐标XY获取PublicKey对象的两种方法

已知公钥坐标

        X:B5F2DC9B2C5EFB3329FE07FE3AE7D816E95CBECAFDD7F9E5D2AA73EC04C6C332

        Y:7F87AAEB592B531B668DE5C0D56B73D50D2C3102C2C0549A08E765A0B5D05DBE

方法一

        BigInteger X=new BigInteger("B5F2DC9B2C5EFB3329FE07FE3AE7D816E95CBECAFDD7F9E5D2AA73EC04C6C332",16);

        BigInteger Y=new BigInteger("7F87AAEB592B531B668DE5C0D56B73D50D2C3102C2C0549A08E765A0B5D05DBE",16);

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());                 //载入bc库的支持

        ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("sm2p256v1");       //获取bc库内置曲线参数,曲线名称sm2p256v1

        ECDomainParameters ecDomainParameters = new ECDomainParameters(spec.getCurve(),spec.getG(), spec.getN());

        KeyFactory keyFactory= KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);

        ECCurve ecurve = ecDomainParameters.getCurve();          //获取曲线对象

        ECPoint q = ecurve.createPoint(X,Y);        //创建公钥点

        ECParameterSpec ecps = new ECParameterSpec(ecurve,ecDomainParameters.getG(),ecDomainParameters.getN());

        ECPublicKeySpec keySpec = new ECPublicKeySpec(q, ecps);

        PublicKey pk= (ECPublicKey) keyFactory.generatePublic(keySpec);


方法二

  BigInteger X=new BigInteger("B5F2DC9B2C5EFB3329FE07FE3AE7D816E95CBECAFDD7F9E5D2AA73EC04C6C332",16);

        BigInteger Y=new BigInteger("7F87AAEB592B531B668DE5C0D56B73D50D2C3102C2C0549A08E765A0B5D05DBE",16);

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());                 //载入bc库的支持

        ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("sm2p256v1");       //获取bc库内置曲线参数,曲线名称sm2p256v1

        ECDomainParameters ecDomainParameters = new ECDomainParameters(spec.getCurve(),spec.getG(), spec.getN());

        KeyFactory keyFactory= KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);

        ECCurve ecurve = ecDomainParameters.getCurve();          //获取曲线对象

        ECPoint q = ecurve.createPoint(X,Y);        //创建公钥点

        ECParameterSpec ecps = new ECParameterSpec(ecurve,ecDomainParameters.getG(),ecDomainParameters.getN());

        ECPublicKeySpec keySpec = new ECPublicKeySpec(q, ecps);

        PublicKey pk=new BCECPublicKey("BC",keySpec,BouncyCastleProvider.CONFIGURATION);

    

   方法一和方法二只有最后一句不同,前面都是为了获取曲线参数和创建坐标点。分开来写纯粹是为了凑点字数

原创类文章未经允许请勿转载:39点博客 » 【国密SM2算法】通过公钥坐标XY获取PublicKey对象的两种方法

分享到: +More

评论 抢地板

换个身份

取消评论
  1. #1
    访客
    大神,转换出来的公钥对象很奇怪,识别不了公钥的算法标识,按理说sm2p256v1的OID标识是1.2.156.10197.1.501,单打印出来不是: SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(pk.getEncoded());
    System.out.println(subjectPublicKeyInfo.getAlgorithm().getAlgorithm());
    System.out.println(subjectPublicKeyInfo.getAlgorithm().getParameters());
    访客 5年前 (2020-05-25)回复
    • SunShine
      检查下bc包是否是最新版本
      SunShine 4年前 (2020-07-22)回复