# MD5 Modules
### Author : 品茶
> 品茶:一般MD5会用到一些数据加密的地方,比如用户数据库的密码字段,分发文件给出文件的校验和防止下载文件被改动。
> 注意:md5是有被撞库的风险,但是我们基本可以忽略不计
## 生成字符串的校验和
~~~
h := md5.New()
io.WriteString(h, "The fog is getting thicker!") // 利用io.Write interface往h里写数据,就是多条数据的和
io.WriteString(h, "And Leon's getting laaarger!")
fmt.Printf("%x", h.Sum(nil)) //h.sum()
~~~
> md5.New()
~~~
// New returns a new hash.Hash computing the MD5 checksum.
func New() hash.Hash {
d := new(digest) //赋值指针
d.Reset() //初始化diest结构体的值
return d //返回一个初始化的结构体
}
~~~
> new()
~~~
// The new built-in function allocates memory. The first argument is a type,
// not a value, and the value returned is a pointer to a newly
// allocated zero value of that type.
// 分配内存,第一个参数为类型,返回的是一个零值的指针。
func new(Type) *Type
~~~
> TYPE digest 结构体
~~~
const (
chunk = 64
init0 = 0x67452301
init1 = 0xEFCDAB89
init2 = 0x98BADCFE
init3 = 0x10325476
)
// digest represents the partial evaluation of a checksum.
type digest struct {
s [4]uint32
x [chunk]byte
nx int
len uint64
}
func (d *digest) Reset() {
d.s[0] = init0
d.s[1] = init1
d.s[2] = init2
d.s[3] = init3
d.nx = 0
d.len = 0
}
~~~
> chekcSum
~~~
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[:]...)
}
~~~
## 文件的校验和
~~~
f, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
h := md5.New()
if _, err := io.Copy(h, f); err != nil {
log.Fatal(err)
}
fmt.Printf("%x", h.Sum(nil))
~~~
## []byte方式
~~~
data := []byte("These pretzels are making me thirsty.")
fmt.Printf("%x", md5.Sum(data))
~~~
## EXP:
~~~
package main
import (
"crypto/md5"
"fmt"
"io"
"log"
"os"
)
func main() {
// []byte数组型
// []byte -> md5
data := []byte("zuoloveyou") //[]byte型
fmt.Println(data)
h := md5.Sum(data)
fmt.Println(h)
fmt.Printf("%x\n", h)
// output
//[122 117 111 108 111 118 101 121 111 117]
//[198 206 119 255 230 157 195 147 195 138 119 136 195 154 148 202]
//c6ce77ffe69dc393c38a7788c39a94ca
// 字符串型
// more string -> md5
h1 := md5.New()
io.WriteString(h1, "zuoloveyou")
io.WriteString(h1, "good job") // => io.WriteString(h1, "zuoloveyougood job")
fmt.Printf("%x\n", h1.Sum(nil))
// output
//a90389da0e251b5d6cf76e618e9943c3
// 生成文件的md5 与mac 命令结果一样
// file -> md5
fd, err := os.Open("src/server/go.png")
if err != nil {
log.Fatalf("main: %v", err)
}
defer fd.Close()
h2 := md5.New()
if _, err := io.Copy(h2, fd); err != nil {
log.Fatal(err)
}
fmt.Printf("%x\n", h2.Sum(nil))
// output
//d90b1d83b799c1555b62447b4330453a
//macbook command
//➜ worker git:(master) ✗ md5 src/server/go.png
//MD5 (src/server/go.png) = d90b1d83b799c1555b62447b4330453a
}
~~~