what is the collision of rand.Read

363 Views Asked by At

I have encountered two problems while browsing mattermost code

  1. Why the length of data []byte is 1+(length*5/8)? why is length multiplied by 5?
  2. 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

refer to https://github.com/mattermost/mattermost-server/blob/fc60a1e8dd9d1a225687aead0684035ee63d7562/model/utils.go#L184

1

There are 1 best solutions below

0
On

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.