Skip to content

Commit

Permalink
crypt/mwords: add misc function to get N random words from wordlist
Browse files Browse the repository at this point in the history
  • Loading branch information
cpl committed May 7, 2019
1 parent d1fc6af commit 9b31752
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
23 changes: 22 additions & 1 deletion crypt/mwords/utility.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package mwords

import "math/big"
import (
"math/big"
"math/rand"
"time"
)

// bit mask for 11 least significant bits
var bits0to11 = big.NewInt(0x7FF)
Expand Down Expand Up @@ -46,3 +50,20 @@ func isValidEntropy(bits uint) bool {
}
return true
}

// RandomWords will return n random words from the wordlist.
func RandomWords(n uint) []string {
// seed RNG
rand.Seed(time.Now().UTC().UnixNano())

// return slice
ret := make([]string, n)

// get n random words
for n > 0 {
ret[n-1] = mnemonicWords[rand.Int()%Count]
n--
}

return ret
}
12 changes: 12 additions & 0 deletions crypt/mwords/utility_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package mwords

import (
"testing"

"cpl.li/go/cryptor/tests"
)

func TestEntropyBits(t *testing.T) {
Expand All @@ -26,3 +28,13 @@ func TestEntropyBits(t *testing.T) {
}
}
}

func assertRandomWords(t *testing.T, num uint) {
tests.AssertEqual(t, uint(len(RandomWords(num))), num, "invalid word count")
}

func TestRandomWords(t *testing.T) {
for i := uint(0); i < 100; i++ {
assertRandomWords(t, i)
}
}

0 comments on commit 9b31752

Please sign in to comment.