-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathencrypt_https_password.go
85 lines (72 loc) · 1.83 KB
/
encrypt_https_password.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
package utils
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
type PasswordCipherInterface interface {
EncryptPassword() string
DecryptPassword() string
}
type PasswordCipherStruct struct {
PlainPassword string
EncryptedPassword string
KeyString string
}
// Encrypts the password and returns the encrypted string
func (x PasswordCipherStruct) EncryptPassword() string {
plainText := x.PlainPassword
keyString := x.KeyString
keyBytes := []byte(keyString + keyString)
plainBytes := []byte(plainText)
if keyBytes != nil {
block, blockErr := aes.NewCipher(keyBytes)
if blockErr != nil {
fmt.Println(blockErr.Error())
return ""
}
aesGCM, gcmErr := cipher.NewGCM(block)
if gcmErr != nil {
fmt.Println(gcmErr.Error())
return ""
}
nonce := make([]byte, aesGCM.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return ""
}
encryptedBytes := aesGCM.Seal(nonce, nonce, plainBytes, nil)
return base64.StdEncoding.EncodeToString(encryptedBytes)
}
return ""
}
// Decrypts the AES encrypted password
func (x PasswordCipherStruct) DecryptPassword() string {
keyString := x.KeyString
password := x.EncryptedPassword
encBytes, _ := base64.StdEncoding.DecodeString(password)
keyBytes := []byte(keyString + keyString)
if keyBytes == nil && encBytes == nil {
return ""
}
block, blockErr := aes.NewCipher(keyBytes)
if blockErr != nil {
fmt.Println(blockErr.Error())
return ""
}
aesGCM, gcmErr := cipher.NewGCM(block)
if gcmErr != nil {
fmt.Println(gcmErr.Error())
return ""
}
nonceSize := aesGCM.NonceSize()
nonce, cipherText := encBytes[:nonceSize], encBytes[nonceSize:]
plainText, decryptErr := aesGCM.Open(nil, nonce, cipherText, nil)
if decryptErr != nil {
fmt.Println(decryptErr.Error())
return ""
}
return string(plainText)
}