Guomi.SM2 (guomi v0.4.2)

Copy Markdown View Source

SM2 helpers built on top of OTP crypto/public_key capabilities.

SM2 is a Chinese commercial cryptographic algorithm standard, including:

  • Key pair generation
  • Digital signature helpers using SM3 prehashing and OTP ECDSA primitives
  • Encryption/decryption helpers using an internal ECDH + SM3 KDF construction

If the runtime/OpenSSL does not expose SM2 primitives, APIs return {:error, :unsupported}.

Compatibility

sign/2 and verify/3 currently operate on raw 64-byte ECDSA-style signatures over an SM3 digest. They do not expose the SM2 user ID/ZA parameterization used by some interoperable SM2 signature profiles.

encrypt/2 and decrypt/2 use this package's internal ciphertext format: C1 || C2 || C3, where C1 is a 65-byte ephemeral public key and C3 is an SM3 MAC. This format is intended for Guomi-to-Guomi round trips and should not be assumed to interoperate with OpenSSL or other SM2 implementations.

Example

# Key pair generation
{:ok, private_key, public_key} = Guomi.SM2.generate_keypair()

# Sign and verify
{:ok, signature} = Guomi.SM2.sign("message", private_key)
{:ok, true} = Guomi.SM2.verify("message", signature, public_key)

# Encrypt and decrypt
{:ok, ciphertext} = Guomi.SM2.encrypt("secret", public_key)
{:ok, plaintext} = Guomi.SM2.decrypt(ciphertext, private_key)

Summary

Types

error_reason()

@type error_reason() ::
  :unsupported | :invalid_key | :decryption_failed | :invalid_ciphertext

Functions

decrypt(ciphertext, private_key)

@spec decrypt(binary(), binary()) :: {:ok, binary()} | {:error, error_reason()}

Decrypt ciphertext using SM2 decryption algorithm.

Parameters

  • ciphertext: The encrypted data
  • private_key: The recipient's private key

Returns

  • {:ok, plaintext} on success
  • {:error, reason} on failure

Example

{:ok, private_key, public_key} = Guomi.SM2.generate_keypair()
{:ok, ciphertext} = Guomi.SM2.encrypt("secret message", public_key)
{:ok, plaintext} = Guomi.SM2.decrypt(ciphertext, private_key)

encrypt(plaintext, public_key)

@spec encrypt(binary() | iodata(), binary()) ::
  {:ok, binary()} | {:error, error_reason()}

Encrypt plaintext using SM2 encryption algorithm.

Parameters

  • plaintext: The data to encrypt
  • public_key: The recipient's public key

Returns

  • {:ok, ciphertext} on success
  • {:error, reason} on failure

Example

{:ok, private_key, public_key} = Guomi.SM2.generate_keypair()
{:ok, ciphertext} = Guomi.SM2.encrypt("secret message", public_key)

generate_keypair()

@spec generate_keypair() :: {:ok, binary(), binary()} | {:error, :unsupported}

sign(message, private_key)

@spec sign(binary() | iodata(), binary()) :: {:ok, binary()} | {:error, :unsupported}

supported?()

@spec supported?() :: boolean()

verify(message, signature, public_key)

@spec verify(binary() | iodata(), binary(), binary()) ::
  {:ok, boolean()} | {:error, :unsupported}