GO加密模块

常见模块

Keyed-Hash Message Authentication Code 密钥哈希消息认证码

  • HMac 使用密钥对消息签名的算法。

    这个算法,就是在计算哈希的时候,嵌入一个密钥,对MD5,SHA算法都有用,本质上这个算法,就是提供一个SHA(message + salt)的通用计算公式。

1
2
3
4
5
6
func hmacSign(key string, message string) {
mac := hmac.New(md5.New, []byte(key))
mac.Write([]byte(message))
expectedMAC := mac.Sum(nil)
fmt.Println(hex.EncodeToString(expectedMAC))
}

哈希计算 MD5

  • 这个没什么说的,不建议使用的方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 计算字符串MD5
data := []byte("These pretzels are making me thirsty.")
fmt.Printf("%x", md5.Sum(data))

// 计算字符串MD5
h := md5.New()
h.Write([]byte("These pretzels are making me thirsty."))
io.WriteString(h, "The fog is getting thicker!")
io.WriteString(h, "And Leon's getting laaarger!")
fmt.Printf("%x", h.Sum(nil))

// 计算文件MD5
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))

随机数生成 rand

  • 在Linux上使用getrandom(2) 否则从/dev/urandom获取。

  • By default, getrandom() draws entropy from the urandom source (i.e.,
    the same source as the /dev/urandom device). This behavior can be
    changed via the flags argument.

  • OpenBSD 使用getentropy(2)

  • 其它Unix-like systems从/dev/urandom生成

  • Windows上使用CryptGenRandom API生成

1
2
3
4
nonce := make([]byte, 12)
io.ReadFull(rand.Reader, nonce)

rand.Read(b)//此方法等价于上面的调用。

块加密算法 rc4

  • 不安全的加密算法,不建议使用,这个是加密算法最早用在流式加密中。
1
2
3
4
5
6
7
8
9
ciper, err := rc4.NewCipher([]byte("HelloWorld"))
if nil != err {
panic(err)
}

plaintext := "RC4AAAAAAAAAA"
buffer := make([]byte, len(plaintext))
ciper.XORKeyStream(buffer, []byte(plaintext))
fmt.Println(buffer)