I'm not sure if the title is adequate or not but I'm experiencing some strangeness in trying to generate a random string of fixed length.
I have set up a code playground as an example of what I'm talking about. You can hit "Run" as much as you like and the same "random" string will be printed. What am I doing wrong or how to generate random string at each call?
Also, here's the code I used (for history):
package main
import "fmt"
import "time"
import "math/rand"
import "encoding/base64"
// GenerateRandomBytes returns securely generated random bytes.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
return nil, err
}
return b, nil
}
// GenerateRandomString returns a URL-safe, base64 encoded
// securely generated random string.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomString(s int) string {
b, _ := GenerateRandomBytes(s)
return base64.URLEncoding.EncodeToString(b)
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Print(GenerateRandomString(12))
}
Aucun commentaire:
Enregistrer un commentaire