Generating a random, fixed-length byte array in Go

前端 未结 3 1272
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 03:43

I have a byte array, with a fixed length of 4.

token := make([]byte, 4)

I need to set each byte to a random byte. How can I do so, in the most

3条回答
  •  时光取名叫无心
    2021-02-05 03:53

    Using math.Rand means that you are using the system CSPRNG that your operating system provides. This means using /dev/urandom/ and Windows’ CryptGenRandom API. Go’s crypto/rand package, thankfully, abstracts these implementation details away to minimise the risk of getting it wrong.

    import(
       "crypto/rand"
       "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
    }
    

提交回复
热议问题