Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Random Sha256

I am having trouble getting a random sha256 hash using a timestamp seed:

https://play.golang.org/p/2-_VPe3oFr (dont use playground - time always same)

Does anyone understand why it always returns the same result? (non-playground runs)

like image 412
user2350858 Avatar asked Dec 03 '22 17:12

user2350858


2 Answers

Because you do this:

timestamp := time.Now().Unix()
log.Print(fmt.Sprintf("%x", sha256.Sum256([]byte(string(timestamp))))[:45])

You print the hex form of the SHA-256 digest of the data:

[]byte(string(timestamp))

What is it exactly?

timestamp is of type int64, converting it to string is:

Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points are converted to "\uFFFD".

But its value is not a valid unicode code point so it will always be "\uFFFD" which is efbfbd (UTF-8 encoded), and your code always prints the SHA-256 of the data []byte{0xef, 0xbf, 0xbd} which is (or rather its first 45 hex digits because you slice the result):

83d544ccc223c057d2bf80d3f2a32982c32c3c0db8e26

I guess you wanted to generate some random bytes and calculate the SHA-256 of that, something like this:

data := make([]byte, 10)
for i := range data {
    data[i] = byte(rand.Intn(256))
}
fmt.Printf("%x", sha256.Sum256(data))

Note that if you'd use the crypto/rand package instead of math/rand, you could fill a slice of bytes with random values using the rand.Read() function, and you don't even have to set seed (and so you don't even need the time package):

data := make([]byte, 10)
if _, err := rand.Read(data); err == nil {
    fmt.Printf("%x", sha256.Sum256(data))
}
like image 191
icza Avatar answered Dec 23 '22 20:12

icza


Yes. This:

string(timestamp)

does not do what you think it does, see the spec. Long story short, the timestamp is not a valid unicode code point, so the result is always "\uFFFD".

like image 40
margnus1 Avatar answered Dec 23 '22 21:12

margnus1