Skip to content

Commit

Permalink
Merge pull request #37 from wneessen/rng_change
Browse files Browse the repository at this point in the history
Updated GetChar() method to use a much faster and optimized algorithm
  • Loading branch information
wneessen authored Oct 24, 2021
2 parents b6f60f7 + 3e8be11 commit f094820
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 24 deletions.
10 changes: 7 additions & 3 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion cmd/apg/apg.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ func main() {
sylList[pwString] = pwSyls
default:
charRange := chars.GetRange(&cfgObj)
pwString, err := random.GetChar(&charRange, pwLength)
pwString, err := random.GetChar(charRange, pwLength)
if err != nil {
log.Fatalf("error generating random character range: %s\n", err)
}
Expand Down
12 changes: 6 additions & 6 deletions cmd/apg/apg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func TestGenLength(t *testing.T) {
cfgObj.MaxPassLen = testCase.maxLength
pwLength := config.GetPwLengthFromParams(&cfgObj)
for i := 0; i < 1000; i++ {
pwString, err := random.GetChar(&charRange, pwLength)
pwString, err := random.GetChar(charRange, pwLength)
if err != nil {
t.Errorf("getRandChar returned an error: %q", err)
}
Expand All @@ -99,7 +99,7 @@ func TestGenLength(t *testing.T) {
func TestGetRandChar(t *testing.T) {
t.Run("return_value_is_A_B_or_C", func(t *testing.T) {
charRange := "ABC"
randChar, err := random.GetChar(&charRange, 1)
randChar, err := random.GetChar(charRange, 1)
if err != nil {
t.Fatalf("Random character generation failed => %v", err.Error())
}
Expand All @@ -110,7 +110,7 @@ func TestGetRandChar(t *testing.T) {

t.Run("return_value_has_specific_length", func(t *testing.T) {
charRange := "ABC"
randChar, err := random.GetChar(&charRange, 1000)
randChar, err := random.GetChar(charRange, 1000)
if err != nil {
t.Fatalf("Random character generation failed => %v", err.Error())
}
Expand All @@ -122,7 +122,7 @@ func TestGetRandChar(t *testing.T) {

t.Run("fail", func(t *testing.T) {
charRange := "ABC"
randChar, err := random.GetChar(&charRange, -2000)
randChar, err := random.GetChar(charRange, -2000)
if err == nil {
t.Fatalf("Generated random characters expected to fail, but returned a value => %v",
randChar)
Expand Down Expand Up @@ -255,7 +255,7 @@ func BenchmarkGetRandNum(b *testing.B) {
func BenchmarkGetRandChar(b *testing.B) {
charRange := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\"#/!\\$%&+-*.,?=()[]{}:;~^|"
for i := 0; i < b.N; i++ {
_, _ = random.GetChar(&charRange, 20)
_, _ = random.GetChar(charRange, 20)
}
}

Expand All @@ -269,7 +269,7 @@ func BenchmarkConvertChar(b *testing.B) {
cfgObj.HumanReadable = false
charRange := chars.GetRange(&cfgObj)
for i := 0; i < b.N; i++ {
charToConv, _ := random.GetChar(&charRange, 1)
charToConv, _ := random.GetChar(charRange, 1)
charBytes := []byte(charToConv)
_, _ = spelling.ConvertCharToName(charBytes[0])
}
Expand Down
2 changes: 1 addition & 1 deletion example-code/simple-password-generator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func main() {
}
pl := config.GetPwLengthFromParams(&c)
cs := chars.GetRange(&c)
pw, err := random.GetChar(&cs, pl)
pw, err := random.GetChar(cs, pl)
if err != nil {
panic(err)
}
Expand Down
48 changes: 35 additions & 13 deletions random/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,50 @@ package random

import (
"crypto/rand"
"encoding/binary"
"fmt"
"math/big"
"strings"
)

// Bitmask sizes for the string generators (based on 93 chars total)
const (
letterIdxBits = 7 // 7 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)

// GetChar generates random characters based on given character range
// and password length
func GetChar(charRange *string, pwLength int) (string, error) {
if pwLength <= 0 {
err := fmt.Errorf("provided pwLength value is <= 0: %v", pwLength)
return "", err
func GetChar(cr string, l int) (string, error) {
if l < 1 {
return "", fmt.Errorf("length is negative")
}
rs := strings.Builder{}
rs.Grow(l)
crl := len(cr)

rp := make([]byte, 8)
_, err := rand.Read(rp)
if err != nil {
return rs.String(), err
}
availCharsLength := len(*charRange)
charSlice := []byte(*charRange)
returnString := make([]byte, pwLength)
for i := 0; i < pwLength; i++ {
randNum, err := GetNum(availCharsLength)
if err != nil {
return "", err
for i, c, r := l-1, binary.BigEndian.Uint64(rp), letterIdxMax; i >= 0; {
if r == 0 {
_, err := rand.Read(rp)
if err != nil {
return rs.String(), err
}
c, r = binary.BigEndian.Uint64(rp), letterIdxMax
}
if idx := int(c & letterIdxMask); idx < crl {
rs.WriteByte(cr[idx])
i--
}
returnString[i] = charSlice[randNum]
c >>= letterIdxBits
r--
}
return string(returnString), nil
return rs.String(), nil
}

// GetNum generates a random number with given maximum value
Expand Down

0 comments on commit f094820

Please sign in to comment.