-
Notifications
You must be signed in to change notification settings - Fork 1
/
strongbox.go
253 lines (218 loc) · 5.71 KB
/
strongbox.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package strongbox
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
)
// StrongBox is used to encrypt and decrypt
type StrongBox struct {
PublicKey *rsa.PublicKey
PrivateKey *rsa.PrivateKey
Password string
Base64 bool
}
// New create a StrongBox pointer
// publicKey, privateKey public & private key's files
// Ruby default params
// :base64 => false
// :symmetric => :always
func New(publicKey, privateKey, password string, base64 bool) (*StrongBox, error) {
pub, err := ioutil.ReadFile(publicKey)
if err != nil {
return nil, err
}
priv, err := ioutil.ReadFile(privateKey)
if err != nil {
return nil, err
}
return NewWithData(string(pub), string(priv), password, base64)
}
// NewWithData creates a strongbox with string content keys
func NewWithData(pub, priv, password string, base64 bool) (*StrongBox, error) {
pubBlock, _ := pem.Decode([]byte(pub))
if pubBlock == nil {
return nil, fmt.Errorf("invalid public key: %s", pub)
}
pubInterface, err := x509.ParsePKIXPublicKey(pubBlock.Bytes)
if err != nil {
return nil, fmt.Errorf("invalid public key: %s, err: %s", pub, err.Error())
}
pubKey, ok := pubInterface.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("may be Go has something wrong")
}
privBlock, _ := pem.Decode([]byte(priv))
if pubBlock == nil {
return nil, fmt.Errorf("invalid private key: %s", priv)
}
if x509.IsEncryptedPEMBlock(privBlock) {
privBlock.Bytes, err = x509.DecryptPEMBlock(privBlock, []byte(password))
if err != nil {
return nil, fmt.Errorf("wrong password[%s] for private key[%s], err: %s", password, priv, err.Error())
}
}
privKey, err := x509.ParsePKCS1PrivateKey(privBlock.Bytes)
if err != nil {
return nil, fmt.Errorf("invalid private key: %s, err: %s", priv, err.Error())
}
return &StrongBox{
PublicKey: pubKey,
PrivateKey: privKey,
Password: password,
Base64: base64,
}, nil
}
// RSAEncrypt encrypts a []byte use RSA
// Ruby strongbox:
// encrypt_with_public_key :symmetric => :never
func (s *StrongBox) RSAEncrypt(data []byte) ([]byte, error) {
output, err := rsa.EncryptPKCS1v15(rand.Reader, s.PublicKey, data)
if err != nil {
return nil, err
}
if s.Base64 {
buf := make([]byte, base64.StdEncoding.EncodedLen(len(output)))
base64.StdEncoding.Encode(buf, output)
return buf, nil
}
return output, nil
}
// RSADecrypt decrypts a []byte use RSA
func (s *StrongBox) RSADecrypt(data []byte) ([]byte, error) {
var (
text []byte
err error
)
if s.Base64 {
text = make([]byte, base64.StdEncoding.DecodedLen(len(data)))
n, err := base64.StdEncoding.Decode(text, data)
if err != nil {
return nil, err
}
text = text[:n]
} else {
text = data
}
output, err := rsa.DecryptPKCS1v15(rand.Reader, s.PrivateKey, text)
if err != nil {
return nil, err
}
return output, nil
}
// CBCEncrypt encrypts a []byte use AES-256-CBC
// Ruby strongbox:
// encrypt_with_public_key :symmetric => :always
// retrun encrypt data, key, iv, error
func (s *StrongBox) CBCEncrypt(data []byte) ([]byte, []byte, []byte, error) {
key, iv := make([]byte, aes.BlockSize*2), make([]byte, aes.BlockSize)
_, err := io.ReadFull(rand.Reader, key)
if err != nil {
return nil, nil, nil, err
}
_, err = io.ReadFull(rand.Reader, iv)
if err != nil {
return nil, nil, nil, err
}
padded, err := pkcs7Pad(data, aes.BlockSize)
if err != nil {
return nil, nil, nil, err
}
c, err := aes.NewCipher(key)
if err != nil {
return nil, nil, nil, err
}
cbc := cipher.NewCBCEncrypter(c, iv)
cbc.CryptBlocks(padded, padded)
key, err = s.RSAEncrypt(key)
if err != nil {
return nil, nil, nil, err
}
iv, err = s.RSAEncrypt(iv)
if err != nil {
return nil, nil, nil, err
}
if s.Base64 {
buf := make([]byte, base64.StdEncoding.EncodedLen(len(padded)))
base64.StdEncoding.Encode(buf, padded)
padded = buf
}
return padded, key, iv, nil
}
// CBCDecrypt decrypts a []byte use AES-256-CBC
func (s *StrongBox) CBCDecrypt(data, key, iv []byte) ([]byte, error) {
var (
text []byte
err error
)
if s.Base64 {
text = make([]byte, base64.StdEncoding.DecodedLen(len(data)))
n, err := base64.StdEncoding.Decode(text, data)
if err != nil {
return nil, err
}
text = text[:n]
} else {
text = data
}
if len(text) == 0 || len(text)%aes.BlockSize != 0 {
return nil, fmt.Errorf("invalid blocksize(%v), aes.BlockSize = %v", len(text), aes.BlockSize)
}
keyDc, err := s.RSADecrypt(key)
if err != nil {
return nil, err
}
ivDc, err := s.RSADecrypt(iv)
if err != nil {
return nil, err
}
c, err := aes.NewCipher(keyDc)
if err != nil {
return nil, err
}
cbc := cipher.NewCBCDecrypter(c, ivDc)
cbc.CryptBlocks(text, text)
if text, err = pkcs7Unpad(text, aes.BlockSize); err != nil {
return nil, err
}
return text, nil
}
// pkcs7Pad appends padding.
func pkcs7Pad(data []byte, blocklen int) ([]byte, error) {
if blocklen <= 0 {
return nil, fmt.Errorf("invalid blocklen %d", blocklen)
}
padlen := 1
for ((len(data) + padlen) % blocklen) != 0 {
padlen = padlen + 1
}
pad := bytes.Repeat([]byte{byte(padlen)}, padlen)
return append(data, pad...), nil
}
// pkcs7Unpad returns slice of the original data without padding.
func pkcs7Unpad(data []byte, blocklen int) ([]byte, error) {
if blocklen <= 0 {
return nil, fmt.Errorf("invalid blocklen %d", blocklen)
}
if len(data)%blocklen != 0 || len(data) == 0 {
return nil, fmt.Errorf("invalid data len %d", len(data))
}
padlen := int(data[len(data)-1])
if padlen > blocklen || padlen == 0 {
return nil, fmt.Errorf("invalid padding")
}
pad := data[len(data)-padlen:]
for i := 0; i < padlen; i++ {
if pad[i] != byte(padlen) {
return nil, fmt.Errorf("invalid padding")
}
}
return data[:len(data)-padlen], nil
}