This is a creation in Article, where the information may have evolved or changed.
A friend sends a codes that calculates the MD5 value written in Golang:
Package Mainimport ("Crypto/md5" "FMT") func main () {hash: = MD5. New () B: = []byte ("test") hash. Write (b) fmt. Printf ("%x%x\n", hash.) Sum (nil), MD5. Sum (b))}
From the above calculation effect, MD5. Sum (b) = hash. Write (b) + hash. Sum (nil).
As for its reasons, see the following comments from StackOverflow:
The definition of Sum:func (D0 *digest) Sum (in []byte) []byte { //Make a copy of D0 so, caller can keep writing and summing. D: = *d0 Hash: = D.checksum () return append (In, hash[:] ...)} When you call sum (nil) it returns D.checksum () directly as a byte slice, however if call sum ([]byte) it appends D.CHEC Ksum () to your input.
As you can see from the text above, the write function will clear the string inside the MD5 object and use its arguments as the new internal string. The SUM function computes the MD5 value of the internal string and appends the input parameter to the internal string.
Can think: hash. Write (b) + hash. Sum (nil) = hash. Write (nil) + hash. Sum (b) + hash. Sum (nil) = MD5. Sum (b).
The following code verifies the above equation:
Package Mainimport ("Crypto/md5" "FMT") func main () {hash: = MD5. New () B: = []byte ("test") hash. Write (b) fmt. Printf ("%x%x\n", hash.) Sum (nil), MD5. Sum (b)) hash. Write (nil) fmt. Printf ("%x%x\n", hash.) Sum (b), hash. Sum (nil))}
This note. Declined reprint.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.