-
Notifications
You must be signed in to change notification settings - Fork 1
/
encrypt.go
74 lines (60 loc) · 1.47 KB
/
encrypt.go
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 (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
"golang.org/x/crypto/bcrypt"
)
// Encrypt 加密
// inputPassword 未加密的密码
func Encrypt(inputPassword string) (string, error) {
// Generate "hash" 加密密码
hash, err := bcrypt.GenerateFromPassword([]byte(inputPassword), bcrypt.DefaultCost)
if err != nil {
return "", err
}
// 加密后的密码
password := string(hash)
return password, nil
}
// Compare 比较密码
func Compare(inputPwd, hashPwd string) error {
err := bcrypt.CompareHashAndPassword([]byte(hashPwd), []byte(inputPwd))
return err
}
var key = []byte("ruokeqx-Is_Master_Web-coder!!!!!")
// AesEncrypt Aes 加密
func AesEncrypt(plaintext []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
// AesDecrypt Aes 解密
func AesDecrypt(ciphertext []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, errors.New("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
return gcm.Open(nil, nonce, ciphertext, nil)
}