publicclassSM2UtilextendsSM2GennerateKeyPair{/** 素数p */publicstaticfinalBigInteger p =newBigInteger("FFFFFFFE"+"FFFFFFFF"+"FFFFFFFF"+"FFFFFFFF"+"FFFFFFFF"+"00000000"+"FFFFFFFF"+"FFFFFFFF",16);/** 系数a */publicstaticfinalBigInteger a =newBigInteger("FFFFFFFE"+"FFFFFFFF"+"FFFFFFFF"+"FFFFFFFF"+"FFFFFFFF"+"00000000"+"FFFFFFFF"+"FFFFFFFC",16);/** 系数b */publicstaticfinalBigInteger b =newBigInteger("28E9FA9E"+"9D9F5E34"+"4D5A9E4B"+"CF6509A7"+"F39789F5"+"15AB8F92"+"DDBCBD41"+"4D940E93",16);/** 坐标x */publicstaticfinalBigInteger xg =newBigInteger("32C4AE2C"+"1F198119"+"5F990446"+"6A39C994"+"8FE30BBF"+"F2660BE1"+"715A4589"+"334C74C7",16);/** 坐标y */publicstaticfinalBigInteger yg =newBigInteger("BC3736A2"+"F4F6779C"+"59BDCEE3"+"6B692153"+"D0A9877C"+"C62A4740"+"02DF32E5"+"2139F0A0",16);/** 基点G, G=(xg,yg),其介记为n */publicstaticfinalBigInteger n =newBigInteger("FFFFFFFE"+"FFFFFFFF"+"FFFFFFFF"+"FFFFFFFF"+"7203DF6B"+"21C6052B"+"53BBF409"+"39D54123",16);privatestaticSecureRandom random =newSecureRandom();privateECCurve.Fp curve;publicstaticECPointG;publicSM2Util(){
curve =newECCurve.Fp(p,a,b);G= curve.createPoint(xg,yg);}}
2.随机数的生成
publicclassSM2Random{privatestaticfinalSecureRandom random =newSecureRandom();publicstaticBigIntegerrandom(BigInteger m){BigInteger r =newBigInteger(256,random);while(r.compareTo(m)>=0){
r =newBigInteger(128,random);}return r;}}
3.获得公私钥对
publicclassSM2GennerateKeyPair{publicSM2KeyPairgenerateKeyPair(){BigInteger d =SM2Random.random(SM2Util.n.subtract(newBigInteger("1")));SM2KeyPair keyPair =newSM2KeyPair(SM2Util.G.multiply(d).normalize(),d);if(SM2CheckPublicKey.checkPublicKey(keyPair.getPublicKey())){System.out.println("成功生成密钥");return keyPair;}else{System.err.println("生成密钥失败");returnnull;}}}