/
core.go
329 lines (287 loc) · 8.26 KB
/
core.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package crypto
import (
"context"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"hash/crc32"
kms "cloud.google.com/go/kms/apiv1"
kmsv1 "google.golang.org/genproto/googleapis/cloud/kms/v1"
"google.golang.org/protobuf/types/known/wrapperspb"
)
const (
DefaultBits2048 = 2048
publicKeyType = "PUBLIC KEY"
privateKeyType = "PRIVATE KEY"
)
// NewAesKey generates new AES key
func NewAesKey() ([]byte, error) {
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
err := fmt.Errorf("could not create a rand AES key: %w", err)
return nil, err
}
return key[:], nil
}
// NewRsaKeyPair generates a new RSA key pair
func NewRsaKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error) {
privkey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, nil, fmt.Errorf("could not generate RSA key pair: %w", err)
}
return privkey, &privkey.PublicKey, nil
}
// NewEcdsaKeyPair generates a new ECDSA key pair
func NewEcdsaKeyPair(pubkeyCurve elliptic.Curve) (*ecdsa.PrivateKey, *ecdsa.PublicKey, error) {
privatekey, err := ecdsa.GenerateKey(pubkeyCurve, rand.Reader)
if err != nil {
return nil, nil, fmt.Errorf("could not generate ECDSA key pair: %w", err)
}
return privatekey, &privatekey.PublicKey, nil
}
// NewEd25519KeyPair generates a new Ed25519 key pair
func NewEd25519KeyPair() (*ed25519.PrivateKey, *ed25519.PublicKey, error) {
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate ed25519 key pair: %w", err)
}
return &privateKey, &publicKey, nil
}
// RsaPrivateKeyToBytes private key to bytes
func RsaPrivateKeyToBytes(priv *rsa.PrivateKey) []byte {
privBytes := pem.EncodeToMemory(
&pem.Block{
Type: privateKeyType,
Bytes: x509.MarshalPKCS1PrivateKey(priv),
},
)
return privBytes
}
// EcdsaPrivateKeyToBytes private key to bytes
func EcdsaPrivateKeyToBytes(priv *ecdsa.PrivateKey) ([]byte, error) {
b, err := x509.MarshalECPrivateKey(priv)
if err != nil {
return nil, fmt.Errorf("failed to x509 marshal ECDSA key: %w", err)
}
privBytes := pem.EncodeToMemory(
&pem.Block{
Type: privateKeyType,
Bytes: b,
},
)
return privBytes, nil
}
// Ed25519PrivateKeyToBytes private key to bytes
func Ed25519PrivateKeyToBytes(priv *ed25519.PrivateKey) ([]byte, error) {
b, err := x509.MarshalPKCS8PrivateKey(*priv)
if err != nil {
return nil, fmt.Errorf("failed to x509 marshal Ed25519 key: %w", err)
}
privBytes := pem.EncodeToMemory(
&pem.Block{
Type: privateKeyType,
Bytes: b,
},
)
return privBytes, nil
}
// RsaPublicKeyToBytes public key to bytes
func RsaPublicKeyToBytes(pub *rsa.PublicKey) ([]byte, error) {
pubASN1, err := x509.MarshalPKIXPublicKey(pub)
if err != nil {
err := fmt.Errorf("could not marshal public key: %w", err)
return nil, err
}
pubBytes := pem.EncodeToMemory(&pem.Block{
Type: publicKeyType,
Bytes: pubASN1,
})
return pubBytes, nil
}
// EcdsaPublicKeyToBytes public key to bytes
func EcdsaPublicKeyToBytes(pub *ecdsa.PublicKey) ([]byte, error) {
pubASN1, err := x509.MarshalPKIXPublicKey(pub)
if err != nil {
err := fmt.Errorf("could not marshal public key: %w", err)
return nil, err
}
pubBytes := pem.EncodeToMemory(&pem.Block{
Type: publicKeyType,
Bytes: pubASN1,
})
return pubBytes, nil
}
// Ed25519PublicKeyToBytes public key to bytes
func Ed25519PublicKeyToBytes(pub *ed25519.PublicKey) ([]byte, error) {
pubASN1, err := x509.MarshalPKIXPublicKey(*pub)
if err != nil {
err := fmt.Errorf("could not marshal public key: %w", err)
return nil, err
}
pubBytes := pem.EncodeToMemory(&pem.Block{
Type: publicKeyType,
Bytes: pubASN1,
})
return pubBytes, nil
}
// BytesToRsaPrivateKey bytes to private key
func BytesToRsaPrivateKey(priv []byte) (*rsa.PrivateKey, error) {
block, _ := pem.Decode(priv)
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
err := fmt.Errorf("could not parse private key: %w", err)
return nil, err
}
return key, nil
}
// BytesToEcdsaPrivateKey bytes to private key
func BytesToEcdsaPrivateKey(priv []byte) (*ecdsa.PrivateKey, error) {
block, _ := pem.Decode(priv)
key, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
err := fmt.Errorf("could not parse private key: %w", err)
return nil, err
}
return key, nil
}
// BytesToEd25519PrivateKey bytes to private key
func BytesToEd25519PrivateKey(priv []byte) (*ed25519.PrivateKey, error) {
block, _ := pem.Decode(priv)
obj, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
err := fmt.Errorf("could not parse private key: %w", err)
return nil, err
}
key, ok := obj.(*ed25519.PrivateKey)
if !ok {
return nil, fmt.Errorf("type assertion error while parsing private key: %T", obj)
}
return key, nil
}
// BytesToRsaPublicKey bytes to public key
func BytesToRsaPublicKey(pub []byte) (*rsa.PublicKey, error) {
block, _ := pem.Decode(pub)
d, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
err := fmt.Errorf("could not parse public key: %w", err)
return nil, err
}
key, ok := d.(*rsa.PublicKey)
if !ok {
err := fmt.Errorf("type assertion to public key failed")
return nil, err
}
return key, nil
}
// BytesToEcdsaPublicKey bytes to public key
func BytesToEcdsaPublicKey(pub []byte) (*ecdsa.PublicKey, error) {
block, _ := pem.Decode(pub)
d, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
err := fmt.Errorf("could not parse public key: %w", err)
return nil, err
}
key, ok := d.(*ecdsa.PublicKey)
if !ok {
err := fmt.Errorf("type assertion to public key failed")
return nil, err
}
return key, nil
}
// BytesToEd25519PublicKey bytes to public key
func BytesToEd25519PublicKey(pub []byte) (*ed25519.PublicKey, error) {
block, _ := pem.Decode(pub)
d, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
err := fmt.Errorf("could not parse public key: %w", err)
return nil, err
}
key, ok := d.(*ed25519.PublicKey)
if !ok {
err := fmt.Errorf("type assertion to public key failed")
return nil, err
}
return key, nil
}
// EncryptWithKms encrypts input data using Google KMS. You must have a service account
// referenced by env. var. GOOGLE_APPLICATION_CREDENTIALS
func EncryptWithKms(ctx context.Context,
data []byte, project, location, keyring, key string) ([]byte, error) {
kmsClient, err := kms.NewKeyManagementClient(ctx)
if err != nil {
err := fmt.Errorf("failed to create kms client: %w", err)
return nil, err
}
defer kmsClient.Close()
resp, err := kmsClient.Encrypt(
ctx,
&kmsv1.EncryptRequest{
Name: getKmsName(
project,
location,
keyring,
key,
),
Plaintext: data,
AdditionalAuthenticatedData: nil,
PlaintextCrc32C: wrapperspb.Int64(int64(crc32Sum(data))),
AdditionalAuthenticatedDataCrc32C: nil,
},
)
if err != nil {
err := fmt.Errorf("could not kms encrypt input: %w", err)
return nil, err
}
return resp.Ciphertext, nil
}
// DecryptWithKms decrypts input data using Google KMS. You must have a service account
// referenced by env. var. GOOGLE_APPLICATION_CREDENTIALS
func DecryptWithKms(ctx context.Context,
data []byte, project, location, keyring, key string) ([]byte, error) {
kmsClient, err := kms.NewKeyManagementClient(ctx)
if err != nil {
err := fmt.Errorf("failed to create kms client: %w", err)
return nil, err
}
defer kmsClient.Close()
resp, err := kmsClient.Decrypt(
ctx,
&kmsv1.DecryptRequest{
Name: getKmsName(
project,
location,
keyring,
key,
),
Ciphertext: data,
AdditionalAuthenticatedData: nil,
CiphertextCrc32C: wrapperspb.Int64(int64(crc32Sum(data))),
AdditionalAuthenticatedDataCrc32C: nil,
},
)
if err != nil {
err := fmt.Errorf("could not kms decrypt input: %w", err)
return nil, err
}
return resp.Plaintext, nil
}
// getKmsName constructs the canonical URI endpoint path for KMS encryption call
func getKmsName(projectId, kmsLocation, keyringName, keyName string) string {
return fmt.Sprintf(
"projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
projectId,
kmsLocation,
keyringName,
keyName,
)
}
// crc32Sum produces crc32 sum
func crc32Sum(data []byte) uint32 {
t := crc32.MakeTable(crc32.Castagnoli)
return crc32.Checksum(data, t)
}