Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Js前台加密,Java后台解密(Hutool) #10

Open
pruidong opened this issue Jun 14, 2024 · 0 comments
Open

Js前台加密,Java后台解密(Hutool) #10

pruidong opened this issue Jun 14, 2024 · 0 comments

Comments

@pruidong
Copy link

 
    // log是Lombok的@Slf4j注解
    //
    // HuTool,生成公钥和私钥(需要引入maven依赖):

    KeyPair pair = SecureUtil.generateKeyPair("SM2");

    byte[] privateKeyBytes = pair.getPrivate().getEncoded();
    byte[] publicKeyBytes = pair.getPublic().getEncoded();

    String privateKeyBase64 = Base64.getEncoder().encodeToString(privateKeyBytes);
    String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKeyBytes);

    System.out.println("私钥(Base64): " + privateKeyBase64);
    System.out.println("公钥(Base64): " + publicKeyBase64);

    SM2 sm2 = SmUtil.sm2(privateKeyBytes, publicKeyBytes);
    // 公钥加密,私钥解密
    String encryptStr = sm2.encryptBase64("你好", KeyType.PublicKey);
    System.out.println(encryptStr);
    String decryptStr = StrUtil.utf8Str(sm2.decrypt(encryptStr, KeyType.PrivateKey));
    System.out.println(decryptStr);



  // 后端解密过程.
  // 把上面生成的公钥和私钥对改成下面的:
  
  private static final String PUBLIC_KEY =
      "公钥";
  private static final String PRIVATE_KEY =
      "私钥";

  public static String decryptStr(String params) {
    try {
      var sm2 = SmUtil.sm2(PRIVATE_KEY, PUBLIC_KEY);
      // 前台cipherMode=1
      sm2.setMode(SM2Engine.Mode.C1C3C2);
      // 把下面这个值的输出返回给前台,这是前台用的pubkeyHex
      // 
      // System.out.println(sm2.getQ(false));
      var decryptResult = StrUtil.utf8Str(sm2.decrypt(params, KeyType.PrivateKey));
      var decryptResult1 = new String(Base64.getDecoder().decode(decryptResult));
      log.info("入参: {},解密后: {}", params, decryptResult1);
      return decryptResult1;
    } catch (Exception exception) {
      log.error("解密失败,入参: {},失败原因: {}", params, exception.getMessage());
      exception.printStackTrace();
    }
    return "";
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant