Skip to content

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

Description

@jpg1024
 
    // 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 "";
  }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions