Skip to content

hmac_sha256

Mattias Wadman edited this page Mar 15, 2023 · 4 revisions

Put content below in hmac_sha256.jq and use like this:

$ fq -n -L . 'include "hmac_sha256"; "the message to hash here" | hmac_sha256("the shared secret key here") | ., to_hex, to_base64'
    │00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11│0123456789abcdef01│
0x00│9a 59 98 4c f1 ac 00 b0 15 89 dd 6b 08 48 23 a5 c0 2d│.Y.L.......k.H#..-│.: raw bits 0x0-0x1f.7 (32)
0x12│b3 f7 06 2b 9f 83 90 a5 08 25 2e 90 a7 1a│           │...+.....%....│   │
"9a59984cf1ac00b01589dd6b084823a5c02db3f7062b9f8390a508252e90a71a"
"mlmYTPGsALAVid1rCEgjpcAts/cGK5+DkKUIJS6Qpxo="
# from https://en.wikipedia.org/wiki/HMAC
# function hmac is
#     input:
#         key:        Bytes    // Array of bytes
#         message:    Bytes    // Array of bytes to be hashed
#         hash:       Function // The hash function to use (e.g. SHA-1)
#         blockSize:  Integer  // The block size of the hash function (e.g. 64 bytes for SHA-1)
#         outputSize: Integer  // The output size of the hash function (e.g. 20 bytes for SHA-1)
#     // Compute the block sized key
#     block_sized_key = computeBlockSizedKey(key, hash, blockSize)
#     o_key_pad ← block_sized_key xor [0x5c blockSize]   // Outer padded key
#     i_key_pad ← block_sized_key xor [0x36 blockSize]   // Inner padded key
#     return  hash(o_key_pad ∥ hash(i_key_pad ∥ message))
# function computeBlockSizedKey is
#     input:
#         key:        Bytes    // Array of bytes
#         hash:       Function // The hash function to use (e.g. SHA-1)
#         blockSize:  Integer  // The block size of the hash function (e.g. 64 bytes for SHA-1)
#     // Keys longer than blockSize are shortened by hashing them
#     if (length(key) > blockSize) then
#         key = hash(key)
#     // Keys shorter than blockSize are padded to blockSize by padding with zeros on the right
#     if (length(key) < blockSize) then
#         return  Pad(key, blockSize) // Pad key with zeros to make it blockSize bytes long
#     return  key

def hmac_sha256($key):
  def block_size: 64; # internal block size
  def block_sized_key:
    if length > block_size then to_sha256 | explode
    else . + [range(block_size-length) | 0]
    end;
  def xor($a; $b): [$a, $b] | transpose | map(bxor(.[0];.[1]));
  ( . as $message
  | ($key | tobytes | explode | block_sized_key) as $block_sized_key
  | xor($block_sized_key; [range(block_size) | 0x5c ]) as $o_key_pad
  | xor($block_sized_key; [range(block_size) | 0x36 ]) as $i_key_pad
  | [ $o_key_pad
    , [$i_key_pad, $message] | to_sha256
    ]
  | to_sha256
  );
Clone this wiki locally