当前位置:   article > 正文

适用于前后端的SM2国密加密解密_前端sm2加密

前端sm2加密

1.vue 前端

1.1导入依赖及前端代码示例

  1. //导入依赖
  2. npm install --save sm-crypto
  3. //页面引入
  4. import { sm2 } from 'sm-crypto';
  5. methods: {
  6. handleLogin() {
  7. this.$refs.loginForm.validate(valid => {
  8. //示例此处为传入密码加密然后得到加密后的数据this.loginForm.password
  9. this.loginForm.password = this.rsaPublicData(this.loginForm.password);
  10. });
  11. },
  12. //加密的方法
  13. rsaPublicData(data) {
  14. //publicKey 为sm2的公钥,公钥用来加密,私钥用来解密
  15. //示例对应的私钥为 74a89d4e78dd999a1882e0202566ee8971464eaf097dede170c86ad683e6e751 用来给后端解密用
  16. const publicKey =
  17. '0476cf11ef3ab14ac836c0bf850c46cb96402c1d7dd4ded1591a4e5a4fea8951a96a842b4d4e7b9ec6fd779ccc6ef8d83ee7623184e6788847ed0c827351d41093';
  18. const cipherMode = 1;
  19. //data为加密的数据
  20. const result = sm2.doEncrypt(data, publicKey, cipherMode);
  21. return result;
  22. },
  23. }

2.后端代码示例

1.导入依赖

  1. <dependency>
  2. <groupId>javax.xml.bind</groupId>
  3. <artifactId>jaxb-api</artifactId>
  4. <version>2.3.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.bouncycastle</groupId>
  8. <artifactId>bcprov-jdk15on</artifactId>
  9. <version>1.69</version>
  10. </dependency>

2.代码示例

1.controller层接口

  1. @PostMapping("/login")
  2. public R login(@RequestBody User user) {
  3. //示例私钥
  4. String privateKey = "74a89d4e78dd999a1882e0202566ee8971464eaf097dede170c86ad683e6e751";
  5. //示例公钥
  6. String publicKey = "0476cf11ef3ab14ac836c0bf850c46cb96402c1d7dd4ded1591a4e5a4fea8951a96a842b4d4e7b9ec6fd779ccc6ef8d83ee7623184e6788847ed0c827351d41093";
  7. System.out.println("privateKey"+privateKey);
  8. //privateKey 为私钥 publicKey为公钥,重要的是私钥
  9. LoSM2.InitKey(privateKey, publicKey);
  10. //user.getPassword()为加密后要解密的数据
  11. String encrypt = LoSM2.decrypt(user.getPassword());
  12. System.out.println("解码密码:+"+encrypt);
  13. return R.ok().data("密码",encrypt);
  14. }

 2.

  1. import org.bouncycastle.crypto.engines.SM2Engine;
  2. /**
  3. * 简单单例SM2加解密, 配合前端
  4. */
  5. public class LoSM2 {
  6. private static String ECNameModel = "sm2p256v1";
  7. private static SM2Engine.Mode CipherMode = SM2Engine.Mode.C1C3C2;
  8. private final String privateKey;
  9. private final String publicKey;
  10. private LoSM2(String privateKey, String publicKey){
  11. this.privateKey = privateKey;
  12. this.publicKey = publicKey;
  13. }
  14. private volatile static LoSM2 instance = null;
  15. public static LoSM2 getInstance(){
  16. if(instance == null){
  17. throw new RuntimeException("请InitKey初始化密钥!!!");
  18. }
  19. return instance;
  20. }
  21. /**
  22. * SM2初始密钥(私钥,公钥)
  23. * @param privateKey
  24. * @param publicKey
  25. * @return
  26. */
  27. public static LoSM2 InitKey(String privateKey, String publicKey) {
  28. System.out.println(instance.privateKey);
  29. if(instance == null){
  30. synchronized(LoSM2.class){
  31. if(instance == null){
  32. instance = new LoSM2(privateKey, publicKey);
  33. }
  34. }
  35. }
  36. return instance;
  37. }
  38. private static class SM2SimpSelfLoader {
  39. private static final LoSM2 instance = InitKey("", "");
  40. }
  41. private static boolean IsInitKey(){
  42. if(instance == null) {
  43. throw new RuntimeException("请InitKey初始化密钥!!!");
  44. }else {
  45. return true;
  46. }
  47. }
  48. /**
  49. * SM2加密
  50. * @param cleartext 明文数据
  51. */
  52. public String encrypt(String cleartext) {
  53. if(!IsInitKey()){
  54. return "";
  55. }
  56. return SimpSM2Util.encrypt(instance.publicKey, cleartext);
  57. }
  58. /**
  59. * SM2解密
  60. * @param cipherData 密文数据
  61. */
  62. public static String decrypt(String cipherData) {
  63. if(!IsInitKey()){
  64. System.out.println(instance);
  65. System.out.println(IsInitKey());
  66. return "";
  67. }
  68. return SimpSM2Util.decrypt(instance.privateKey, cipherData);
  69. }
  70. }

 3.工具类

  1. import org.bouncycastle.asn1.gm.GMNamedCurves;
  2. import org.bouncycastle.asn1.x9.X9ECParameters;
  3. import org.bouncycastle.crypto.engines.SM2Engine;
  4. import org.bouncycastle.crypto.params.*;
  5. import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
  6. import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
  7. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  8. import org.bouncycastle.math.ec.ECPoint;
  9. import org.bouncycastle.util.encoders.Hex;
  10. import org.junit.Test;
  11. import java.math.BigInteger;
  12. import java.security.*;
  13. import java.security.spec.ECGenParameterSpec;
  14. /**
  15. * 简单的sm2
  16. */
  17. public class SimpSM2Util {
  18. /**
  19. * SM2加密算法
  20. * @param publicKey 公钥
  21. * @param data 明文数据
  22. * @return
  23. */
  24. public static String encrypt(String publicKey, String data) {
  25. // 获取一条SM2曲线参数
  26. X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
  27. // 构造ECC算法参数,曲线方程、椭圆曲线G点、大整数N
  28. ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
  29. //提取公钥点
  30. ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(publicKey));
  31. // 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04
  32. ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);
  33. SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
  34. // 设置sm2为加密模式
  35. sm2Engine.init(true, new ParametersWithRandom(publicKeyParameters, new SecureRandom()));
  36. byte[] arrayOfBytes = null;
  37. try {
  38. byte[] in = data.getBytes();
  39. arrayOfBytes = sm2Engine.processBlock(in, 0, in.length);
  40. } catch (Exception e) {
  41. System.out.println("SM2加密时出现异常:"+e.getMessage());
  42. }
  43. return Hex.toHexString(arrayOfBytes);
  44. }
  45. /**
  46. * SM2解密算法
  47. * @param privateKey 私钥
  48. * @param cipherData 密文数据
  49. * @return
  50. */
  51. public static String decrypt(String privateKey, String cipherData) {
  52. // 使用BC库加解密时密文以04开头,传入的密文前面没有04则补上
  53. if (!cipherData.startsWith("04")){
  54. cipherData = "04" + cipherData;
  55. }
  56. byte[] cipherDataByte = Hex.decode(cipherData);
  57. BigInteger privateKeyD = new BigInteger(privateKey, 16);
  58. //获取一条SM2曲线参数
  59. X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
  60. //构造domain参数
  61. ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
  62. ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);
  63. SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
  64. // 设置sm2为解密模式
  65. sm2Engine.init(false, privateKeyParameters);
  66. String result = "";
  67. try {
  68. byte[] arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);
  69. return new String(arrayOfBytes);
  70. } catch (Exception e) {
  71. System.out.println("SM2解密时出现异常:"+e.getMessage());
  72. }
  73. return result;
  74. }
  75. @Test
  76. //生成密钥
  77. public void createKey() throws Exception{
  78. //String M="encryption standard111111111111111111111111111111";
  79. SimpSM2Util sm2 = new SimpSM2Util();
  80. ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
  81. // 获取一个椭圆曲线类型的密钥对生成器
  82. KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
  83. // 使用SM2参数初始化生成器
  84. kpg.initialize(sm2Spec);
  85. // 获取密钥对
  86. KeyPair keyPair = kpg.generateKeyPair();
  87. PublicKey publicKey = keyPair.getPublic();
  88. BCECPublicKey p=(BCECPublicKey)publicKey;
  89. System.out.println("publicKey:"+Hex.toHexString(p.getQ().getEncoded(false)));
  90. PrivateKey privateKey = keyPair.getPrivate();
  91. BCECPrivateKey s=(BCECPrivateKey)privateKey;
  92. System.out.println("privateKey:"+Hex.toHexString(s.getD().toByteArray()));
  93. }
  94. }

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

闽ICP备14008679号