From 08b94c3a4c698d4708a800f969808811fba338db Mon Sep 17 00:00:00 2001 From: George Shaw Date: Mon, 6 Nov 2017 11:43:26 -0600 Subject: [PATCH] referencing issue #57 --- pkg/api/user/auth.go | 6 +----- pkg/encryption/random_string.go | 24 ++++++++++++---------- pkg/encryption/random_string_test.go | 30 ++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 15 deletions(-) create mode 100644 pkg/encryption/random_string_test.go diff --git a/pkg/api/user/auth.go b/pkg/api/user/auth.go index 4eedb23..36b51f1 100644 --- a/pkg/api/user/auth.go +++ b/pkg/api/user/auth.go @@ -47,11 +47,7 @@ func Auth(res http.ResponseWriter, req *http.Request) bool { return false } - secret, err := encryption.RandomString() - if err != nil { - http.Error(res, err.Error(), http.StatusInternalServerError) - return false - } + secret := encryption.RandomString(16) userDatabaseData.Secret = secret err = ds.Put(database.BUCKET_USERS, []byte(userRequestData.User), userDatabaseData) diff --git a/pkg/encryption/random_string.go b/pkg/encryption/random_string.go index 199bcfc..cbe1de4 100644 --- a/pkg/encryption/random_string.go +++ b/pkg/encryption/random_string.go @@ -2,18 +2,22 @@ package encryption import ( - "crypto/rand" - "fmt" + "math/rand" + "time" ) -func RandomString() (string, error) { - n := 5 - b := make([]byte, n) +const charset = "abcdefghijklmnopqrstuvwxyz" + + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + + "1234567890!@#$%^&*()" - if _, err := rand.Read(b); err != nil { - return "", err +var seed *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano())) + +// RandomString function takes an integer length value in and returns a +// random string of that size built from the charset constant. +func RandomString(length int) string { + b := make([]byte, length) + for i := range b { + b[i] = charset[seed.Intn(len(charset))] } - - s := fmt.Sprintf("%X", b) - return s, nil + return string(b) } diff --git a/pkg/encryption/random_string_test.go b/pkg/encryption/random_string_test.go new file mode 100644 index 0000000..dcd0557 --- /dev/null +++ b/pkg/encryption/random_string_test.go @@ -0,0 +1,30 @@ +// Encryption package has functions inside of it that utilize various encypting and hashing techniques +package encryption + +import "testing" + +func TestRandomString(t *testing.T) { + testData := []struct { + length int + output string + }{ + {16, ""}, + {16, ""}, + {16, ""}, + {16, ""}, + } + + for i := 0; i < len(testData); i++ { + testData[i].output = RandomString(testData[i].length) + } + + for i := 0; i < len(testData)-1; i++ { + compare := testData[i].output + + for ii := i + 1; ii < len(testData); ii++ { + if compare == testData[ii].output { + t.Errorf("Random string generator generated two strings with the same value. (%s - %s)", compare, testData[ii].output) + } + } + } +}