Package cn.gmkit.sm9

Class SM9EncMasterKey

java.lang.Object
cn.gmkit.sm9.SM9EncMasterKey
All Implemented Interfaces:
AutoCloseable

public final class SM9EncMasterKey extends Object implements AutoCloseable
SM9 加密主密钥(由 KGC 与加密方使用)。

通过 generate() 生成含私有部分的完整主密钥用于派生用户解密私钥; 通过 importPublicMasterKeyPem(String) 仅导入公开主密钥用于加密。 使用完毕后应调用 close() 释放 native 资源(推荐使用 try-with-resources)。

明文长度限制

SM9 加密单次明文长度上限为 255 字节,超过时 encrypt(byte[], String) 会抛出 SM9Exception;更大数据请采用混合加密 (例如用 SM4 加密数据、用 SM9 封装 SM4 密钥)。
  • Field Details

    • MAX_PLAINTEXT_SIZE

      public static final int MAX_PLAINTEXT_SIZE
      SM9 加密单次明文的最大字节数。
      See Also:
  • Method Details

    • generate

      public static SM9EncMasterKey generate()
      生成新的 SM9 加密主密钥(含私有部分)。
      Returns:
      加密主密钥
      Throws:
      SM9Exception - native 不可用或生成操作失败时抛出
    • extractKey

      public SM9EncKey extractKey(String id)
      为指定用户标识派生解密私钥。
      Parameters:
      id - 用户标识(ID)
      Returns:
      用户解密私钥
      Throws:
      SM9Exception - ID 为空、当前对象已关闭或 native 派生失败时抛出
    • encrypt

      public byte[] encrypt(byte[] plaintext, String id)
      向指定用户标识加密明文(IBE)。
      Parameters:
      plaintext - 明文,长度不得超过 MAX_PLAINTEXT_SIZE
      id - 接收方用户标识
      Returns:
      密文
      Throws:
      SM9Exception - ID/明文无效、明文超过上限、对象已关闭或 native 加密失败时抛出
    • exportEncryptedMasterKeyInfoPem

      public void exportEncryptedMasterKeyInfoPem(String password, String file)
      将主密钥(含私有部分)以口令加密导出为 PEM 文件。
      Parameters:
      password - 加密口令
      file - 输出文件路径
      Throws:
      SM9Exception - 口令/路径为空、对象已关闭或 native 写入失败时抛出
    • importEncryptedMasterKeyInfoPem

      public static SM9EncMasterKey importEncryptedMasterKeyInfoPem(String password, String file)
      从加密 PEM 文件导入主密钥(含私有部分)。
      Parameters:
      password - 解密口令
      file - PEM 文件路径
      Returns:
      加密主密钥
      Throws:
      SM9Exception - native 不可用、参数无效、口令错误或 PEM 读取失败时抛出
    • exportPublicMasterKeyPem

      public void exportPublicMasterKeyPem(String file)
      将公开主密钥导出为 PEM 文件(用于分发给加密方)。
      Parameters:
      file - 输出文件路径
      Throws:
      SM9Exception - 路径为空、对象已关闭或 native 写入失败时抛出
    • importPublicMasterKeyPem

      public static SM9EncMasterKey importPublicMasterKeyPem(String file)
      从 PEM 文件导入公开主密钥(仅含公开部分,用于加密)。
      Parameters:
      file - PEM 文件路径
      Returns:
      仅含公开部分的加密主密钥
      Throws:
      SM9Exception - native 不可用、路径无效或 PEM 读取失败时抛出
    • close

      public void close()
      释放底层 native 资源。重复调用安全。
      Specified by:
      close in interface AutoCloseable