/
decrypt.go
140 lines (116 loc) · 2.28 KB
/
decrypt.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main
import (
"fmt"
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"io/ioutil"
"io"
"bytes"
"compress/zlib"
"os"
"flag"
)
func main() {
var (
err error
inName = flag.String("in", "", "input file")
outName = flag.String("out", "", "output file")
)
flag.Parse()
in, err := os.Open(*inName)
check(err)
out, err := os.OpenFile(*outName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
check(err)
var inB, outB []byte
enc := false
if flag.Arg(0) == "enc" || flag.Arg(0) == "dec" {
enc = true
inB, _ = ioutil.ReadAll(in)
if flag.Arg(0) == "enc" {
inB = pad(16, inB)
}
outB = make([]byte, len(inB))
}
var (
key = mustDecodeHexString(os.ExpandEnv("$KEY"))
iv = mustDecodeHexString(os.ExpandEnv("$IV"))
)
switch flag.Arg(0) {
case "enc":
err = encrypt(key, iv, inB, outB)
case "dec":
err = decrypt(key, iv, inB, outB)
case "cmp":
err = compress(in, out)
case "dmp":
err = decompress(in, out)
default:
log("no command given")
}
check(err)
if enc {
io.Copy(out, bytes.NewReader(outB))
}
}
func decrypt(key, iv, in, out []byte) error {
block, err := aes.NewCipher(key)
if err != nil {
return err
}
stream := cipher.NewCBCDecrypter(block, iv)
stream.CryptBlocks(out, in)
return nil
}
func encrypt(key, iv, in, out []byte) error {
block, err := aes.NewCipher(key)
if err != nil {
return err
}
stream := cipher.NewCBCEncrypter(block, iv)
stream.CryptBlocks(out, in)
return nil
}
func decompress(in io.Reader, out io.Writer) error {
dcmp, err := zlib.NewReader(in)
if err != nil {
return err
}
defer dcmp.Close()
_, err = io.Copy(out, dcmp)
if err != nil {
return err
}
return nil
}
func compress(in io.Reader, out io.Writer) error {
cmp := zlib.NewWriter(out)
defer cmp.Close()
_, err := io.Copy(cmp, in)
if err != nil {
return err
}
return nil
}
func log(s string, v ...interface{}) {
fmt.Fprintf(os.Stderr, s, v...)
}
// taken from andreburgaud/crypt2go
func pad(bs int, buf []byte) []byte {
bufLen := len(buf)
padLen := bs - (bufLen % bs)
padText := bytes.Repeat([]byte{byte(padLen)}, padLen)
return append(buf, padText...)
}
func mustDecodeHexString(s string) []byte {
d, e := hex.DecodeString(s)
if e != nil {
panic(e)
}
return d
}
func check(err error) {
if err != nil {
panic(err)
}
}