-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.go
90 lines (69 loc) · 1.99 KB
/
crypto.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package gosdk
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"github.com/pkg/errors"
"golang.org/x/crypto/bcrypt"
"io"
)
type CryptoUtils interface {
Encrypt(secret []byte, content string) (encoded string, err error)
Decrypt(secret []byte, secure string) (decoded string, err error)
Hash(bv []byte) string
Bcrypt(bv []byte) string
CompareHashAndPassword(hash string, password string) error
}
func NewCryptoUtils() CryptoUtils {
return &cryptoUtils{}
}
type cryptoUtils struct {
}
func (u *cryptoUtils) Encrypt(secret []byte, content string) (encoded string, err error) {
plainText := []byte(content)
block, err := aes.NewCipher(secret)
if err != nil {
return
}
cipherText := make([]byte, aes.BlockSize+len(plainText))
iv := cipherText[:aes.BlockSize]
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
return
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(cipherText[aes.BlockSize:], plainText)
return base64.RawStdEncoding.EncodeToString(cipherText), nil
}
func (u *cryptoUtils) Decrypt(secret []byte, secure string) (decoded string, err error) {
cipherText, err := base64.RawStdEncoding.DecodeString(secure)
if err != nil {
return
}
block, err := aes.NewCipher(secret)
if err != nil {
return
}
if len(cipherText) < aes.BlockSize {
err = errors.New("invalid ciphertext")
return
}
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(cipherText, cipherText)
return string(cipherText), err
}
func (u *cryptoUtils) Hash(bv []byte) string {
h := sha256.New()
h.Write(bv)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func (u *cryptoUtils) Bcrypt(bv []byte) string {
hashed, _ := bcrypt.GenerateFromPassword(bv, bcrypt.MinCost)
return string(hashed)
}
func (u *cryptoUtils) CompareHashAndPassword(hash string, password string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
}