Skip to content
This repository has been archived by the owner on Jan 10, 2025. It is now read-only.

Commit

Permalink
new rand token func with crypto/rand + test
Browse files Browse the repository at this point in the history
  • Loading branch information
y-eight committed Nov 16, 2022
1 parent c21907b commit 4db4680
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 12 deletions.
30 changes: 18 additions & 12 deletions helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
package helper

import (
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/base64"
Expand All @@ -30,10 +31,9 @@ import (
"hash/fnv"
"io/ioutil"
"log"
"math/rand"
"math/big"
"net"
"regexp"
"time"

"google.golang.org/grpc/credentials"
)
Expand Down Expand Up @@ -117,19 +117,25 @@ const charset = "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"0123456789"

var seededRand *rand.Rand = rand.New(
rand.NewSource(time.Now().UnixNano()))

func stringWithCharset(length int, charset string) string {
b := make([]byte, length)
for i := range b {
b[i] = charset[seededRand.Intn(len(charset))]
func stringWithCharset(n int64, chars string) (string, error) {
ret := make([]byte, n)
for i := int64(0); i < n; i++ {
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
if err != nil {
return "", err
}
ret[i] = chars[num.Int64()]
}
return string(b)

return string(ret), nil
}

func GenerateRandomToken(length int) string {
return stringWithCharset(length, charset)
func GenerateRandomToken(length int64) string {
token, err := stringWithCharset(length, charset)
if err != nil {
panic("Could not generate a random token, please check func GenerateRandomToken")
}
return token
}

//------------------
Expand Down
43 changes: 43 additions & 0 deletions helper/helper_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package helper

import (
"fmt"
"testing"
)

func Test_stringWithCharset(t *testing.T) {
tests := []struct {
name string
length int64
charset string
}{
{
name: "normal string",
length: 32,
charset: charset,
},
{
name: "0 string",
length: 0,
charset: charset,
},
{
name: "0 charset",
length: 32,
charset: "1",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
str, err := stringWithCharset(tt.length, tt.charset)
fmt.Printf("%v\n", str)
if err != nil {
t.Error("stringWithCharset with errors")
}
if len(str) != int(tt.length) {
t.Errorf("Length of string is not as eypexted: %v != %v", len(str), tt.length)
}
})
}
}

0 comments on commit 4db4680

Please sign in to comment.