-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcipherCli.go
69 lines (61 loc) · 1.39 KB
/
cipherCli.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
package main
import (
"fmt"
"io"
"os"
cipher "github.com/8ff/cipherbox/pkg/cc2p1305_scrypt"
)
func main() {
// Parse args
args := os.Args
if len(args) != 2 {
fmt.Println("Usage: cipherCli e|d")
os.Exit(1)
}
if args[1] != "e" && args[1] != "d" {
fmt.Println("Usage: cipherCli e|d")
os.Exit(1)
}
// Read key from CKEY env var to byte slice
key := []byte(os.Getenv("CKEY"))
if len(key) == 0 {
fmt.Fprintf(os.Stderr, "CKEY env var not set")
os.Exit(1)
}
// Initialize cipher
c, err := cipher.Init(cipher.Params{KeySize: len(key), Key: key})
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to initialize cipher: %v", err)
os.Exit(1)
}
// Read all data from stdin
data := make([]byte, 0)
buf := make([]byte, 1024)
for {
n, err := os.Stdin.Read(buf)
if err != nil {
if err == io.EOF {
break
}
fmt.Fprintf(os.Stderr, "Failed to read data from stdin: %v", err)
os.Exit(1)
}
data = append(data, buf[:n]...)
}
switch args[1] {
case "e", "-e", "encrypt", "-encrypt", "--encrypt":
encrypted, err := c.Encrypt(data)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to encrypt data: %v\n", err)
os.Exit(1)
}
os.Stdout.Write(encrypted)
case "d", "-d", "decrypt", "-decrypt", "--decrypt":
decrypted, err := c.Decrypt(data)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to decrypt data: %v\n", err)
os.Exit(1)
}
os.Stdout.Write(decrypted)
}
}