Go语言 字符串加密

AES加密

CBC模式,最常见的使用方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main

import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)

func AesEncrypt(str string, key string) string {
// 转成字节数组
strData := []byte(str)
k := []byte(key)
// 分组秘钥
// NewCipher该函数限制了输入k的长度必须为16, 24或者32
block, _ := aes.NewCipher(k)
// 获取秘钥块的长度
blockSize := block.BlockSize()
// 补全码
strData = PKCS7Padding(strData, blockSize)
// 加密模式
blockMode := cipher.NewCBCEncrypter(block, k[:blockSize])
// 创建数组
cryted := make([]byte, len(strData))
// 加密
blockMode.CryptBlocks(cryted, strData)
return base64.StdEncoding.EncodeToString(cryted)
}

func AesDecrypt(cryted string, key string) string {
// 转成字节数组
crytedByte, _ := base64.StdEncoding.DecodeString(cryted)
k := []byte(key)
// 分组秘钥
block, _ := aes.NewCipher(k)
// 获取秘钥块的长度
blockSize := block.BlockSize()
// 加密模式
blockMode := cipher.NewCBCDecrypter(block, k[:blockSize])
// 创建数组
str := make([]byte, len(crytedByte))
// 解密
blockMode.CryptBlocks(str, crytedByte)
// 去补全码
str = PKCS7UnPadding(str)
return string(str)
}

//补码
//AES加密数据块分组长度必须为128bit(byte[16]),密钥长度可以是128bit(byte[16])、192bit(byte[24])、256bit(byte[32])中的任意一个。
func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
padding := blocksize - len(ciphertext)%blocksize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}

//去码
func PKCS7UnPadding(strData []byte) []byte {
length := len(strData)
unpadding := int(strData[length-1])
return strData[:(length - unpadding)]
}

func main() {
str := "hello world"
//key的长度可是16位、24位、32位中的一个
key := "psvmc123456789101112131415161718"
fmt.Println("原字符串内容:", str)
encryptCode := AesEncrypt(str, key)
fmt.Println("加密后的密文:", encryptCode)
decryptCode := AesDecrypt(encryptCode, key)
fmt.Println("解密结果:", decryptCode)
}

MD5加密

工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package utils

import (
"crypto/md5"
"fmt"
)

func MD5Encode(str string) string {
return fmt.Sprintf("%x", md5.Sum([]byte(str)))
}

func MD5More(str string) string {
return MD5Encode(MD5Encode(str))
}

调用

1
2
3
4
5
6
7
8
9
10
11
12
13
package test

import (
"fmt"
"testing"
"z-wiki/utils"
)

func TestStr(t *testing.T) {
str := "Hello World"
md5Str := utils.MD5More(str)
fmt.Println(md5Str)
}