-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencryptor.go
108 lines (88 loc) · 2.8 KB
/
encryptor.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/Funny-Systems-OSS/CloudSQL-Proxy-Hardening-Common"
)
var (
version = flag.Bool("v", false, "Print the version of the proxy and exit.")
instanceID = flag.Int("i", -1, "The instance ID which the cloud_sql_proxy will be set.")
credentialFilePath = flag.String("f", "", "The json file be used to retrieve Service Account credential in cloud_sql_proxy.")
outputFilePath = flag.String("o", "", "If provided, it is treated as the store path of encrypted file. Default to be the same place as the input with filename '<FILENAME>.encrypted'.")
)
const (
versionString = "1.0.0"
usage = `
Usage:
encrypt_funny -f [credential file] -i [instance ID]
Options:
`
)
func init(){
fmt.Println(funny.Funny)
flag.Usage = func() {
fmt.Fprintf(os.Stderr, usage)
flag.VisitAll(func(f *flag.Flag) {
usage := strings.Replace(f.Usage, "\n", "\n ", -1)
fmt.Fprintf(os.Stderr, " -%s\n %s\n\n", f.Name, usage)
})
}
}
func checkFlags() error {
if *instanceID == -1 {
return errors.New("Must specify ID of credential Instance.")
}
if *credentialFilePath == "" {
return errors.New("Must specify path of credential file.")
}
if *outputFilePath == "" {
*outputFilePath = *credentialFilePath + ".encrypted"
}
return nil
}
func readDataFromFile(filepath string) ([]byte, error) {
return ioutil.ReadFile(filepath)
}
func writeDataToFile(filepath string, data []byte) error {
return ioutil.WriteFile(filepath, data, 666)
}
func main() {
flag.Parse()
if *version {
fmt.Println("Encrypt Funny:", versionString)
return
}
if err := checkFlags(); err != nil {
log.Fatal(err)
}
log.Printf("Reading file from \"%s\".\n", *credentialFilePath)
plaintext, err := readDataFromFile(*credentialFilePath)
if err != nil {
log.Fatal("File not found.")
}
key := funny.KeyGenerator(*instanceID)
nonce := funny.NonceGenerator(*instanceID)
log.Println("Encrypting file...")
ciphertext := funny.Encrypt(plaintext, []byte(key), []byte(nonce))
if err = writeDataToFile(*outputFilePath, []byte(ciphertext)); err != nil {
log.Fatal(err)
}
log.Println("Done.")
log.Printf("\"%s\" saved.\n", *outputFilePath)
log.Println("Validating...")
byteCiphertext, err := readDataFromFile(*outputFilePath)
if err != nil {
log.Fatal("Output file not found.")
}
log.Println("OK.")
if !funny.Validate(funny.Decrypt(byteCiphertext, []byte(key), []byte(nonce)), plaintext){
log.Println("Some shit happened. The enrypted file might not work.")
} else {
log.Println("Task complete.")
}
}