Go language: MD5 encryption

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang's cryptographic libraries are placed in the crypto directory, where the MD5 library is in the CRYPTO/MD5 package, which mainly provides the new () and sum () functions.

package mainimport (    "crypto/md5"    "encoding/hex"    "fmt")func main() {    data := []byte("Mdroid.cn")    md5Ctx := md5.New()    md5Ctx.Write(data)    cipherStr := md5Ctx.Sum(nil)    fmt.Println(cipherStr)    fmt.Printf("%x\n", md5.Sum(data))    fmt.Printf("%x\n", cipherStr)    fmt.Println(hex.EncodeToString(cipherStr))}

Results:

[24 55 47 68 190 11 229 212 65 82 130 95 125 93 53 9]18372f44be0be5d44152825f7d5d350918372f44be0be5d44152825f7d5d350918372f44be0be5d44152825f7d5d3509

Analysis:

MD5. New () Initializes a MD5 object that returns a hash. The hash object. The function prototype is the Func New () hash. Hash. In fact, the object implemented a hash. The sum interface of the hash. Sum () calculates the MD5 checksum. SUM () function prototype func Sum (data []byte) [Size]byte.
by flipping through the source code can see that he is not the data to verify the calculation, but the hash. The content stored inside the hash object is checksum computed and then appended to data to form a new byte slice. So the usual way to do this is to set data to nil.
The method returns a byte array of size 16, which is a 128bit, 16-byte byte array for MD5.

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.