Is there a function for Golang which is or nearly is identicle to PHP's openssl_random_pseudo_bytes()
function?
I need this to generate pseudo-random string of bytes in Golang.
Is there a function for Golang which is or nearly is identicle to PHP's openssl_random_pseudo_bytes()
function?
I need this to generate pseudo-random string of bytes in Golang.
Quick and lightweight pseudo-random string of bytes generator
At first define array of bytes that we want to use for our generator( in this case it shall be letters) Then decide how many bits represent one letter(it will allow us take letters one by one) and letter "template" that contains amount of bits for one letter Also I stored maximum index that I can take from my array of bytes
const (
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
StringRandomizer function gets an argument(length of string that I want to get as result)
Basically, this function just a simple loop that creates a new array of bytes with defined length, and pseudo-random elements. Until I did not fill in all required elements of result array(did not put 'n' elements), I get one random letter from my letterBytes const. If length of the string that I want to get at the end more that letterIdxMax, I just create new random sequence of 63 bytes(src.Int63()) and proceed looping
func StringRandomizer(n int) string {
src := rand.NewSource(time.Now().UnixNano())
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; remain-- {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
}
return string(b)
}