Skip to content

Commit

Permalink
Add func to generate random 512 bits key (#122)
Browse files Browse the repository at this point in the history
  • Loading branch information
lil5 authored Dec 13, 2021
1 parent d92f7b6 commit 8b80431
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
21 changes: 21 additions & 0 deletions algo_hs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 13 additions & 0 deletions algo_hs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

0 comments on commit 8b80431

Please sign in to comment.