Updated GetChar() method to use a much faster and optimized algorithm

This commit is contained in:
Winni Neessen 2021-10-24 20:13:37 +02:00
parent b6f60f7c1c
commit 3e8be112fe
Signed by: wneessen
GPG key ID: 5F3AF39B820C119D
5 changed files with 50 additions and 24 deletions

View file

@ -4,9 +4,12 @@
<option name="autoReloadType" value="ALL" />
</component>
<component name="ChangeListManager">
<list default="true" id="e32960c0-29e5-4669-9fc2-ef12314486ce" name="Changes" comment="Updated README.md and added code-example for programmatic use">
<list default="true" id="e32960c0-29e5-4669-9fc2-ef12314486ce" name="Changes" comment="Some parts of the Config struct don't need exporting">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/config/config.go" beforeDir="false" afterPath="$PROJECT_DIR$/config/config.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/cmd/apg/apg.go" beforeDir="false" afterPath="$PROJECT_DIR$/cmd/apg/apg.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/cmd/apg/apg_test.go" beforeDir="false" afterPath="$PROJECT_DIR$/cmd/apg/apg_test.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example-code/simple-password-generator/main.go" beforeDir="false" afterPath="$PROJECT_DIR$/example-code/simple-password-generator/main.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/random/random.go" beforeDir="false" afterPath="$PROJECT_DIR$/random/random.go" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -107,7 +110,8 @@
<MESSAGE value="More README.md updates" />
<MESSAGE value="Updated CLI usage text to reflect the changes of #27" />
<MESSAGE value="Updated README.md and added code-example for programmatic use" />
<option name="LAST_COMMIT_MESSAGE" value="Updated README.md and added code-example for programmatic use" />
<MESSAGE value="Some parts of the Config struct don't need exporting" />
<option name="LAST_COMMIT_MESSAGE" value="Some parts of the Config struct don't need exporting" />
</component>
<component name="VgoProject">
<integration-enabled>true</integration-enabled>

View file

@ -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)
}

View file

@ -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)
}
@ -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())
}
@ -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())
}
@ -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)
@ -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)
}
}
@ -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])
}

View file

@ -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)
}

View file

@ -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")
}
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
rs := strings.Builder{}
rs.Grow(l)
crl := len(cr)
rp := make([]byte, 8)
_, err := rand.Read(rp)
if err != nil {
return rs.String(), 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
}
returnString[i] = charSlice[randNum]
if idx := int(c & letterIdxMask); idx < crl {
rs.WriteByte(cr[idx])
i--
}
c >>= letterIdxBits
r--
}
return string(returnString), nil
return rs.String(), nil
}
// GetNum generates a random number with given maximum value