aboutsummaryrefslogtreecommitdiff
path: root/hkdf.go
diff options
context:
space:
mode:
authorOnur Gündüz <ogunduz@gmail.com>2026-03-10 11:58:37 +0100
committerOnur Gündüz <ogunduz@gmail.com>2026-03-10 11:58:37 +0100
commit03b95111f19a93ccee00e8e8e0afaab8112f5484 (patch)
treec0bfd7c5c768b441c901645a5a9a83c533eaf56f /hkdf.go
parentbcb40853f819cdbea99ec5d0ab2ee7594efd7690 (diff)
downloadnoise-03b95111f19a93ccee00e8e8e0afaab8112f5484.tar.gz
noise-03b95111f19a93ccee00e8e8e0afaab8112f5484.zip
Init package
Diffstat (limited to 'hkdf.go')
-rw-r--r--hkdf.go51
1 files changed, 51 insertions, 0 deletions
diff --git a/hkdf.go b/hkdf.go
new file mode 100644
index 0000000..264821f
--- /dev/null
+++ b/hkdf.go
@@ -0,0 +1,51 @@
+package noisehandshake
+
+import (
+ "crypto/hmac"
+ "fmt"
+ "hash"
+
+ "golang.org/x/crypto/blake2b"
+)
+
+const (
+ hashLen = 64
+)
+
+// newBLAKE2b512 returns a new BLAKE2b-512 hash.
+func newBLAKE2b512() hash.Hash {
+ h, err := blake2b.New512(nil)
+ if err != nil {
+ panic(fmt.Sprintf("noisehandshake: could not create BLAKE2b-512 hash: %v", err))
+ }
+ return h
+}
+
+// hkdf performs HMAC-based Extract-and-Expand Key Derivation Function.
+// Returns numChunks of hashLen-sized outputs.
+func hkdf(salt, inputKeyMaterial, info []byte, numChunks int) [][]byte {
+ // Extract phase: PRK = HMAC-Hash(salt, ikm)
+ extractMac := hmac.New(newBLAKE2b512, salt)
+ extractMac.Write(inputKeyMaterial)
+ prk := extractMac.Sum(nil)
+
+ // Expand phase: generate numChunks outputs
+ results := make([][]byte, numChunks)
+ var lastChunk []byte
+
+ for i := range numChunks {
+ expandMac := hmac.New(newBLAKE2b512, prk)
+
+ // T(i) = HMAC(PRK, T(i-1) || info || i)
+ if lastChunk != nil {
+ expandMac.Write(lastChunk)
+ }
+ expandMac.Write(info)
+ expandMac.Write([]byte{byte(i + 1)})
+
+ lastChunk = expandMac.Sum(nil)
+ results[i] = lastChunk
+ }
+
+ return results
+}