Guomi.SM4 (guomi v0.5.3)

Copy Markdown View Source

Pure Elixir SM4 block cipher (GM/T 0002-2012).

Summary

Functions

Decrypts SM4-ECB ciphertext with a 16-byte key.

Decrypts SM4-CBC using the same 16-byte key, 16-byte iv, and padding mode.

Decrypts SM4-CTR data with the original 16-byte key and initial counter block.

Encrypts plaintext with SM4-ECB and a 16-byte key.

Encrypts with SM4-CBC using a 16-byte key and 16-byte unpredictable iv.

Encrypts arbitrary-length input with SM4-CTR.

Returns true; SM4 is implemented entirely in Elixir.

Types

error_reason()

@type error_reason() ::
  :invalid_key_size
  | :invalid_iv_size
  | :invalid_block_size
  | :invalid_padding
  | :unsupported

Functions

decrypt(ciphertext, key, opts \\ [])

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

Decrypts SM4-ECB ciphertext with a 16-byte key.

:padding must match encryption and may be :pkcs7 (default) or :none. Returns an error for invalid key, block size, padding option, or PKCS#7 data.

decrypt_cbc(ciphertext, key, iv, opts \\ [])

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

Decrypts SM4-CBC using the same 16-byte key, 16-byte iv, and padding mode.

Successful padding removal does not authenticate the message.

decrypt_ctr(ciphertext, key, counter, opts \\ [])

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

Decrypts SM4-CTR data with the original 16-byte key and initial counter block.

CTR encryption and decryption are the same operation. This function does not authenticate ciphertext.

encrypt(plaintext, key, opts \\ [])

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

Encrypts plaintext with SM4-ECB and a 16-byte key.

:padding may be :pkcs7 (default) or :none. With :none, the input must be block-aligned. ECB does not provide semantic security or integrity and is unsuitable for structured or sensitive messages.

encrypt_cbc(plaintext, key, iv, opts \\ [])

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

Encrypts with SM4-CBC using a 16-byte key and 16-byte unpredictable iv.

:padding may be :pkcs7 (default) or :none. CBC provides confidentiality only; callers that need integrity must authenticate the IV and ciphertext.

encrypt_ctr(plaintext, key, counter, opts \\ [])

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

Encrypts arbitrary-length input with SM4-CTR.

counter is a 16-byte initial counter block interpreted as a big-endian 128-bit integer. It must never be reused with the same key. CTR has no padding and provides no integrity; consequently opts must be empty.

supported?()

@spec supported?() :: boolean()

Returns true; SM4 is implemented entirely in Elixir.