Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a random, fixed-length byte array in Go

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 efficient matter? The math/rand methods do not provide a Random Byte function, as far as I am concerned.

Perhaps there is a built-in way, or should I go with generating a random string and converting it to a byte array?

like image 322
Momo Avatar asked Mar 03 '16 19:03

Momo


People also ask

How do you generate a random string of a fixed length in go?

Previous solutions get a random number to designate a random letter by calling rand. Intn() which delegates to Rand. Intn() which delegates to Rand. Int31n() .

How do you generate random bytes in Golang?

Go rand. The rand. Intn function returns, as an int, a non-negative pseudo-random number in [0,n) from the default source. The example prints five random integers. To get different pseudo random values, we seed the random generator with time.

How do you generate random characters in Golang?

Next up, we need to randomly choose a character from the string, we can do that by importing the rand package in Golang. The rand function has a function called Intn, which generates a random number between 0 (inclusive) to the provided number(non-inclusive).

Is a processing of converting a random length string to a fixed length?

A hash is a mathematical function that converts an input of arbitrary length into an encrypted output of a fixed length.


1 Answers

Package rand

import "math/rand"  

func Read

func Read(p []byte) (n int, err error) 

Read generates len(p) random bytes from the default Source and writes them into p. It always returns len(p) and a nil error.

func (*Rand) Read

func (r *Rand) Read(p []byte) (n int, err error) 

Read generates len(p) random bytes and writes them into p. It always returns len(p) and a nil error.

For example,

package main  import (     "math/rand"     "fmt" )  func main() {     token := make([]byte, 4)     rand.Read(token)     fmt.Println(token) } 

Output:

[187 163 35 30] 
like image 198
peterSO Avatar answered Sep 24 '22 19:09

peterSO