-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpassword.go
88 lines (81 loc) · 1.83 KB
/
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
86
87
88
package kpx
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"fmt"
"github.com/howeyc/gopass"
"io"
"os"
)
func createKey() []byte {
key := make([]byte, 256)
rand.Read(key)
return key
}
func readKey() []byte {
key, err := os.ReadFile(options.KeyFile)
if err == nil {
return key
}
key = createKey()
err = os.WriteFile(options.KeyFile, key, 0600)
if err != nil {
panic(err)
}
return key
}
func createHash() string {
hasher := md5.New()
hasher.Write(readKey())
return hex.EncodeToString(hasher.Sum(nil))
}
func encrypt(data string) string {
block, _ := aes.NewCipher([]byte(createHash()))
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
ciphertext := gcm.Seal(nonce, nonce, []byte(data), nil)
encrypted := base64.StdEncoding.EncodeToString(ciphertext)
return encrypted
}
func decrypt(data string) (string, error) {
encoded, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return "", err
}
key := []byte(createHash())
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := encoded[:nonceSize], encoded[nonceSize:]
decrypted, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
return string(decrypted), nil
}
func encryptPassword() {
fmt.Printf("Encrypt a password - key location is `%s`\n", options.KeyFile)
fmt.Print("Password: ")
pwdBytes, err := gopass.GetPasswdMasked() // looks like password always exists even if error
if err != nil {
os.Exit(1)
}
fmt.Printf("Encrypted: %s%s\n", ENCRYPTED, encrypt(string(pwdBytes)))
os.Exit(0)
}