先看实现代码:

package main 
import (   
    "crypto/md5"    
    "encoding/hex"    
    "fmt"    
) func main() {   
    h := md5.New()    
    h.Write([]byte("123456")) // 需要加密的字符串为 123456    
    cipherStr := h.Sum(nil)    
    fmt.Println(cipherStr)    
    fmt.Printf("%s\n", hex.EncodeToString(cipherStr)) // 输出加密结果    
}

代码输入效果:

说明:

Golang的加密库都放在crypto目录下,其中MD5库在crypto/md5包中,该包主要提供了New和Sum函数。

这里直接对一串字符串计算MD5。其中通过md5.New()初始化一个MD5对象,其实它是一个hash.Hash对象。 函数原型为:

// New returns a new hash.Hash computing the MD5 checksum.
func New() hash.Hash {d := new(digest)d.Reset()return d}
该对象实现了hash.Hash的Sum接口:计算出校验和。其函数原型 为:// Hash is the common interface implemented by all hash functions.
type Hash interface {// Sum appends the current hash to b and returns the resulting slice.
    // It does not change the underlying hash state.
    Sum(b []byte) []byte…}

Sum 函数是对hash.Hash对象内部存储的内容进行校验和 计算然后将其追加到data的后面形成一个新的byte切片。因此通常的使用方法就是将data置为nil。

该方法返回一个Size大小的byte数组,对于MD5来说就是一个128bit的16字节byte数组。

 

参考资料:

Golang计算MD5
http://gotaly.blog.51cto.com/8861157/1403942

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: go