前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Golang语言情怀-第63期 Go 语言标准库翻译 crypto/md5

Golang语言情怀-第63期 Go 语言标准库翻译 crypto/md5

作者头像
李海彬
发布2021-03-09 11:04:22
4370
发布2021-03-09 11:04:22
举报

import "crypto/md5"

md5包实现了MD5哈希算法,

Constants
func Sum(data []byte) [Size]byte
func New() hash.Hash
  • New
  • Sum

Constants

const BlockSize = 64

MD5字节块大小。

const Size = 16

MD5校验和字节数。

func Sum

func Sum(data []byte) [Size]byte

返回数据data的MD5校验和。

package main

import (
    "crypto/md5"
    "fmt"
)

func main() {
    data := []byte("These pretzels are making me thirsty.")
    fmt.Printf("%x", md5.Sum(data))
}

func New

func New() hash.Hash
package main

import (
    "crypto/md5"
    "fmt"
    "io"
)

func main() {
    h := md5.New()
    io.WriteString(h, "The fog is getting thicker!")
    io.WriteString(h, "And Leon's getting laaarger!")
    fmt.Printf("%x", h.Sum(nil))
}
package main

import (
    "crypto/md5"
    "fmt"
    "io"
    "log"
    "os"
)

func main() {
    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))
}

MD5 四种实现方式

func md5_1(s string) {
    m := md5.New()
    m.Write([]byte (s))
    fmt.Println(hex.EncodeToString(m.Sum(nil)))
}
func md5_2(s string) {
    m := md5.Sum([]byte (s))
    fmt.Println(hex.EncodeToString(m[:]))
}func md5_3(s string) {
    m := md5.Sum([]byte(s))
    fmt.Printf("%x", m)
    fmt.Println()
}

func md5_4(s string) {
    m := md5.New()
    io.WriteString(m, s)
    fmt.Println(hex.EncodeToString(m.Sum(nil)))
}



参考资料:

Go语言中文文档

http://www.golang.ltd/

Go语言官方文档

https://golang.google.cn/

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-03-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言情怀 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Constants
  • func Sum
  • func New
  • MD5 四种实现方式
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档