4

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)

2
  • 1
    Please post your code. (A link to play.golang.org is fine, but it's not a substitute for the code itself.) Commented Mar 9, 2015 at 1:21
  • 2
    Why would you want a "random sha256 hash"? A sha256 hash is not random; it's a deterministic function of its input. If what you need is a random sequence of 256 bits, why should sha256 be involved? Commented Mar 9, 2015 at 1:34

2 Answers 2

13

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))
}
Sign up to request clarification or add additional context in comments.

Comments

4

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.