Class Sm2Util

java.lang.Object
com.sure.tool.crypto.Sm2Util

public final class Sm2Util extends Object
国密 SM2 椭圆曲线公钥密码算法工具类(纯 JDK 实现,零第三方依赖)。

实现遵循 GB/T 32918-2016,覆盖密钥对生成、签名/验签(r||s,64 字节)与 加密/解密(C1||C3||C2,C1 为未压缩点)。默认用户标识 1234567812345678。

用法示例:

Sm2Util.Sm2KeyPair kp = Sm2Util.generateKeyPair();
byte[] sig = Sm2Util.sign(kp, "消息".getBytes(StandardCharsets.UTF_8));
boolean ok = Sm2Util.verify(kp.getPublicX(), kp.getPublicY(),
        "消息".getBytes(StandardCharsets.UTF_8), sig);
Since:
1.0.1
Author:
suretool
  • Method Details

    • generateKeyPair

      public static Sm2Util.Sm2KeyPair generateKeyPair()
      生成 SM2 密钥对。
      Returns:
      密钥对
    • sign

      public static byte[] sign(Sm2Util.Sm2KeyPair keyPair, byte[] message)
      SM2 签名(r||s,64 字节)。
      Parameters:
      keyPair - 密钥对
      message - 消息
      Returns:
      签名(r||s)
    • sign

      public static byte[] sign(Sm2Util.Sm2KeyPair keyPair, byte[] message, byte[] userId)
      SM2 签名(r||s,64 字节)。
      Parameters:
      keyPair - 密钥对
      message - 消息
      userId - 用户标识(默认 1234567812345678)
      Returns:
      签名(r||s)
    • verify

      public static boolean verify(BigInteger publicX, BigInteger publicY, byte[] message, byte[] signature)
      SM2 验签。
      Parameters:
      publicX - 公钥 x 坐标
      publicY - 公钥 y 坐标
      message - 消息
      signature - 签名(r||s,64 字节)
      Returns:
      验签是否通过
    • verify

      public static boolean verify(BigInteger publicX, BigInteger publicY, byte[] message, byte[] signature, byte[] userId)
      SM2 验签。
      Parameters:
      publicX - 公钥 x 坐标
      publicY - 公钥 y 坐标
      message - 消息
      signature - 签名(r||s,64 字节)
      userId - 用户标识
      Returns:
      验签是否通过
    • encrypt

      public static byte[] encrypt(BigInteger publicX, BigInteger publicY, byte[] data)
      SM2 加密(C1||C3||C2)。
      Parameters:
      publicX - 公钥 x 坐标
      publicY - 公钥 y 坐标
      data - 明文
      Returns:
      密文
    • decrypt

      public static byte[] decrypt(Sm2Util.Sm2KeyPair keyPair, byte[] cipher)
      SM2 解密(C1||C3||C2)。
      Parameters:
      keyPair - 密钥对
      cipher - 密文
      Returns:
      明文
      Throws:
      CryptoException - 密文非法或校验失败时抛出