Module: GmSSL::SM3

Extended by:
FFI::Library, Helper
Defined in:
lib/gmssl/sm3.rb

Defined Under Namespace

Classes: SM3_CTX, SM3_DIGEST_CTX, SM3_HMAC_CTX, SM3_KDF_CTX

Constant Summary collapse

SM3_DIGEST_SIZE =
32
SM3_BLOCK_SIZE =
64
SM3_STATE_WORDS =
8
SM3_HMAC_SIZE =
SM3_DIGEST_SIZE
SM3_PBKDF2_MIN_ITER =
10000
SM3_PBKDF2_MAX_ITER =
16777215
SM3_PBKDF2_MAX_SALT_SIZE =
64
SM3_PBKDF2_DEFAULT_SALT_SIZE =
8

Class Method Summary collapse

Methods included from Helper

bytes_to_hex_string, hex_string_to_packed_bytes

Class Method Details

.digest(data) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/gmssl/sm3.rb', line 62

def self.digest(data)
  # Initialize SM3
  sm3_ctx = SM3_CTX.new
  sm3_init(sm3_ctx)
  # Update SM3 context with data
  sm3_update(sm3_ctx, data, data.bytesize)
  # Finalize the hash
  digest = FFI::MemoryPointer.new(:uint8, SM3_DIGEST_SIZE)
  sm3_finish(sm3_ctx, digest)
  digest.read_bytes(SM3_DIGEST_SIZE).unpack1('H*')
end

.hmac(hex_key, data) ⇒ Object



74
75
76
77
78
79
80
81
82
# File 'lib/gmssl/sm3.rb', line 74

def self.hmac(hex_key, data)
  key = hex_string_to_packed_bytes(hex_key)
  ctx = SM3_HMAC_CTX.new
  sm3_hmac_init(ctx, key, key.bytesize)
  sm3_hmac_update(ctx, data, data.bytesize)
  mac = FFI::MemoryPointer.new(:uint8, SM3_HMAC_SIZE)
  sm3_hmac_finish(ctx, mac)
  mac.read_string(SM3_HMAC_SIZE).unpack1('H*')
end

.pbkdf2(psswd, hex_salt, iterations, outlen) ⇒ Object



84
85
86
87
88
89
# File 'lib/gmssl/sm3.rb', line 84

def self.pbkdf2(psswd, hex_salt, iterations, outlen)
  salt = hex_string_to_packed_bytes(hex_salt)
  out = FFI::MemoryPointer.new(:uint8, outlen)
  sm3_pbkdf2(psswd, psswd.bytesize, salt, salt.bytesize, iterations, outlen, out)
  out.read_string(outlen).unpack1('H*')
end