forked from Eauldane/SnowcloakUtils
Initial commit - secure RandomStringGenerator implementation
This commit is contained in:
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
bin
|
||||
.idea
|
26
SnowcloakUtils.go
Normal file
26
SnowcloakUtils.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package SnowcloakUtils
|
||||
|
||||
import (
|
||||
"crypto/rand" // Probably better than math/rand for this
|
||||
"log"
|
||||
)
|
||||
|
||||
func GenerateRandomString(length int) string {
|
||||
// C# had optional parameters that allowed lowercase for chardata and gpose lobbies, Go doesn't.
|
||||
// We can probably get away with just uppercase.
|
||||
allowedArray := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
|
||||
random := make([]byte, length)
|
||||
_, err := rand.Read(random)
|
||||
if err != nil {
|
||||
log.Fatalf("Couldn't generate secure slice: %s", err)
|
||||
}
|
||||
allowedLength := len(allowedArray)
|
||||
i := 0
|
||||
charArray := make([]rune, length)
|
||||
for i < length {
|
||||
charArray[i] = allowedArray[int(random[i])%allowedLength] // Casting random[i] due to type mismatch
|
||||
i++
|
||||
}
|
||||
|
||||
return string(charArray)
|
||||
}
|
17
SnowcloakUtils_test.go
Normal file
17
SnowcloakUtils_test.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package SnowcloakUtils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenerateRandomString(t *testing.T) {
|
||||
fmt.Println("Test: 8 chars")
|
||||
fmt.Println(GenerateRandomString(8))
|
||||
fmt.Println("Test: 10 chars")
|
||||
fmt.Println(GenerateRandomString(10))
|
||||
fmt.Println("Test: 15 chars")
|
||||
fmt.Println(GenerateRandomString(15))
|
||||
fmt.Println("Test: 30 chars")
|
||||
fmt.Println(GenerateRandomString(30))
|
||||
}
|
Reference in New Issue
Block a user