Created
March 6, 2023 12:13
-
-
Save sicet7/b8aff99ab5b361c884a541861a844148 to your computer and use it in GitHub Desktop.
String seeded random string generator in GO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/sha256" | |
"encoding/base64" | |
"encoding/binary" | |
"fmt" | |
"io" | |
"math/rand" | |
) | |
func getSeededRandomString(seedString string, length int) (string, error) { | |
h := sha256.New() | |
_, err := io.WriteString(h, seedString) | |
if err != nil { | |
return "", err | |
} | |
seed := binary.BigEndian.Uint64(h.Sum(nil)) | |
fmt.Println(seed) | |
myRand := rand.New(rand.NewSource(int64(seed))) | |
output := "" | |
var buffer []byte | |
for len(output) < length { | |
buffer = make([]byte, 32) | |
_, err = myRand.Read(buffer) | |
if err != nil { | |
return "", err | |
} | |
output = output + base64.URLEncoding.EncodeToString(buffer) | |
} | |
return output[:length], nil | |
} | |
func main() { | |
output, err := getSeededRandomString("mart2in", 25) | |
if err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println(output) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment