From 8b80431446bd1c81193db6a7f24ef9878ed06df9 Mon Sep 17 00:00:00 2001
From: "Lucian I. Last"
Date: Mon, 13 Dec 2021 13:47:46 +0000
Subject: [PATCH] Add func to generate random 512 bits key (#122)
---
algo_hs.go | 21 +++++++++++++++++++++
algo_hs_test.go | 13 +++++++++++++
2 files changed, 34 insertions(+)
diff --git a/algo_hs.go b/algo_hs.go
index e915642..6ad6b4d 100644
--- a/algo_hs.go
+++ b/algo_hs.go
@@ -3,10 +3,31 @@ package jwt
import (
"crypto"
"crypto/hmac"
+ "crypto/rand"
"hash"
"sync"
)
+func generateRandomBytes(n int) ([]byte, error) {
+ b := make([]byte, n)
+ _, err := rand.Read(b)
+ if err != nil {
+ return nil, err
+ }
+ return b, nil
+}
+
+// Generates a key of random 512 bits
+func GenerateRandom512Bit() ([]byte, error) {
+ const byteSize = int(512.0 / 8)
+ key, err := generateRandomBytes(byteSize)
+ if err != nil {
+ return nil, err
+ }
+
+ return key, nil
+}
+
// NewSignerHS returns a new HMAC-based signer.
func NewSignerHS(alg Algorithm, key []byte) (*HSAlg, error) {
return newHS(alg, key)
diff --git a/algo_hs_test.go b/algo_hs_test.go
index 877cf40..fab925a 100644
--- a/algo_hs_test.go
+++ b/algo_hs_test.go
@@ -40,6 +40,19 @@ func TestHS(t *testing.T) {
f(HS256, hsKey256, hsKeyAnother256, ErrInvalidSignature)
}
+func TestNewKey(t *testing.T) {
+ key, err := GenerateRandom512Bit()
+ if err != nil {
+ t.Fatalf("Error returned directly from GenerateRandom512Bit: %e", err)
+ }
+
+ // 8 bits to 1 byte
+ const byteCount = int(512.0 / 8)
+ if l := len(key); l != byteCount {
+ t.Fatalf("length of key is %d, want %d", l, byteCount)
+ }
+}
+
var (
hsKey256 = []byte("hmac-secret-key-256")
hsKey384 = []byte("hmac-secret-key-384")