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:
[CPP] View plaincopy on code to view a snippet derived from my Code slice
Package Main
Import (
"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:
[CPP] View plaincopy on code to view a snippet derived from my Code slice
The definition of Sum:
Func (D0 *digest) Sum (in []byte) []byte {
Make a copy of D0 so that 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. that can be considered as: 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:
[CPP] View plaincopy on code to view a snippet derived from my Code slice
Package Main
Import (
"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.