当前位置:   article > 正文

国密算法-SM2_国密sm2

国密sm2

        国密算法是国家密码局制定标准的一系列算法,包括SM1、SM2、SM3、SM4等。其中,SM1是采用硬件实现的,不予讨论;SM2是非对称加密算法;SM3是摘要算法;SM4是对称加密算法。本篇贴出SM2 Java版本实现生成公私钥及加解密、签名验签代码,供大家一起讨论学习,所有的代码实现都是基于BC库来做的。
        BC库是实现加解密算法的基础库,我们首先要在代码里引入BC库

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

        下面是整个工具类,实现密钥生成,加解密及签名验签功能

  1. import org.apache.commons.codec.binary.Base64;
  2. import org.bouncycastle.crypto.CipherParameters;
  3. import org.bouncycastle.crypto.engines.SM2Engine;
  4. import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
  5. import org.bouncycastle.crypto.params.ECPublicKeyParameters;
  6. import org.bouncycastle.crypto.params.ParametersWithRandom;
  7. import org.bouncycastle.crypto.signers.SM2Signer;
  8. import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil;
  9. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import java.security.*;
  13. import java.security.spec.ECGenParameterSpec;
  14. import java.security.spec.KeySpec;
  15. import java.security.spec.PKCS8EncodedKeySpec;
  16. import java.security.spec.X509EncodedKeySpec;
  17. public class Sm2Utils {
  18. private static Logger log = LoggerFactory.getLogger(Sm2Utils.class);
  19. /**
  20. * SM2算法生成密钥对
  21. *
  22. * @return 密钥对信息
  23. */
  24. public static KeyPair generateSm2KeyPair() {
  25. try {
  26. final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("prime256v1");
  27. final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
  28. SecureRandom random = new SecureRandom();
  29. kpg.initialize(sm2Spec, random);
  30. KeyPair keyPair = kpg.generateKeyPair();
  31. return keyPair;
  32. } catch (Exception e) {
  33. log.error("generate sm2 key pail failed:", e.getMessage(), e);
  34. throw new RuntimeException("生成密钥对失败");
  35. }
  36. }
  37. /**
  38. * sm2公钥加密
  39. *
  40. * @param data
  41. * @param key
  42. * @return
  43. * @throws Exception
  44. */
  45. public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
  46. KeySpec keySpec = new X509EncodedKeySpec(key);
  47. PublicKey publicKey = KeyFactory.getInstance("EC", new BouncyCastleProvider()).generatePublic(keySpec);
  48. ECPublicKeyParameters parameters = (ECPublicKeyParameters) ECUtil.generatePublicKeyParameter(publicKey);
  49. CipherParameters pubKeyParameters = new ParametersWithRandom(parameters);
  50. SM2Engine engine = new SM2Engine(SM2Engine.Mode.C1C2C3);
  51. engine.init(true, pubKeyParameters);
  52. return engine.processBlock(data, 0, data.length);
  53. }
  54. /**
  55. * sm2私钥解密
  56. * @param data
  57. * @param key
  58. * @return
  59. * @throws Exception
  60. */
  61. public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
  62. KeySpec keySpec = new PKCS8EncodedKeySpec(key);
  63. KeyFactory keyfactory = KeyFactory.getInstance("EC", new BouncyCastleProvider());
  64. PrivateKey privateKey = keyfactory.generatePrivate(keySpec);
  65. CipherParameters privateKeyParameters = ECUtil.generatePrivateKeyParameter(privateKey);
  66. SM2Engine engine = new SM2Engine(SM2Engine.Mode.C1C2C3);
  67. engine.init(false, privateKeyParameters);
  68. byte[] byteDate = engine.processBlock(data, 0, data.length);
  69. return byteDate;
  70. }
  71. /**
  72. * 私钥签名
  73. * @param data
  74. * @param key
  75. * @return
  76. * @throws Exception
  77. */
  78. public static byte[] sign(byte[] data, byte[] key) throws Exception {
  79. SM2Signer signer = new SM2Signer();
  80. KeySpec keySpec = new PKCS8EncodedKeySpec(key);
  81. KeyFactory keyfactory = KeyFactory.getInstance("EC", new BouncyCastleProvider());
  82. PrivateKey privateKey = keyfactory.generatePrivate(keySpec);
  83. ECPrivateKeyParameters keyParameters = (ECPrivateKeyParameters) ECUtil.generatePrivateKeyParameter(privateKey);
  84. CipherParameters param = new ParametersWithRandom(keyParameters);
  85. signer.init(true, param);
  86. signer.update(data, 0, data.length);
  87. return signer.generateSignature();
  88. }
  89. /**
  90. * 公钥验签
  91. * @param data
  92. * @param sign
  93. * @param key
  94. * @return
  95. * @throws Exception
  96. */
  97. public static boolean verify(byte[] data, byte[] sign, byte[] key) throws Exception {
  98. SM2Signer signer = new SM2Signer();
  99. KeySpec keySpec = new X509EncodedKeySpec(key);
  100. PublicKey publicKey = KeyFactory.getInstance("EC", new BouncyCastleProvider()).generatePublic(keySpec);
  101. CipherParameters param = ECUtil.generatePublicKeyParameter(publicKey);
  102. signer.init(false, param);
  103. signer.update(data, 0, data.length);
  104. return signer.verifySignature(sign);
  105. }
  106. public static void main(String[] args) throws Exception {
  107. KeyPair keyPair = generateSm2KeyPair();//生成密钥
  108. String publicKey = Base64.encodeBase64String(keyPair.getPublic().getEncoded());
  109. String privateKey = Base64.encodeBase64String(keyPair.getPrivate().getEncoded());
  110. System.out.println("sm2公钥=" + publicKey);
  111. System.out.println("sm2私钥=" + privateKey);
  112. String plaintext = "test";//明文
  113. String signature = Base64.encodeBase64String((sign(plaintext.getBytes("utf-8"),keyPair.getPrivate().getEncoded())));
  114. String ciphertext = Base64.encodeBase64String(encrypt(plaintext.getBytes("utf-8"), Base64.decodeBase64(publicKey)));
  115. System.out.println("ciphertext: " + ciphertext);
  116. System.out.println("signature: " + signature);
  117. boolean result = verify(plaintext.getBytes("utf-8"),Base64.decodeBase64(signature),keyPair.getPublic().getEncoded());
  118. plaintext = new String(decrypt(Base64.decodeBase64(ciphertext), Base64.decodeBase64(privateKey)), "utf-8");
  119. System.out.println("plaintext: " + plaintext);
  120. System.out.println("verify result: " + result);
  121. }
  122. }

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

闽ICP备14008679号