| 1 |
//////////////////////////////////////////////////////////////// |
| 2 |
// Copyright 2016 Galois, Inc. All Rights Reserved |
| 3 |
// |
| 4 |
// Authors: |
| 5 |
// Aaron Tomb : [email protected] |
| 6 |
// Nathan Collins : [email protected] |
| 7 |
// Joey Dodds : [email protected] |
| 8 |
// |
| 9 |
// Licensed under the Apache License, Version 2.0 (the "License"). |
| 10 |
// You may not use this file except in compliance with the License. |
| 11 |
// A copy of the License is located at |
| 12 |
// |
| 13 |
// http://aws.amazon.com/apache2.0 |
| 14 |
// |
| 15 |
// or in the "license" file accompanying this file. This file is distributed |
| 16 |
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 17 |
// express or implied. See the License for the specific language governing |
| 18 |
// permissions and limitations under the License. |
| 19 |
// |
| 20 |
//////////////////////////////////////////////////////////////// |
| 21 |
|
| 22 |
module HMAC where |
| 23 |
|
| 24 |
import SHA256 |
| 25 |
|
| 26 |
//////// Functional version //////// |
| 27 |
|
| 28 |
hmacSHA256 : {pwBytes, msgBytes} |
| 29 |
(fin pwBytes, fin msgBytes |
| 30 |
, 32 >= width msgBytes |
| 31 |
, 64 >= width (8*pwBytes) |
| 32 |
, 64 >= width (8 * (64 + msgBytes)) |
| 33 |
) => [pwBytes][8] -> [msgBytes][8] -> [256] |
| 34 |
hmacSHA256 = hmac `{blockLength=64} SHA256 SHA256 SHA256 |
| 35 |
|
| 36 |
kinit : { pwBytes, blockLength, digest } |
| 37 |
( fin pwBytes, fin blockLength, fin digest ) |
| 38 |
=> ([pwBytes][8] -> [8*digest]) |
| 39 |
-> [pwBytes][8] |
| 40 |
-> [blockLength][8] |
| 41 |
kinit hash key = |
| 42 |
if `pwBytes > (`blockLength : [max (width pwBytes) (width blockLength)]) |
| 43 |
then take `{blockLength} (split (hash key) # (zero : [blockLength][8])) |
| 44 |
else take `{blockLength} (key # (zero : [blockLength][8])) |
| 45 |
|
| 46 |
// Due to limitations of the type system we must accept two |
| 47 |
// separate arguments (both aledgedly the same) for two |
| 48 |
// separate length inputs. |
| 49 |
hmac : { msgBytes, pwBytes, digest, blockLength } |
| 50 |
( fin pwBytes, fin digest, fin blockLength ) |
| 51 |
=> ([blockLength + msgBytes][8] -> [8*digest]) |
| 52 |
-> ([blockLength + digest][8] -> [8*digest]) |
| 53 |
-> ([pwBytes][8] -> [8*digest]) |
| 54 |
-> [pwBytes][8] |
| 55 |
-> [msgBytes][8] |
| 56 |
-> [digest*8] |
| 57 |
hmac hash hash2 hash3 key message = hash2 (okey # internal) |
| 58 |
where |
| 59 |
ks : [blockLength][8] |
| 60 |
ks = kinit hash3 key |
| 61 |
okey = [k ^ 0x5C | k <- ks] |
| 62 |
ikey = [k ^ 0x36 | k <- ks] |
| 63 |
internal = split (hash (ikey # message)) |
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|