-
Notifications
You must be signed in to change notification settings - Fork 0
/
cryptography.go
492 lines (423 loc) · 14.3 KB
/
cryptography.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
package utilities
import (
"crypto/aes"
"crypto/cipher"
"crypto/ecdh"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"math/big"
"slices"
)
type KeyUse int
var (
ECDSA KeyUse = 1
ECDH KeyUse = 2
)
type JWK struct {
Key_ops []string `json:"use,omitempty"` // ["sign", "verify", "encrypt", "decrypt", "wrapKey", "unwrapKey", "deriveKey", "deriveBits"]
Kty string `json:"kty,omitempty"` // "EC", "RSA"
Kid string `json:"kid,omitempty"` // Key ID
Crv string `json:"crv,omitempty"` // "P-256"
X string `json:"x,omitempty"` // x coordinate as base64 URL encoded string.
Y string `json:"y,omitempty"` // y coordinate as base64 URL encoded string.
D string `json:"d,omitempty"` // d coordinate as base64 URL encoded string. Private keys only.
}
// This will give you a private and public key pair both as *JWK structs.
// The Kid (i.e., "key-id") is equivalent shared but for the prefix "priv_" or "pub_"
// appended to a random base64 URL encoded string.The Crv parameter is hardcoded
// for now during key creation as are the key_ops.
func GenerateKeyPair(keyUse KeyUse) (*JWK, *JWK, error) {
id := make([]byte, 16)
rand.Read(id)
id_str := base64.URLEncoding.EncodeToString(id)
var privKey JWK
privKey.Kty = "EC"
privKey.Crv = "P-256"
privKey.Kid = "priv_" + id_str
privKey.Key_ops = []string{}
if keyUse == ECDSA {
privKey.Key_ops = append(privKey.Key_ops, "sign")
} else if keyUse == ECDH {
privKey.Key_ops = append(privKey.Key_ops, "deriveKey")
} else {
return nil, nil, fmt.Errorf("Unrecognized keyUse. Must be 'ECDSA', or 'ECDH.'")
}
privKey_ecdsaPtr, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
privKey.D = base64.URLEncoding.EncodeToString(privKey_ecdsaPtr.D.Bytes())
privKey.X = base64.URLEncoding.EncodeToString(privKey_ecdsaPtr.X.Bytes())
privKey.Y = base64.URLEncoding.EncodeToString(privKey_ecdsaPtr.Y.Bytes())
//privKey_ecdsaPtr.ECDH()
var pubKey JWK
pubKey.Kid = "pub_" + id_str
pubKey.Kty = "EC"
pubKey.Crv = "P-256"
pubKey.Kid = "pub_" + id_str
pubKey.Key_ops = []string{}
if keyUse == ECDSA {
pubKey.Key_ops = append(pubKey.Key_ops, "verify")
} else if keyUse == ECDH {
pubKey.Key_ops = append(pubKey.Key_ops, "deriveKey")
} else {
return nil, nil, fmt.Errorf("Unrecognized keyUse. Must be 'ECDSA', or 'ECDH.'")
}
pubKey.X = base64.URLEncoding.EncodeToString(privKey_ecdsaPtr.X.Bytes())
pubKey.Y = base64.URLEncoding.EncodeToString(privKey_ecdsaPtr.Y.Bytes())
return &privKey, &pubKey, nil
}
func (jwk *JWK) ExportKeyAsGoType() (interface{}, error) {
if jwk.Crv != "P-256" {
return nil, fmt.Errorf("Cannot convert to *ecdh.PublicKey. Incorrect 'Crv' property.")
}
if jwk.Kty != "EC" {
return nil, fmt.Errorf("Cannot convert to *ecdh.PublicKey. Incorrect 'Kty' property.")
}
// Step 1, create the 'common-to-all' base key. That is, an ecdsa.PublicKey
pubKey := new(ecdsa.PublicKey)
pubKey.Curve = elliptic.P256()
bsX, err := base64.URLEncoding.DecodeString(jwk.X)
if err != nil {
return nil, fmt.Errorf("Unable to interpret jwk.X coordinate as byte slice: %w", err)
}
pubKey.X = new(big.Int).SetBytes(bsX)
bsY, err := base64.URLEncoding.DecodeString(jwk.Y)
if err != nil {
return nil, fmt.Errorf("Unable to interpret jwk.Y coordinate as byte slice: %w", err)
}
pubKey.Y = new(big.Int).SetBytes(bsY)
// Step 2 decide if key is to be private
var keyUsage KeyUse
var privateFlag bool
if slices.Contains(jwk.Key_ops, "deriveKey") {
keyUsage = ECDH
} else {
keyUsage = ECDSA
}
if jwk.D != "" {
privateFlag = true
}
privKey := new(ecdsa.PrivateKey)
if privateFlag {
privKey.PublicKey = *pubKey
bsD, err := base64.URLEncoding.DecodeString(jwk.D)
if err != nil {
return nil, fmt.Errorf("Unable to interpret jwk.D coordinate as byte slice: %w", err)
}
privKey.D = new(big.Int).SetBytes(bsD)
}
if keyUsage == ECDSA && !privateFlag { // return an *ecdsa.PublicKey
return pubKey, nil
} else if keyUsage == ECDSA && privateFlag { // return an *ecdsa.PrivateKey
return privKey, nil
} else if keyUsage == ECDH && !privateFlag { // return an *ecdh.PublicKey
publicKey, err := pubKey.ECDH()
if err != nil {
return nil, err
}
return publicKey, nil
} else if keyUsage == ECDH && privateFlag { // return an *ecdsa.PrivateKey
privateKey, err := privKey.ECDH()
if err != nil {
return nil, err
}
return privateKey, nil
}
return nil, fmt.Errorf("Unable to Export key. Unrecognized Key_ops.")
}
// Currently only supports checking against pk of type *ecdsa.Private/Public & *ecdh.Private/Public
func (jwk *JWK) Equal(pk interface{}) bool {
switch key := pk.(type) {
case *ecdsa.PrivateKey:
if !slices.Contains(jwk.Key_ops, "sign") ||
jwk.Kty != "EC" ||
jwk.Crv != key.Params().Name ||
jwk.X != base64.URLEncoding.EncodeToString(key.PublicKey.X.Bytes()) ||
jwk.Y != base64.URLEncoding.EncodeToString(key.PublicKey.Y.Bytes()) ||
jwk.D != base64.URLEncoding.EncodeToString(key.D.Bytes()) {
return false
}
case *ecdsa.PublicKey:
if !slices.Contains(jwk.Key_ops, "verify") ||
jwk.Kty != "EC" ||
jwk.Crv != key.Params().Name ||
jwk.X != base64.URLEncoding.EncodeToString(key.X.Bytes()) ||
jwk.Y != base64.URLEncoding.EncodeToString(key.Y.Bytes()) ||
jwk.D != "" {
return false
}
case *ecdh.PrivateKey:
if !slices.Contains(jwk.Key_ops, "deriveKey") ||
jwk.Kty != "EC" ||
jwk.Crv != fmt.Sprint(key.Curve()) ||
jwk.X != base64.URLEncoding.EncodeToString(key.PublicKey().Bytes()[1:33]) ||
jwk.Y != base64.URLEncoding.EncodeToString(key.PublicKey().Bytes()[33:]) ||
jwk.D != base64.URLEncoding.EncodeToString(key.Bytes()) {
return false
}
case *ecdh.PublicKey:
if !slices.Contains(jwk.Key_ops, "deriveKey") ||
jwk.Kty != "EC" ||
jwk.Crv != fmt.Sprint(key.Curve()) ||
jwk.X != base64.URLEncoding.EncodeToString(key.Bytes()[1:33]) ||
jwk.Y != base64.URLEncoding.EncodeToString(key.Bytes()[33:]) ||
jwk.D != "" {
return false
}
case *JWK:
for _, val := range jwk.Key_ops {
if !slices.Contains(key.Key_ops, val) {
return false
}
}
if jwk.Kty != key.Kty ||
jwk.Kid != key.Kid ||
jwk.Crv != key.Crv ||
jwk.X != key.X ||
jwk.Y != key.Y ||
jwk.D != key.D {
return false
}
default:
//fmt.Println("ERROR: At this time only ECDSA & ECDH keys are supported.")
return false
}
return true
}
func (jwk1 *JWK) EqualToJWK(jwk2 *JWK) bool {
for _, val := range jwk1.Key_ops {
if !slices.Contains(jwk2.Key_ops, val) {
return false
}
}
if jwk1.Kty != jwk2.Kty {
return false
}
if jwk1.Kid != jwk2.Kid {
return false
}
if jwk1.Crv != jwk2.Crv {
return false
}
if jwk1.X != jwk2.X {
return false
}
if jwk1.Y != jwk2.Y {
return false
}
if jwk1.D != jwk2.D {
return false
}
return true
}
// func (*JWK) ExportECDSAKeyPair() (*ecdsa.PrivateKey, *ecdsa.PublicKey, error)
func (privateKey *JWK) GetECDHSharedSecret(publicKey *JWK) (*JWK, error) {
// is public key public?
if publicKey.D != "" {
return nil, fmt.Errorf("Function takes a public JWK as argument. Private key detected.")
}
// is publis key for ECDH?
if !slices.Contains(publicKey.Key_ops, "deriveKey") {
return nil, fmt.Errorf("The public JWK passed in as argument must have 'deriveKey' as one of the key_ops")
}
// is private private?
if privateKey.D == "" {
return nil, fmt.Errorf("Function receiver must be private JWK. No private key detected.")
}
// is private for ECDH?
if !slices.Contains(privateKey.Key_ops, "deriveKey") {
return nil, fmt.Errorf("Function receiver must have 'deriveKey' as one of the Key_ops.")
}
// convert both to *ecdh.[private|public]Key
privKey_unCasted, err := privateKey.ExportKeyAsGoType()
if err != nil {
return nil, fmt.Errorf("Unable to export private key as Go Type: %w", err)
}
var privKey *ecdh.PrivateKey
if pk, ok := privKey_unCasted.(*ecdh.PrivateKey); ok {
privKey = pk
} else {
return nil, fmt.Errorf("Returned private key could not be cast as *ecdh.PrivateKey")
}
pubKey_unCasted, err := publicKey.ExportKeyAsGoType()
if err != nil {
return nil, fmt.Errorf("Unable to export public key as Go Type: %w", err)
}
var pubKey *ecdh.PublicKey
if pk, ok := pubKey_unCasted.(*ecdh.PublicKey); ok {
pubKey = pk
} else {
return nil, fmt.Errorf("Returned public key could not be cast as *ecdh.PublicKey")
}
// Do ECDH
ss, err := privKey.ECDH(pubKey)
// Kid is derived from the private key's Kid
symmetricJWK := &JWK{
Kty: "EC",
Key_ops: []string{"encrypt", "decrypt"},
Kid: "shared_" + privateKey.Kid[4:],
Crv: privateKey.Crv,
X: base64.URLEncoding.EncodeToString(ss),
}
// convert the result to a JWK.
return symmetricJWK, nil
}
func (ss *JWK) SymmetricEncrypt(data []byte) ([]byte, error) {
if !slices.Contains(ss.Key_ops, "encrypt") {
return nil, fmt.Errorf("Receiver Key_ops must include 'encrypt' ")
}
ssBS, err := base64.URLEncoding.DecodeString(ss.X)
if err != nil {
return nil, fmt.Errorf("Unable to interpret ss.X coordinate as byte slice: %w", err)
}
blockCipher, err := aes.NewCipher(ssBS)
if err != nil {
return nil, fmt.Errorf("Symmetric encryption failed @ 1 : %w", err)
}
aesgcm, err := cipher.NewGCM(blockCipher)
if err != nil {
return nil, fmt.Errorf("Symmetric encryption failed @ 2: %w", err)
}
nonce := make([]byte, aesgcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, fmt.Errorf("Symmetric encryption failed @ 3: %w", err)
}
cipherText := aesgcm.Seal(nonce, nonce, data, nil)
return cipherText, nil
}
func (ss *JWK) SymmetricDecrypt(ciphertext []byte) ([]byte, error) {
if len(ciphertext) == 0 {
return nil, fmt.Errorf("Receiver Key_ops must include 'decrypt' ")
}
if !slices.Contains(ss.Key_ops, "decrypt") {
return nil, fmt.Errorf("Receiver Key_ops must include 'decrypt' ")
}
ssBS, err := base64.URLEncoding.DecodeString(ss.X)
if err != nil {
return nil, fmt.Errorf("Unable to interpret ss.X coordinate as byte slice: %w", err)
}
blockCipher, err := aes.NewCipher(ssBS)
if err != nil {
return nil, fmt.Errorf("Symmetric encryption failed @ 1: %w", err)
}
aesgcm, err := cipher.NewGCM(blockCipher)
if err != nil {
return nil, fmt.Errorf("Symmetric encryption failed @ 2: %w", err)
}
nonceSize := aesgcm.NonceSize()
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("Symmetric encryption failed @ 3: %w", err)
}
return plaintext, nil
}
func (privateKey *JWK) SignWithKey(data []byte) ([]byte, error) {
ecdsaPrivateKey, err := privateKey.ExportKeyAsGoType()
if err != nil {
return nil, fmt.Errorf("Unable to call ExportKeyAsGoType on function receiver. Error: %w", err)
}
var ecdsaKeyAsGoType *ecdsa.PrivateKey
if privKey, ok := ecdsaPrivateKey.(*ecdsa.PrivateKey); ok {
ecdsaKeyAsGoType = privKey
} else {
return nil, fmt.Errorf("Receiver, privateKey, of type %T could not be cast as compatible Go type, *ecdsa.PrivateKey.", privateKey)
}
hash32 := sha256.Sum256(data) //sha256 outputs a [32]byte that must be converted to []byte using the built in copy() method.
var hash []byte
copy(hash, hash32[:])
signature, err := ecdsa.SignASN1(rand.Reader, ecdsaKeyAsGoType, hash)
if err != nil {
return nil, fmt.Errorf("Unable to sign data. Internal error: %w", err)
}
return signature, nil
}
func (publicKey *JWK) CheckAgainstASN1Signature(signature, data []byte) (bool, error) {
if !slices.Contains(publicKey.Key_ops, "verify") {
return false, fmt.Errorf("Check function receiver. *JWK Key_ops must include 'verify'")
}
ecdsaPublicKey, err := publicKey.ExportKeyAsGoType()
if err != nil {
return false, fmt.Errorf("Unable to call ExportKeyAsGoType on function receiver. Error: %w", err)
}
var ecdsaKeyAsGoType *ecdsa.PublicKey
if pubKey, ok := ecdsaPublicKey.(*ecdsa.PublicKey); ok {
ecdsaKeyAsGoType = pubKey
} else {
return false, fmt.Errorf("Receiver, publicKey, of type %T could not be cast as a compatible *ecdsa.PublicKey.", publicKey)
}
hash32 := sha256.Sum256(data) //sha256 outputs a [32]byte that must be converted to []byte using the built in copy() method.
var hash []byte
copy(hash, hash32[:])
verified := ecdsa.VerifyASN1(ecdsaKeyAsGoType, hash, signature)
if verified != true {
return false, fmt.Errorf("Signature validation failed for this public key")
}
return verified, nil
}
func VerifyASN1Signature(JWK *JWK, signature, data []byte) (bool, error) {
result, err := JWK.CheckAgainstASN1Signature(signature, data)
if err != nil {
return false, fmt.Errorf("Unable to verify signature: %w", err)
}
return result, nil
}
func SignData(JWK *JWK, data []byte) ([]byte, error) {
ASN1Signature, err := JWK.SignWithKey(data)
if err != nil {
return nil, fmt.Errorf("Unable to sign: %w", err)
}
return ASN1Signature, nil
}
func (JWK *JWK) ExportAsBase64() (string, error) {
marshalled, err := json.Marshal(JWK)
if err != nil {
return "", fmt.Errorf("Failure to export JWK as Base64 %w", err)
}
return base64.URLEncoding.EncodeToString(marshalled), nil
}
func B64ToJWK(userPubJWK string) (*JWK, error) {
userPubJWK_BS, err := base64.URLEncoding.DecodeString(userPubJWK)
if err != nil {
return nil, fmt.Errorf("Failure to decode userPubJWK, %w", err)
}
userPubJWKConverted := &JWK{}
err = json.Unmarshal(userPubJWK_BS, userPubJWKConverted)
if err != nil {
return nil, fmt.Errorf("Failure to unmarshal userPubJWK: %w", err)
}
return userPubJWKConverted, nil
}
// PRIVATE FUNCTIONS FOR PKG UTILS
func BigIntEqual(a, b *big.Int) bool {
return subtle.ConstantTimeCompare(a.Bytes(), b.Bytes()) == 1
}
func JWKFromMap(data map[string]interface{}) (*JWK, error) {
serverPubKeyRaw, ok := data["server_pubKeyECDH"]
if !ok {
return nil, fmt.Errorf("server_pubKeyECDH not found in data")
}
serverPubKey, ok := serverPubKeyRaw.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("server_pubKeyECDH is not a valid map")
}
jwk := &JWK{}
// Extracting values from the serverPubKey map
if use, ok := serverPubKey["use"].([]interface{}); ok {
for _, v := range use {
jwk.Key_ops = append(jwk.Key_ops, v.(string))
}
}
jwk.Kty, _ = serverPubKey["kty"].(string)
jwk.Kid, _ = serverPubKey["kid"].(string)
jwk.Crv, _ = serverPubKey["crv"].(string)
jwk.X, _ = serverPubKey["x"].(string)
jwk.Y, _ = serverPubKey["y"].(string)
jwk.D, _ = serverPubKey["d"].(string)
return jwk, nil
}