当前位置:   article > 正文

国密:生成SM2秘钥、加解密及加验签_sm2加密

sm2加密

国密改造已经持续了很长时间了,相信很多从事金融科技类的程序猿都遇到过这个需求。这篇文章就为大家带来笔者对于国密改造的一些经验,主要是代码层面,有兴趣的同学可以研究下国密的算法模型!

注:本文所用到的工具类并非笔者所写!

目录

一、国密简述

二、依赖准备

三、SM2算法应用

1、生成SM2公私钥

工具类

测试Demo

 2、数据加解密


一、国密简述

国密——国家密码局制定的国家密码算法。主要包含SM1、SM2、SM3、SM4几种方式。

SM1:对称加密,且算法不公开,使用硬件加密,本文不做叙述;

SM2:非对称加密,签名以及生成秘钥速度优于RSA,基于ECC算法,运算效率更高,且更安全;

SM3:摘要,国产杂凑算法,生成长度为256比特,优于MD5以及SHA-1算法;

SM4: 无线局域网标准的分组数据算法。对称加密,密钥长度和分组长度均为128位;

注意

生成SM2 公钥是130 位 前面多了04两个标识符,注意区分!

二、依赖准备

国密主要用到下面的包

  1. <dependency>
  2. <groupId>org.bouncycastle</groupId>
  3. <artifactId>bcpkix-jdk15on</artifactId>
  4. <version>1.57</version>
  5. </dependency>

一定注意版本。实际项目中笔者发现项目其他子工程用到1.56版本的包,所以选择了低版本。

三、SM2算法应用

1、生成SM2公私钥

工具类

  1. package cn.test.encrypt.utils.sm2;
  2. import cn.test.encrypt.utils.Util;
  3. import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
  4. import org.bouncycastle.crypto.digests.SM3Digest;
  5. import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
  6. import org.bouncycastle.crypto.params.ECPublicKeyParameters;
  7. import org.bouncycastle.math.ec.ECPoint;
  8. import java.math.BigInteger;
  9. public class Cipher {
  10. private int ct;
  11. private ECPoint p2;
  12. private SM3Digest sm3keybase;
  13. private SM3Digest sm3c3;
  14. private byte key[];
  15. private byte keyOff;
  16. public Cipher()
  17. {
  18. this.ct = 1;
  19. this.key = new byte[32];
  20. this.keyOff = 0;
  21. }
  22. private void Reset()
  23. {
  24. this.sm3keybase = new SM3Digest();
  25. this.sm3c3 = new SM3Digest();
  26. byte p[] = Util.byteConvert32Bytes(p2.getX().toBigInteger());
  27. this.sm3keybase.update(p, 0, p.length);
  28. this.sm3c3.update(p, 0, p.length);
  29. p = Util.byteConvert32Bytes(p2.getY().toBigInteger());
  30. this.sm3keybase.update(p, 0, p.length);
  31. this.ct = 1;
  32. NextKey();
  33. }
  34. private void NextKey()
  35. {
  36. SM3Digest sm3keycur = new SM3Digest(this.sm3keybase);
  37. sm3keycur.update((byte) (ct >> 24 & 0xff));
  38. sm3keycur.update((byte) (ct >> 16 & 0xff));
  39. sm3keycur.update((byte) (ct >> 8 & 0xff));
  40. sm3keycur.update((byte) (ct & 0xff));
  41. sm3keycur.doFinal(key, 0);
  42. this.keyOff = 0;
  43. this.ct++;
  44. }
  45. public ECPoint Init_enc(SM2 sm2, ECPoint userKey)
  46. {
  47. AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.generateKeyPair();
  48. ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) key.getPrivate();
  49. ECPublicKeyParameters ecpub = (ECPublicKeyParameters) key.getPublic();
  50. BigInteger k = ecpriv.getD();
  51. ECPoint c1 = ecpub.getQ();
  52. this.p2 = userKey.multiply(k);
  53. Reset();
  54. return c1;
  55. }
  56. public void Encrypt(byte data[])
  57. {
  58. this.sm3c3.update(data, 0, data.length);
  59. for (int i = 0; i < data.length; i++)
  60. {
  61. if (keyOff == key.length)
  62. {
  63. NextKey();
  64. }
  65. data[i] ^= key[keyOff++];
  66. }
  67. }
  68. public void Init_dec(BigInteger userD, ECPoint c1)
  69. {
  70. this.p2 = c1.multiply(userD);
  71. Reset();
  72. }
  73. public void Decrypt(byte data[])
  74. {
  75. for (int i = 0; i < data.length; i++)
  76. {
  77. if (keyOff == key.length)
  78. {
  79. NextKey();
  80. }
  81. data[i] ^= key[keyOff++];
  82. }
  83. this.sm3c3.update(data, 0, data.length);
  84. }
  85. public void Dofinal(byte c3[])
  86. {
  87. byte p[] = Util.byteConvert32Bytes(p2.getY().toBigInteger());
  88. this.sm3c3.update(p, 0, p.length);
  89. this.sm3c3.doFinal(c3, 0);
  90. Reset();
  91. }
  92. }
  1. package cn.test.encrypt.utils.sm2;
  2. import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
  3. import org.bouncycastle.crypto.params.ECDomainParameters;
  4. import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
  5. import org.bouncycastle.math.ec.ECCurve;
  6. import org.bouncycastle.math.ec.ECFieldElement;
  7. import org.bouncycastle.math.ec.ECFieldElement.Fp;
  8. import org.bouncycastle.math.ec.ECPoint;
  9. import java.math.BigInteger;
  10. import java.security.SecureRandom;
  11. public class SM2 {
  12. //国密参数
  13. public static String[] ecc_param = {
  14. "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF",
  15. "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC",
  16. "28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93",
  17. "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123",
  18. "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7",
  19. "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0"
  20. };
  21. public static SM2 Instance()
  22. {
  23. return new SM2();
  24. }
  25. public final BigInteger ecc_p;
  26. public final BigInteger ecc_a;
  27. public final BigInteger ecc_b;
  28. public final BigInteger ecc_n;
  29. public final BigInteger ecc_gx;
  30. public final BigInteger ecc_gy;
  31. public final ECCurve ecc_curve;
  32. public final ECPoint ecc_point_g;
  33. public final ECDomainParameters ecc_bc_spec;
  34. public final ECKeyPairGenerator ecc_key_pair_generator;
  35. public final ECFieldElement ecc_gx_fieldelement;
  36. public final ECFieldElement ecc_gy_fieldelement;
  37. public SM2()
  38. {
  39. this.ecc_p = new BigInteger(ecc_param[0], 16);
  40. this.ecc_a = new BigInteger(ecc_param[1], 16);
  41. this.ecc_b = new BigInteger(ecc_param[2], 16);
  42. this.ecc_n = new BigInteger(ecc_param[3], 16);
  43. this.ecc_gx = new BigInteger(ecc_param[4], 16);
  44. this.ecc_gy = new BigInteger(ecc_param[5], 16);
  45. this.ecc_gx_fieldelement = new Fp(this.ecc_p, this.ecc_gx);
  46. this.ecc_gy_fieldelement = new Fp(this.ecc_p, this.ecc_gy);
  47. this.ecc_curve = new ECCurve.Fp(this.ecc_p, this.ecc_a, this.ecc_b);
  48. this.ecc_point_g = new ECPoint.Fp(this.ecc_curve, this.ecc_gx_fieldelement, this.ecc_gy_fieldelement);
  49. this.ecc_bc_spec = new ECDomainParameters(this.ecc_curve, this.ecc_point_g, this.ecc_n);
  50. ECKeyGenerationParameters ecc_ecgenparam;
  51. ecc_ecgenparam = new ECKeyGenerationParameters(this.ecc_bc_spec, new SecureRandom());
  52. this.ecc_key_pair_generator = new ECKeyPairGenerator();
  53. this.ecc_key_pair_generator.init(ecc_ecgenparam);
  54. }
  55. }

生成随机秘钥工具类

  1. package cn.test.encrypt.utils.sm2;
  2. import cn.test.encrypt.utils.Util;
  3. import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
  4. import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
  5. import org.bouncycastle.crypto.params.ECPublicKeyParameters;
  6. import org.bouncycastle.math.ec.ECPoint;
  7. import java.io.IOException;
  8. import java.math.BigInteger;
  9. public class SM2EncDecUtils {
  10. //生成随机秘钥对
  11. public static SM2KeyVO generateKeyPair(){
  12. SM2 sm2 = SM2.Instance();
  13. AsymmetricCipherKeyPair key = null;
  14. while (true){
  15. key=sm2.ecc_key_pair_generator.generateKeyPair();
  16. if(((ECPrivateKeyParameters) key.getPrivate()).getD().toByteArray().length==32){
  17. break;
  18. }
  19. }
  20. ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) key.getPrivate();
  21. ECPublicKeyParameters ecpub = (ECPublicKeyParameters) key.getPublic();
  22. BigInteger privateKey = ecpriv.getD();
  23. ECPoint publicKey = ecpub.getQ();
  24. SM2KeyVO sm2KeyVO = new SM2KeyVO();
  25. sm2KeyVO.setPublicKey(publicKey);
  26. sm2KeyVO.setPrivateKey(privateKey);
  27. //System.out.println("公钥: " + Util.byteToHex(publicKey.getEncoded()));
  28. //System.out.println("私钥: " + Util.byteToHex(privateKey.toByteArray()));
  29. return sm2KeyVO;
  30. }
  31. //数据加密
  32. public static String encrypt(byte[] publicKey, byte[] data) throws IOException
  33. {
  34. if (publicKey == null || publicKey.length == 0)
  35. {
  36. return null;
  37. }
  38. if (data == null || data.length == 0)
  39. {
  40. return null;
  41. }
  42. byte[] source = new byte[data.length];
  43. //将数组data复制到source
  44. System.arraycopy(data, 0, source, 0, data.length);
  45. Cipher cipher = new Cipher();
  46. SM2 sm2 = SM2.Instance();//new自建类,, SM2 sm2 = new SM2();
  47. ECPoint userKey = sm2.ecc_curve.decodePoint(publicKey);
  48. ECPoint c1 = cipher.Init_enc(sm2, userKey);
  49. cipher.Encrypt(source);
  50. byte[] c3 = new byte[32];
  51. cipher.Dofinal(c3);
  52. // System.out.println("C1 " + Util.byteToHex(c1.getEncoded()));
  53. // System.out.println("C2 " + Util.byteToHex(source));
  54. //System.out.println("C3 " + Util.byteToHex(c3));
  55. //C1 C2 C3拼装成加密字串
  56. // C1 | C2 | C3
  57. //return Util.byteToHex(c1.getEncoded()) + Util.byteToHex(source) + Util.byteToHex(c3);
  58. // C1 | C3 | C2
  59. return Util.byteToHex(c1.getEncoded()) + Util.byteToHex(c3) + Util.byteToHex(source);
  60. }
  61. //数据解密
  62. public static byte[] decrypt(byte[] privateKey, byte[] encryptedData) throws IOException
  63. {
  64. if (privateKey == null || privateKey.length == 0)
  65. {
  66. return null;
  67. }
  68. if (encryptedData == null || encryptedData.length == 0)
  69. {
  70. return null;
  71. }
  72. //加密字节数组转换为十六进制的字符串 长度变为encryptedData.length * 2
  73. String data = Util.byteToHex(encryptedData);
  74. /***分解加密字串 C1 | C2 | C3
  75. * (C1 = C1标志位2位 + C1实体部分128位 = 130)
  76. * (C3 = C3实体部分64位 = 64)
  77. * (C2 = encryptedData.length * 2 - C1长度 - C2长度)
  78. byte[] c1Bytes = Util.hexToByte(data.substring(0,130));
  79. int c2Len = encryptedData.length - 97;
  80. byte[] c2 = Util.hexToByte(data.substring(130,130 + 2 * c2Len));
  81. byte[] c3 = Util.hexToByte(data.substring(130 + 2 * c2Len,194 + 2 * c2Len));
  82. */
  83. /***分解加密字串 C1 | C3 | C2
  84. * (C1 = C1标志位2位 + C1实体部分128位 = 130)
  85. * (C3 = C3实体部分64位 = 64)
  86. * (C2 = encryptedData.length * 2 - C1长度 - C2长度)
  87. */
  88. byte[] c1Bytes = Util.hexToByte(data.substring(0,130));
  89. int c2Len = encryptedData.length - 97;
  90. byte[] c3 = Util.hexToByte(data.substring(130,130 + 64));
  91. byte[] c2 = Util.hexToByte(data.substring(194,194 + 2 * c2Len));
  92. SM2 sm2 = SM2.Instance();
  93. BigInteger userD = new BigInteger(1, privateKey);
  94. //通过C1实体字节来生成ECPoint
  95. ECPoint c1 = sm2.ecc_curve.decodePoint(c1Bytes);
  96. Cipher cipher = new Cipher();
  97. cipher.Init_dec(userD, c1);
  98. cipher.Decrypt(c2);
  99. cipher.Dofinal(c3);
  100. //返回解密结果
  101. return c2;
  102. }
  103. }

SM2曲线算法工具类

  1. package cn.test.encrypt.utils.sm2;
  2. import cn.test.encrypt.utils.Util;
  3. import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
  4. import org.bouncycastle.crypto.digests.SM3Digest;
  5. import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
  6. import org.bouncycastle.crypto.params.ECDomainParameters;
  7. import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
  8. import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
  9. import org.bouncycastle.crypto.params.ECPublicKeyParameters;
  10. import org.bouncycastle.math.ec.ECCurve;
  11. import org.bouncycastle.math.ec.ECFieldElement;
  12. import org.bouncycastle.math.ec.ECFieldElement.Fp;
  13. import org.bouncycastle.math.ec.ECPoint;
  14. import java.math.BigInteger;
  15. import java.security.SecureRandom;
  16. public class SM2Factory {
  17. /*-----------------------国密算法相关参数begin-----------
  18. * ------------------*/
  19. //A 第一系数
  20. private static final BigInteger a = new BigInteger("fffffffeffffffffffffffffffffffffffffffff00000000fffffffffffffffc",16);
  21. //B 第二系数
  22. private static final BigInteger b = new BigInteger("28e9fa9e9d9f5e344d5a9e4bcf6509a7f39789f515ab8f92ddbcbd414d940e93",16);
  23. //曲线X系数
  24. private static final BigInteger gx = new BigInteger("32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7",16);
  25. //曲线Y系数
  26. private static final BigInteger gy = new BigInteger("bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0",16);
  27. //生产者顺序系数
  28. private static final BigInteger n = new BigInteger("fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123",16);
  29. //素数
  30. private static final BigInteger p = new BigInteger("fffffffeffffffffffffffffffffffffffffffff00000000ffffffffffffffff",16);
  31. //因子系数 1
  32. private static final int h = 1;
  33. /*-----------------------国密算法相关参数end-----------------------------*/
  34. //一些必要类
  35. public final ECFieldElement ecc_gx_fieldelement;
  36. public final ECFieldElement ecc_gy_fieldelement;
  37. public final ECCurve ecc_curve;
  38. public final ECPoint ecc_point_g;
  39. public final ECDomainParameters ecc_bc_spec;
  40. public final ECKeyPairGenerator ecc_key_pair_generator;
  41. /**
  42. * 初始化方法
  43. * @return
  44. */
  45. public static SM2Factory getInstance(){
  46. return new SM2Factory();
  47. }
  48. public SM2Factory() {
  49. this.ecc_gx_fieldelement = new Fp(this.p,this.gx);
  50. this.ecc_gy_fieldelement = new Fp(this.p, this.gy);
  51. this.ecc_curve = new ECCurve.Fp(this.p, this.a, this.b);
  52. this.ecc_point_g = new ECPoint.Fp(this.ecc_curve, this.ecc_gx_fieldelement,this.ecc_gy_fieldelement);
  53. this.ecc_bc_spec = new ECDomainParameters(this.ecc_curve, this.ecc_point_g, this.n);
  54. ECKeyGenerationParameters ecc_ecgenparam;
  55. ecc_ecgenparam = new ECKeyGenerationParameters(this.ecc_bc_spec, new SecureRandom());
  56. this.ecc_key_pair_generator = new ECKeyPairGenerator();
  57. this.ecc_key_pair_generator.init(ecc_ecgenparam);
  58. }
  59. /**
  60. * 根据私钥、曲线参数计算Z
  61. * @param userId
  62. * @param userKey
  63. * @return
  64. */
  65. public byte[] sm2GetZ(byte[] userId, ECPoint userKey){
  66. SM3Digest sm3 = new SM3Digest();
  67. int len = userId.length * 8;
  68. sm3.update((byte) (len >> 8 & 0xFF));
  69. sm3.update((byte) (len & 0xFF));
  70. sm3.update(userId, 0, userId.length);
  71. byte[] p = Util.byteConvert32Bytes(this.a);
  72. sm3.update(p, 0, p.length);
  73. p = Util.byteConvert32Bytes(this.b);
  74. sm3.update(p, 0, p.length);
  75. p = Util.byteConvert32Bytes(this.gx);
  76. sm3.update(p, 0, p.length);
  77. p = Util.byteConvert32Bytes(this.gy);
  78. sm3.update(p, 0, p.length);
  79. p = Util.byteConvert32Bytes(userKey.normalize().getXCoord().toBigInteger());
  80. sm3.update(p, 0, p.length);
  81. p = Util.byteConvert32Bytes(userKey.normalize().getYCoord().toBigInteger());
  82. sm3.update(p, 0, p.length);
  83. byte[] md = new byte[sm3.getDigestSize()];
  84. sm3.doFinal(md, 0);
  85. return md;
  86. }
  87. /**
  88. * 签名相关值计算
  89. * @param md
  90. * @param userD
  91. * @param userKey
  92. * @param sm2Result
  93. */
  94. public void sm2Sign(byte[] md, BigInteger userD, ECPoint userKey, SM2Result sm2Result) {
  95. BigInteger e = new BigInteger(1, md);
  96. BigInteger k = null;
  97. ECPoint kp = null;
  98. BigInteger r = null;
  99. BigInteger s = null;
  100. do {
  101. do {
  102. // 正式环境
  103. AsymmetricCipherKeyPair keypair = ecc_key_pair_generator.generateKeyPair();
  104. ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) keypair.getPrivate();
  105. ECPublicKeyParameters ecpub = (ECPublicKeyParameters) keypair.getPublic();
  106. k = ecpriv.getD();
  107. kp = ecpub.getQ();
  108. //System.out.println("BigInteger:" + k + "\nECPoint:" + kp);
  109. //System.out.println("计算曲线点X1: "+ kp.getXCoord().toBigInteger().toString(16));
  110. //System.out.println("计算曲线点Y1: "+ kp.getYCoord().toBigInteger().toString(16));
  111. //System.out.println("");
  112. // r
  113. r = e.add(kp.getXCoord().toBigInteger());
  114. r = r.mod(this.n);
  115. } while (r.equals(BigInteger.ZERO) || r.add(k).equals(this.n)||r.toString(16).length()!=64);
  116. // (1 + dA)~-1
  117. BigInteger da_1 = userD.add(BigInteger.ONE);
  118. da_1 = da_1.modInverse(this.n);
  119. // s
  120. s = r.multiply(userD);
  121. s = k.subtract(s).mod(this.n);
  122. s = da_1.multiply(s).mod(this.n);
  123. } while (s.equals(BigInteger.ZERO)||(s.toString(16).length()!=64));
  124. sm2Result.r = r;
  125. sm2Result.s = s;
  126. }
  127. /**
  128. * 验签
  129. * @param md sm3摘要
  130. * @param userKey 根据公钥decode一个ecpoint对象
  131. * @param r 没有特殊含义
  132. * @param s 没有特殊含义
  133. * @param sm2Result 接收参数的对象
  134. */
  135. public void sm2Verify(byte md[], ECPoint userKey, BigInteger r,
  136. BigInteger s, SM2Result sm2Result) {
  137. sm2Result.R = null;
  138. BigInteger e = new BigInteger(1, md);
  139. BigInteger t = r.add(s).mod(this.n);
  140. if (t.equals(BigInteger.ZERO)) {
  141. return;
  142. } else {
  143. ECPoint x1y1 = ecc_point_g.multiply(sm2Result.s);
  144. //System.out.println("计算曲线点X0: "+ x1y1.normalize().getXCoord().toBigInteger().toString(16));
  145. //System.out.println("计算曲线点Y0: "+ x1y1.normalize().getYCoord().toBigInteger().toString(16));
  146. //System.out.println("");
  147. x1y1 = x1y1.add(userKey.multiply(t));
  148. //System.out.println("计算曲线点X1: "+ x1y1.normalize().getXCoord().toBigInteger().toString(16));
  149. //System.out.println("计算曲线点Y1: "+ x1y1.normalize().getYCoord().toBigInteger().toString(16));
  150. //System.out.println("");
  151. sm2Result.R = e.add(x1y1.normalize().getXCoord().toBigInteger()).mod(this.n);
  152. //System.out.println("R: " + sm2Result.R.toString(16));
  153. return;
  154. }
  155. }
  156. }

工具类

  1. package cn.test.encrypt.utils;
  2. import java.math.BigInteger;
  3. public class Util {
  4. /**
  5. * 整形转换成网络传输的字节流(字节数组)型数据
  6. *
  7. * @param num 一个整型数据
  8. * @return 4个字节的自己数组
  9. */
  10. public static byte[] intToBytes(int num) {
  11. byte[] bytes = new byte[4];
  12. bytes[0] = (byte) (0xff & (num >> 0));
  13. bytes[1] = (byte) (0xff & (num >> 8));
  14. bytes[2] = (byte) (0xff & (num >> 16));
  15. bytes[3] = (byte) (0xff & (num >> 24));
  16. return bytes;
  17. }
  18. /**
  19. * 四个字节的字节数据转换成一个整形数据
  20. *
  21. * @param bytes 4个字节的字节数组
  22. * @return 一个整型数据
  23. */
  24. public static int byteToInt(byte[] bytes) {
  25. int num = 0;
  26. int temp;
  27. temp = (0x000000ff & (bytes[0])) << 0;
  28. num = num | temp;
  29. temp = (0x000000ff & (bytes[1])) << 8;
  30. num = num | temp;
  31. temp = (0x000000ff & (bytes[2])) << 16;
  32. num = num | temp;
  33. temp = (0x000000ff & (bytes[3])) << 24;
  34. num = num | temp;
  35. return num;
  36. }
  37. /**
  38. * 长整形转换成网络传输的字节流(字节数组)型数据
  39. *
  40. * @param num 一个长整型数据
  41. * @return 4个字节的自己数组
  42. */
  43. public static byte[] longToBytes(long num) {
  44. byte[] bytes = new byte[8];
  45. for (int i = 0; i < 8; i++) {
  46. bytes[i] = (byte) (0xff & (num >> (i * 8)));
  47. }
  48. return bytes;
  49. }
  50. /**
  51. * 大数字转换字节流(字节数组)型数据
  52. *
  53. * @param n
  54. * @return
  55. */
  56. public static byte[] byteConvert32Bytes(BigInteger n) {
  57. byte tmpd[] = (byte[]) null;
  58. if (n == null) {
  59. return null;
  60. }
  61. if (n.toByteArray().length == 33) {
  62. tmpd = new byte[32];
  63. System.arraycopy(n.toByteArray(), 1, tmpd, 0, 32);
  64. } else if (n.toByteArray().length == 32) {
  65. tmpd = n.toByteArray();
  66. } else {
  67. tmpd = new byte[32];
  68. for (int i = 0; i < 32 - n.toByteArray().length; i++) {
  69. tmpd[i] = 0;
  70. }
  71. System.arraycopy(n.toByteArray(), 0, tmpd, 32 - n.toByteArray().length, n.toByteArray().length);
  72. }
  73. return tmpd;
  74. }
  75. /**
  76. * 换字节流(字节数组)型数据转大数字
  77. *
  78. * @param b
  79. * @return
  80. */
  81. public static BigInteger byteConvertInteger(byte[] b) {
  82. if (b[0] < 0) {
  83. byte[] temp = new byte[b.length + 1];
  84. temp[0] = 0;
  85. System.arraycopy(b, 0, temp, 1, b.length);
  86. return new BigInteger(temp);
  87. }
  88. return new BigInteger(b);
  89. }
  90. /**
  91. * 根据字节数组获得值(十六进制数字)
  92. *
  93. * @param bytes
  94. * @return
  95. */
  96. public static String getHexString(byte[] bytes) {
  97. return getHexString(bytes, true);
  98. }
  99. /**
  100. * 根据字节数组获得值(十六进制数字)
  101. *
  102. * @param bytes
  103. * @param upperCase
  104. * @return
  105. */
  106. public static String getHexString(byte[] bytes, boolean upperCase) {
  107. String ret = "";
  108. for (int i = 0; i < bytes.length; i++) {
  109. ret += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1);
  110. }
  111. return upperCase ? ret.toUpperCase() : ret;
  112. }
  113. /**
  114. * 打印十六进制字符串
  115. *
  116. * @param bytes
  117. */
  118. public static void printHexString(byte[] bytes) {
  119. for (int i = 0; i < bytes.length; i++) {
  120. String hex = Integer.toHexString(bytes[i] & 0xFF);
  121. if (hex.length() == 1) {
  122. hex = '0' + hex;
  123. }
  124. System.out.print("0x" + hex.toUpperCase() + ",");
  125. }
  126. System.out.println("");
  127. }
  128. /**
  129. * Convert hex string to byte[]
  130. *
  131. * @param hexString the hex string
  132. * @return byte[]
  133. */
  134. public static byte[] hexStringToBytes(String hexString) {
  135. if (hexString == null || hexString.equals("")) {
  136. return null;
  137. }
  138. hexString = hexString.toUpperCase();
  139. int length = hexString.length() / 2;
  140. char[] hexChars = hexString.toCharArray();
  141. byte[] d = new byte[length];
  142. for (int i = 0; i < length; i++) {
  143. int pos = i * 2;
  144. d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
  145. }
  146. return d;
  147. }
  148. /**
  149. * Convert char to byte
  150. *
  151. * @param c char
  152. * @return byte
  153. */
  154. public static byte charToByte(char c) {
  155. return (byte) "0123456789ABCDEF".indexOf(c);
  156. }
  157. /**
  158. * 用于建立十六进制字符的输出的小写字符数组
  159. */
  160. private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
  161. '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  162. /**
  163. * 用于建立十六进制字符的输出的大写字符数组
  164. */
  165. private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
  166. '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
  167. /**
  168. * 将字节数组转换为十六进制字符数组
  169. *
  170. * @param data byte[]
  171. * @return 十六进制char[]
  172. */
  173. public static char[] encodeHex(byte[] data) {
  174. return encodeHex(data, true);
  175. }
  176. /**
  177. * 将字节数组转换为十六进制字符数组
  178. *
  179. * @param data byte[]
  180. * @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
  181. * @return 十六进制char[]
  182. */
  183. public static char[] encodeHex(byte[] data, boolean toLowerCase) {
  184. return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
  185. }
  186. /**
  187. * 将字节数组转换为十六进制字符数组
  188. *
  189. * @param data byte[]
  190. * @param toDigits 用于控制输出的char[]
  191. * @return 十六进制char[]
  192. */
  193. protected static char[] encodeHex(byte[] data, char[] toDigits) {
  194. int l = data.length;
  195. char[] out = new char[l << 1];
  196. // two characters form the hex value.
  197. for (int i = 0, j = 0; i < l; i++) {
  198. out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
  199. out[j++] = toDigits[0x0F & data[i]];
  200. }
  201. return out;
  202. }
  203. /**
  204. * 将字节数组转换为十六进制字符串
  205. *
  206. * @param data byte[]
  207. * @return 十六进制String
  208. */
  209. public static String encodeHexString(byte[] data) {
  210. return encodeHexString(data, true);
  211. }
  212. /**
  213. * 将字节数组转换为十六进制字符串
  214. *
  215. * @param data byte[]
  216. * @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
  217. * @return 十六进制String
  218. */
  219. public static String encodeHexString(byte[] data, boolean toLowerCase) {
  220. return encodeHexString(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
  221. }
  222. /**
  223. * 将字节数组转换为十六进制字符串
  224. *
  225. * @param data byte[]
  226. * @param toDigits 用于控制输出的char[]
  227. * @return 十六进制String
  228. */
  229. protected static String encodeHexString(byte[] data, char[] toDigits) {
  230. return new String(encodeHex(data, toDigits));
  231. }
  232. /**
  233. * 将十六进制字符数组转换为字节数组
  234. *
  235. * @param data 十六进制char[]
  236. * @return byte[]
  237. * @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度,将抛出运行时异常
  238. */
  239. public static byte[] decodeHex(char[] data) {
  240. int len = data.length;
  241. if ((len & 0x01) != 0) {
  242. throw new RuntimeException("Odd number of characters.");
  243. }
  244. byte[] out = new byte[len >> 1];
  245. // two characters form the hex value.
  246. for (int i = 0, j = 0; j < len; i++) {
  247. int f = toDigit(data[j], j) << 4;
  248. j++;
  249. f = f | toDigit(data[j], j);
  250. j++;
  251. out[i] = (byte) (f & 0xFF);
  252. }
  253. return out;
  254. }
  255. /**
  256. * 将十六进制字符转换成一个整数
  257. *
  258. * @param ch 十六进制char
  259. * @param index 十六进制字符在字符数组中的位置
  260. * @return 一个整数
  261. * @throws RuntimeException 当ch不是一个合法的十六进制字符时,抛出运行时异常
  262. */
  263. protected static int toDigit(char ch, int index) {
  264. int digit = Character.digit(ch, 16);
  265. if (digit == -1) {
  266. throw new RuntimeException("Illegal hexadecimal character " + ch
  267. + " at index " + index);
  268. }
  269. return digit;
  270. }
  271. /**
  272. * 数字字符串转ASCII码字符串
  273. *
  274. * @param String 字符串
  275. * @return ASCII字符串
  276. */
  277. public static String StringToAsciiString(String content) {
  278. String result = "";
  279. int max = content.length();
  280. for (int i = 0; i < max; i++) {
  281. char c = content.charAt(i);
  282. String b = Integer.toHexString(c);
  283. result = result + b;
  284. }
  285. return result;
  286. }
  287. /**
  288. * 十六进制转字符串
  289. *
  290. * @param hexString 十六进制字符串
  291. * @param encodeType 编码类型4:Unicode,2:普通编码
  292. * @return 字符串
  293. */
  294. public static String hexStringToString(String hexString, int encodeType) {
  295. String result = "";
  296. int max = hexString.length() / encodeType;
  297. for (int i = 0; i < max; i++) {
  298. char c = (char) hexStringToAlgorism(hexString
  299. .substring(i * encodeType, (i + 1) * encodeType));
  300. result += c;
  301. }
  302. return result;
  303. }
  304. /**
  305. * 十六进制字符串装十进制
  306. *
  307. * @param hex 十六进制字符串
  308. * @return 十进制数值
  309. */
  310. public static int hexStringToAlgorism(String hex) {
  311. hex = hex.toUpperCase();
  312. int max = hex.length();
  313. int result = 0;
  314. for (int i = max; i > 0; i--) {
  315. char c = hex.charAt(i - 1);
  316. int algorism = 0;
  317. if (c >= '0' && c <= '9') {
  318. algorism = c - '0';
  319. } else {
  320. algorism = c - 55;
  321. }
  322. result += Math.pow(16, max - i) * algorism;
  323. }
  324. return result;
  325. }
  326. /**
  327. * 十六转二进制
  328. *
  329. * @param hex 十六进制字符串
  330. * @return 二进制字符串
  331. */
  332. public static String hexStringToBinary(String hex) {
  333. hex = hex.toUpperCase();
  334. String result = "";
  335. int max = hex.length();
  336. for (int i = 0; i < max; i++) {
  337. char c = hex.charAt(i);
  338. switch (c) {
  339. case '0':
  340. result += "0000";
  341. break;
  342. case '1':
  343. result += "0001";
  344. break;
  345. case '2':
  346. result += "0010";
  347. break;
  348. case '3':
  349. result += "0011";
  350. break;
  351. case '4':
  352. result += "0100";
  353. break;
  354. case '5':
  355. result += "0101";
  356. break;
  357. case '6':
  358. result += "0110";
  359. break;
  360. case '7':
  361. result += "0111";
  362. break;
  363. case '8':
  364. result += "1000";
  365. break;
  366. case '9':
  367. result += "1001";
  368. break;
  369. case 'A':
  370. result += "1010";
  371. break;
  372. case 'B':
  373. result += "1011";
  374. break;
  375. case 'C':
  376. result += "1100";
  377. break;
  378. case 'D':
  379. result += "1101";
  380. break;
  381. case 'E':
  382. result += "1110";
  383. break;
  384. case 'F':
  385. result += "1111";
  386. break;
  387. }
  388. }
  389. return result;
  390. }
  391. /**
  392. * ASCII码字符串转数字字符串
  393. *
  394. * @param String ASCII字符串
  395. * @return 字符串
  396. */
  397. public static String AsciiStringToString(String content) {
  398. String result = "";
  399. int length = content.length() / 2;
  400. for (int i = 0; i < length; i++) {
  401. String c = content.substring(i * 2, i * 2 + 2);
  402. int a = hexStringToAlgorism(c);
  403. char b = (char) a;
  404. String d = String.valueOf(b);
  405. result += d;
  406. }
  407. return result;
  408. }
  409. /**
  410. * 将十进制转换为指定长度的十六进制字符串
  411. *
  412. * @param algorism int 十进制数字
  413. * @param maxLength int 转换后的十六进制字符串长度
  414. * @return String 转换后的十六进制字符串
  415. */
  416. public static String algorismToHexString(int algorism, int maxLength) {
  417. String result = "";
  418. result = Integer.toHexString(algorism);
  419. if (result.length() % 2 == 1) {
  420. result = "0" + result;
  421. }
  422. return patchHexString(result.toUpperCase(), maxLength);
  423. }
  424. /**
  425. * 字节数组转为普通字符串(ASCII对应的字符)
  426. *
  427. * @param bytearray byte[]
  428. * @return String
  429. */
  430. public static String byteToString(byte[] bytearray) {
  431. String result = "";
  432. char temp;
  433. int length = bytearray.length;
  434. for (int i = 0; i < length; i++) {
  435. temp = (char) bytearray[i];
  436. result += temp;
  437. }
  438. return result;
  439. }
  440. /**
  441. * 二进制字符串转十进制
  442. *
  443. * @param binary 二进制字符串
  444. * @return 十进制数值
  445. */
  446. public static int binaryToAlgorism(String binary) {
  447. int max = binary.length();
  448. int result = 0;
  449. for (int i = max; i > 0; i--) {
  450. char c = binary.charAt(i - 1);
  451. int algorism = c - '0';
  452. result += Math.pow(2, max - i) * algorism;
  453. }
  454. return result;
  455. }
  456. /**
  457. * 十进制转换为十六进制字符串
  458. *
  459. * @param algorism int 十进制的数字
  460. * @return String 对应的十六进制字符串
  461. */
  462. public static String algorismToHEXString(int algorism) {
  463. String result = "";
  464. result = Integer.toHexString(algorism);
  465. if (result.length() % 2 == 1) {
  466. result = "0" + result;
  467. }
  468. result = result.toUpperCase();
  469. return result;
  470. }
  471. /**
  472. * HEX字符串前补0,主要用于长度位数不足。
  473. *
  474. * @param str String 需要补充长度的十六进制字符串
  475. * @param maxLength int 补充后十六进制字符串的长度
  476. * @return 补充结果
  477. */
  478. static public String patchHexString(String str, int maxLength) {
  479. String temp = "";
  480. for (int i = 0; i < maxLength - str.length(); i++) {
  481. temp = "0" + temp;
  482. }
  483. str = (temp + str).substring(0, maxLength);
  484. return str;
  485. }
  486. /**
  487. * 将一个字符串转换为int
  488. *
  489. * @param s String 要转换的字符串
  490. * @param defaultInt int 如果出现异常,默认返回的数字
  491. * @param radix int 要转换的字符串是什么进制的,如16 8 10.
  492. * @return int 转换后的数字
  493. */
  494. public static int parseToInt(String s, int defaultInt, int radix) {
  495. int i = 0;
  496. try {
  497. i = Integer.parseInt(s, radix);
  498. } catch (NumberFormatException ex) {
  499. i = defaultInt;
  500. }
  501. return i;
  502. }
  503. /**
  504. * 将一个十进制形式的数字字符串转换为int
  505. *
  506. * @param s String 要转换的字符串
  507. * @param defaultInt int 如果出现异常,默认返回的数字
  508. * @return int 转换后的数字
  509. */
  510. public static int parseToInt(String s, int defaultInt) {
  511. int i = 0;
  512. try {
  513. i = Integer.parseInt(s);
  514. } catch (NumberFormatException ex) {
  515. i = defaultInt;
  516. }
  517. return i;
  518. }
  519. /**
  520. * 十六进制串转化为byte数组
  521. *
  522. * @return the array of byte
  523. */
  524. public static byte[] hexToByte(String hex)
  525. throws IllegalArgumentException {
  526. if (hex.length() % 2 != 0) {
  527. throw new IllegalArgumentException();
  528. }
  529. char[] arr = hex.toCharArray();
  530. byte[] b = new byte[hex.length() / 2];
  531. for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
  532. String swap = "" + arr[i++] + arr[i];
  533. int byteint = Integer.parseInt(swap, 16) & 0xFF;
  534. b[j] = new Integer(byteint).byteValue();
  535. }
  536. return b;
  537. }
  538. /**
  539. * 字节数组转换为十六进制字符串
  540. *
  541. * @param b byte[] 需要转换的字节数组
  542. * @return String 十六进制字符串
  543. */
  544. public static String byteToHex(byte b[]) {
  545. if (b == null) {
  546. throw new IllegalArgumentException(
  547. "Argument b ( byte array ) is null! ");
  548. }
  549. String hs = "";
  550. String stmp = "";
  551. for (int n = 0; n < b.length; n++) {
  552. stmp = Integer.toHexString(b[n] & 0xff);
  553. if (stmp.length() == 1) {
  554. hs = hs + "0" + stmp;
  555. } else {
  556. hs = hs + stmp;
  557. }
  558. }
  559. return hs.toLowerCase();
  560. //return hs.toUpperCase();
  561. }
  562. public static byte[] subByte(byte[] input, int startIndex, int length) {
  563. byte[] bt = new byte[length];
  564. for (int i = 0; i < length; i++) {
  565. bt[i] = input[i + startIndex];
  566. }
  567. return bt;
  568. }
  569. }

SM2对象

  1. package cn.test.encrypt.utils.sm2;
  2. import cn.test.encrypt.utils.Util;
  3. import cn.test.encrypt.test.SecurityTestAll;
  4. import org.bouncycastle.math.ec.ECPoint;
  5. import java.math.BigInteger;
  6. public class SM2KeyVO {
  7. BigInteger privateKey ;
  8. ECPoint publicKey ;
  9. public BigInteger getPrivateKey() {
  10. return privateKey;
  11. }
  12. public void setPrivateKey(BigInteger privateKey) {
  13. this.privateKey = privateKey;
  14. }
  15. public ECPoint getPublicKey() {
  16. return publicKey;
  17. }
  18. public void setPublicKey(ECPoint publicKey) {
  19. this.publicKey = publicKey;
  20. }
  21. //HardPubKey:3059301306072A8648CE3D020106082A811CCF5501822D03420004+X+Y
  22. //SoftPubKey:04+X+Y
  23. public String getPubHexInSoft(){
  24. return Util.byteToHex(publicKey.getEncoded(true));
  25. //System.out.println("公钥: " + );
  26. }
  27. public String getPubHexInHard(){
  28. return SecurityTestAll.SM2PubHardKeyHead +Util.byteToHex(publicKey.getEncoded(true));
  29. }
  30. public String getPriHexInSoft(){
  31. return Util.byteToHex(privateKey.toByteArray());
  32. }
  33. }

测试Demo

  1. public static void main(String[] args) {
  2. SM2KeyVO initKeyVO = SM2EncDecUtils.generateKeyPair();
  3. System.out.println("初始公钥为: "+initKeyVO.getPubHexInSoft());
  4. System.out.println("初始私钥为: "+initKeyVO.getPriHexInSoft());
  5. }

输出结果:

 2、数据加解密

简单业务描述:使用初始公钥加密工作公钥,使用初始私钥解密加密后公钥;

Demo

  1. public static void main(String[] args) throws IOException {
  2. //生成初始秘钥
  3. SM2KeyVO initKeyVO = SM2EncDecUtils.generateKeyPair();
  4. String initPubKey = initKeyVO.getPubHexInSoft();
  5. String initPriKey = initKeyVO.getPriHexInSoft();
  6. System.out.println("初始公钥为: " + initPubKey);
  7. System.out.println("初始私钥为: " + initPriKey);
  8. //生成工作秘钥
  9. SM2KeyVO serverKey = SM2EncDecUtils.generateKeyPair();
  10. String serverPubKey = serverKey.getPubHexInSoft();
  11. String serverPriKey = serverKey.getPriHexInSoft();
  12. System.out.println("服务端公钥为: " + serverPubKey);
  13. System.out.println("服务端私钥为: " + serverPriKey);
  14. //使用初始公钥加密服务端公钥 注意格式字节数组
  15. String encryptServerPubKey = SM2EncDecUtils.encrypt(Convert.hexToBytes(initPubKey), serverPubKey.getBytes());
  16. System.out.println("加密后公钥:"+encryptServerPubKey);
  17. //使用初始私钥解密服务端公钥 注意格式
  18. byte[] decrypt = SM2EncDecUtils.decrypt(Convert.hexToBytes(initPriKey), Convert.hexToBytes(encryptServerPubKey));
  19. System.out.println("解密后服务端公钥:"+new String(decrypt));
  20. if (serverPubKey.equals(new String(decrypt)))
  21. System.out.println("——————————解密成功——————————");
  22. }

结果:

 至此,SM2的公私钥生成以及加解密就完成了,下一期内容为生成Sign以及验证。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/50048
推荐阅读
相关标签
  

闽ICP备14008679号