Skip to content

Commit 19f6d56

Browse files
authored
Implement HMAC SHA256 function in nushell (#1195)
> [!WARNING] > I am not a ~lawyer~ cryptosecurity specialist But this implementation seemed to work on several random examples, tested with https://thetexttool.com/tools/hmac-generator
1 parent 5401eae commit 19f6d56

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

modules/README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
- [virtual\_environments](#virtual_environments)
2727
- [weather](#weather)
2828
- [webscraping](#webscraping)
29+
- [crypto](#crypto)
2930

3031

3132
## [after](./after)
@@ -269,3 +270,6 @@ Simple scripts to demonstrate how to scrape websites in nushell. Requires `query
269270
## [result](./result/)
270271
A module to include in the config which enables storing and convenient access of previously output
271272
results.
273+
274+
## [crypto](./crypto/)
275+
Tools for cryptography

modules/crypto/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Cryptography
2+
3+
Tools for cryptography.

modules/crypto/hmac.nu

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
# HMAC-SHA256 implementation
3+
#
4+
# This is a message authentication algorithm,
5+
# using a shared secret key this allows two peers to validate that the message wasn't tampered with.
6+
# Used for example for issuing JWT tokens.
7+
@example "generate a message authentication code" {
8+
"The quick brown fox jumps over the lazy dog"
9+
| hmac sha256 --key "key"
10+
| encode hex
11+
} --result "F7BC83F430538424B13298E6AA6FB143EF4D59A14946175997479DBC2D1A3CD8"
12+
export def "sha256" [--key: oneof<binary, string>]: oneof<string, binary> -> binary {
13+
let message = $in | into binary
14+
let key = $key | into binary
15+
16+
const block_size = 64
17+
18+
let key_len = ($key | length)
19+
let key = match $key_len {
20+
64 => $key,
21+
65.. => ($key | hash sha256 --binary),
22+
_ => {bytes build $key (1..($block_size - $key_len) | each {0x[00]} | bytes collect)}
23+
}
24+
25+
let i_key = $key | bits xor ((1..$block_size) | each {0x[36]} | bytes collect)
26+
let o_key = $key | bits xor ((1..$block_size) | each {0x[5c]} | bytes collect)
27+
28+
bytes build $i_key $message
29+
| hash sha256 --binary
30+
| bytes build $o_key $in
31+
| hash sha256 --binary
32+
}

0 commit comments

Comments
 (0)