/
encrypt_credential.go
56 lines (52 loc) · 1.24 KB
/
encrypt_credential.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
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"syscall"
"github.com/urfave/cli"
"golang.org/x/crypto/ssh/terminal"
)
func encryptCredential(c *cli.Context) error {
if err := validateEncryptCredential(c); err != nil {
return err
}
fmt.Print("Password: ")
b, err := terminal.ReadPassword(int(syscall.Stdin))
if err != nil {
return err
}
fmt.Println("")
password := string(b)
if password == "" {
return cli.NewExitError("password is not blank", 1)
}
keypath := c.String("key")
b64key, err := ioutil.ReadFile(keypath)
if err != nil {
return err
}
key, err := base64.StdEncoding.DecodeString(string(b64key))
if err != nil {
return cli.NewExitError("key content is invalid. it should be base64 encoded string", 1)
}
encryptedPassword, err := encrypt([]byte(password), key)
if err != nil {
return err
}
fmt.Println(encryptedPassword)
return nil
}
func validateEncryptCredential(c *cli.Context) error {
key := c.String("key")
if key == "" {
_ = cli.ShowCommandHelp(c, "encrypt")
return cli.NewExitError("key is required", 1)
}
if _, err := os.Stat(key); err != nil {
_ = cli.ShowCommandHelp(c, "encrypt")
return cli.NewExitError(fmt.Sprintf("No such file or directory: %s", key), 1)
}
return nil
}