Skip to content

Commit

Permalink
Add crypto GenerateEntropy() and GenerateHexNonce()
Browse files Browse the repository at this point in the history
  • Loading branch information
KendallWeihe committed Feb 16, 2024
1 parent b56de28 commit 8fa1b2b
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
36 changes: 36 additions & 0 deletions crypto/entropy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package crypto

import (
"crypto/rand"
"encoding/hex"
"errors"
)

func GenerateEntropy(n int) ([]byte, error) {
if n <= 0 {
return nil, errors.New("entropy byte size must be > 0")
}

bytes := make([]byte, n)
size, err := rand.Read(bytes)
if err != nil {
return nil, err
}

if size != n {
return nil, errors.New("random generation failed to match expected size")
}

return bytes, nil
}

func GenerateHexNonce() (string, error) {
// 16 bytes was chosen because 16 bytes = 128 bits which is considered minimally sufficient
// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf
bytes, err := GenerateEntropy(16)
if err != nil {
return "", err
}

return hex.EncodeToString(bytes), nil
}
40 changes: 40 additions & 0 deletions crypto/entropy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package crypto_test

import (
"testing"

"github.com/alecthomas/assert/v2"
"github.com/tbd54566975/web5-go/crypto"
)

func Test_GenerateEntropy(t *testing.T) {
size := 16
bytes, err := crypto.GenerateEntropy(size)
assert.NoError(t, err)
assert.Equal(t, size, len(bytes))
}

func Test_GenerateEntropy_InvalidSize(t *testing.T) {
bytes, err := crypto.GenerateEntropy(0)
assert.Error(t, err)
assert.Equal(t, nil, bytes)

bytes, err = crypto.GenerateEntropy(-1)
assert.Error(t, err)
assert.Equal(t, nil, bytes)
}

func Test_GenerateHexNonce(t *testing.T) {
nonceMap := make(map[string]bool)

for i := 0; i < 1000000; i++ {
nonce, err := crypto.GenerateHexNonce()
assert.NoError(t, err)
assert.Equal(t, 32, len(nonce))

nonceMap[nonce] = true
}

// Assert that we have 1000000 unique nonces
assert.Equal(t, 1000000, len(nonceMap))
}

0 comments on commit 8fa1b2b

Please sign in to comment.