golang in md5.Sum (data) and md5.New (). Sum (data)

Original article, reproduced please specify: https://www.cnblogs.com/tkblack/p/11533874.html

Learning for some time golang, we encountered a problem when generating md5 checksum, md5 general we generate the following ways:

data := []byte("hello")
hash := md5.New()
bytes := hash.Sum(nil)
fmt.Printf("%x\n", bytes)    //output:5d41402abc4b2a76b9719d911017c592

or

data := []byte("hello")
bytes := md5.Sum(data)
fmt.Printf("%x\n", bytes)   //output:5d41402abc4b2a76b9719d911017c592

Above two methods are available md5 checksum value is correct, of course, a little difference, the former is returned bytes [] type byte, the latter is returned [Size] byte type, where Size = 16.

Next, we look at another approach:

data := []byte("hello")
hash := md5.New()
bytes := hash.Sum(data)
fmt.Printf("%x\n", bytes)    //output:68656c6c6fd41d8cd98f00b204e9800998ecf8427e

Obviously, this result is not consistent (can not be said to be wrong), you can see the difference from the length, then what difference it here? In fact, this call is two different functions, we look directly at the source:

md5.Sum(data):

// Sum returns the MD5 checksum of the data.
func Sum(data []byte) [Size]byte {
	var d digest
	d.Reset()
	d.Write(data)
	return d.checkSum()
}

md5.New().Sum(data):

func (d *digest) Sum(in []byte) []byte {
	// Make a copy of d so that caller can keep writing and summing.
	d0 := *d
	hash := d0.checkSum()
	return append(in, hash[:]...)
}

In this way, we would be very visually see the difference, the former is calling checksum () method; the latter, first call checksum (), and then in the result of splicing. Therefore, although these two Sum function of the same name, but it is different implementations, the public packet former belonging md5 function, which is a member function of the structure of the digest.

 

Guess you like

Origin www.cnblogs.com/tkblack/p/11533874.html