Calculation of MD5 value in Golang

Source: Internet
Author: User
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.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.