I have encountered two problems while browsing mattermost code
- Why the length of
data []byte
is1+(length*5/8)
? why islength
multiplied by 5? - what is the collision of
rand.Read
? on Linux and FreeBSD,rand.Read
uses getrandom(2) if available
package main
import (
"fmt"
"crypto/rand"
"encoding/base32"
)
func main() {
fmt.Println("Hello, playground")
fmt.Println(NewRandomString(64))
}
var encoding = base32.NewEncoding("ybndrfg8ejkmcpqxot1uwisza345h769")
// NewRandomString returns a random string of the given length.
// The resulting entropy will be (5 * length) bits.
func NewRandomString(length int) string {
data := make([]byte, 1+(length*5/8))
rand.Read(data)
return encoding.EncodeToString(data)[:length]
}
you can try: https://play.golang.org/p/WcS667bP407
Because it's returning a base32 string, and each character of a base32 string holds 5 bits of information. So e.g. if you want to generate a 40-character base32 string, you need 200 bits of randomness, which is achieved by reading 25 (that is, 200 / 8) random bytes.