Skip to content

Instantly share code, notes, and snippets.

@prozacchiwawa
Created March 30, 2017 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save prozacchiwawa/d51b4e49e59a2aa0d3a28b328f62627d to your computer and use it in GitHub Desktop.
Save prozacchiwawa/d51b4e49e59a2aa0d3a28b328f62627d to your computer and use it in GitHub Desktop.
module HmacSha256 exposing (hmac, packedStringOfIntArray, intArrayOfPackedString, presentableIntArray, presentationToIntArray)
import Array exposing (Array)
import Bitwise
import Char
import Debug exposing (log)
import ParseInt as I
{-- Note: relies on a modified version of billstclair's sha256 module with utf-8 handling disabled --}
import Sha256 exposing (sha256)
hmacBlockSize : Int
hmacBlockSize = 64
hextuples : String -> Array String
hextuples s =
Array.initialize ((String.length s) // 2) identity
|> Array.map (\i -> String.slice (i * 2) (i * 2 + 2) s)
presentationToIntArray : String -> Array Int
presentationToIntArray =
hextuples >> Array.map (I.parseIntHex >> Result.toMaybe >> Maybe.withDefault 0)
presentableIntArray : Array Int -> String
presentableIntArray =
Array.map (I.toHex >> String.pad 2 '0') >> Array.toList >> String.concat
packedStringOfIntArray : Array Int -> String
packedStringOfIntArray =
Array.map (Char.fromCode >> String.fromChar) >> Array.toList >> String.concat
intArrayOfPackedString : String -> Array Int
intArrayOfPackedString =
String.toList >> Array.fromList >> Array.map Char.toCode
sha256Ints : Array Int -> Array Int
sha256Ints =
packedStringOfIntArray >> Sha256.sha256 >> presentationToIntArray
arrayPad : Int -> Int -> Array Int -> Array Int
arrayPad n v a =
if Array.length a >= n then
a
else
Array.append a (Array.repeat (n - (Array.length a)) v)
xor : Int -> Array Int -> Array Int
xor v = Array.map (Bitwise.xor v)
hmac : Array Int -> Array Int -> Array Int
hmac key msg =
if Array.length key > hmacBlockSize then
hmac (sha256Ints key) msg
else if Array.length key < hmacBlockSize then
hmac (arrayPad hmacBlockSize 0 key) msg
else
let o_key_pad = xor 0x5c key in
let i_key_pad = xor 0x36 key in
sha256Ints (Array.append o_key_pad (sha256Ints (Array.append i_key_pad msg)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment