-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.go
More file actions
77 lines (62 loc) · 1.63 KB
/
Copy pathcrypto.go
File metadata and controls
77 lines (62 loc) · 1.63 KB
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
75
76
77
package eutil
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
)
func MD5(content string) string {
h := md5.New()
h.Write([]byte(content))
return hex.EncodeToString(h.Sum(nil))
}
func SHA256(content string) string {
h := sha256.New()
h.Write([]byte(content))
return hex.EncodeToString(h.Sum(nil))
}
func SHA512(content string) string {
h := sha512.New()
h.Write([]byte(content))
return hex.EncodeToString(h.Sum(nil))
}
func pkcs7Padding(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padtext...)
}
// AES加密函数
func AesEncrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
plaintext = pkcs7Padding(plaintext, blockSize)
ciphertext := make([]byte, len(plaintext))
mode := cipher.NewCBCEncrypter(block, key[:blockSize])
mode.CryptBlocks(ciphertext, plaintext)
return ciphertext, nil
}
// 去填充函数,去除填充的数据
func pkcs7Unpadding(data []byte) []byte {
length := len(data)
unpadding := int(data[length-1])
return data[:length-unpadding]
}
// AES解密函数
func AesDecrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
mode := cipher.NewCBCDecrypter(block, key[:blockSize])
plaintext := make([]byte, len(ciphertext))
mode.CryptBlocks(plaintext, ciphertext)
plaintext = pkcs7Unpadding(plaintext)
return plaintext, nil
}