forked from ibm-developer/ibm-cloud-hyperprotectcrypto
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server_test.go
760 lines (683 loc) · 25.8 KB
/
server_test.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package examples
import (
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"encoding/asn1"
"fmt"
"reflect"
"github.com/ibm-developer/ibm-cloud-hyperprotectcrypto/golang/ep11"
pb "github.com/ibm-developer/ibm-cloud-hyperprotectcrypto/golang/grpc"
"github.com/ibm-developer/ibm-cloud-hyperprotectcrypto/golang/util"
uuid "github.com/satori/go.uuid"
grpc "google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
// The following IBM Cloud items need to be changed prior to running the sample program
const address = "<grep11_server_address>:<port>"
var callOpts = []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})),
grpc.WithPerRPCCredentials(&util.IAMPerRPCCredentials{
APIKey: "<ibm_cloud_apikey>",
Endpoint: "<https://<iam_ibm_cloud_endpoint>",
Instance: "<hpcs_instance_id>",
}),
}
// Example_getMechanismInfo retrieves a mechanism list and retrieves detailed information for the CKM_RSA_PKCS mechanism
// Flow: connect, get mechanism list, get mechanism info
func Example_getMechanismInfo() {
conn, err := grpc.Dial(address, callOpts...)
if err != nil {
panic(fmt.Errorf("Could not connect to server: %s", err))
}
defer conn.Close()
cryptoClient := pb.NewCryptoClient(conn)
mechanismListRequest := &pb.GetMechanismListRequest{}
mechanismListResponse, err := cryptoClient.GetMechanismList(context.Background(), mechanismListRequest)
if err != nil {
panic(fmt.Errorf("Get mechanism list error: %s", err))
}
fmt.Printf("Got mechanism list:\n%v ...\n", mechanismListResponse.Mechs[:1])
mechanismInfoRequest := &pb.GetMechanismInfoRequest{
Mech: ep11.CKM_RSA_PKCS,
}
_, err = cryptoClient.GetMechanismInfo(context.Background(), mechanismInfoRequest)
if err != nil {
panic(fmt.Errorf("Get mechanism info error: %s", err))
}
// Output:
// Got mechanism list:
// [CKM_RSA_PKCS] ...
}
// Example_encryptAndDecrypt encrypts and decrypts plain text
// Flow: connect, generate AES key, generate IV, encrypt multi-part data, decrypt multi-part data
func Example_encryptAndDecrypt() {
conn, err := grpc.Dial(address, callOpts...)
if err != nil {
panic(fmt.Errorf("Could not connect to server: %s", err))
}
defer conn.Close()
cryptoClient := pb.NewCryptoClient(conn)
keyLen := 128
keyTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_VALUE_LEN, (uint64)(keyLen/8)),
util.NewAttribute(ep11.CKA_WRAP, false),
util.NewAttribute(ep11.CKA_UNWRAP, false),
util.NewAttribute(ep11.CKA_ENCRYPT, true),
util.NewAttribute(ep11.CKA_DECRYPT, true),
util.NewAttribute(ep11.CKA_EXTRACTABLE, false), // set to false!
util.NewAttribute(ep11.CKA_TOKEN, true), // ignored by EP11
)
keygenmsg := &pb.GenerateKeyRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_AES_KEY_GEN},
Template: keyTemplate,
KeyId: uuid.NewV4().String(), // optional
}
generateKeyStatus, err := cryptoClient.GenerateKey(context.Background(), keygenmsg)
if err != nil {
panic(fmt.Errorf("GenerateKey Error: %s", err))
}
fmt.Println("Generated AES Key")
rngTemplate := &pb.GenerateRandomRequest{
Len: (uint64)(ep11.AES_BLOCK_SIZE),
}
rng, err := cryptoClient.GenerateRandom(context.Background(), rngTemplate)
if err != nil {
panic(fmt.Errorf("GenerateRandom Error: %s", err))
}
iv := rng.Rnd[:ep11.AES_BLOCK_SIZE]
fmt.Println("Generated IV")
encipherInitInfo := &pb.EncryptInitRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: iv},
Key: generateKeyStatus.Key, // you may want to store this
}
cipherStateInit, err := cryptoClient.EncryptInit(context.Background(), encipherInitInfo)
if err != nil {
panic(fmt.Errorf("Failed EncryptInit [%s]", err))
}
plain := []byte("Hello, this is a very long and creative message without any imagination")
encipherDataUpdate := &pb.EncryptUpdateRequest{
State: cipherStateInit.State,
Plain: plain[:20],
}
encipherStateUpdate, err := cryptoClient.EncryptUpdate(context.Background(), encipherDataUpdate)
if err != nil {
panic(fmt.Errorf("Failed Encrypt [%s]", err))
}
ciphertext := encipherStateUpdate.Ciphered[:]
encipherDataUpdate = &pb.EncryptUpdateRequest{
State: encipherStateUpdate.State,
Plain: plain[20:],
}
encipherStateUpdate, err = cryptoClient.EncryptUpdate(context.Background(), encipherDataUpdate)
if err != nil {
panic(fmt.Errorf("Failed Encrypt [%s]", err))
}
ciphertext = append(ciphertext, encipherStateUpdate.Ciphered...)
encipherDataFinal := &pb.EncryptFinalRequest{
State: encipherStateUpdate.State,
}
encipherStateFinal, err := cryptoClient.EncryptFinal(context.Background(), encipherDataFinal)
if err != nil {
panic(fmt.Errorf("Failed EncryptFinal [%s]", err))
}
ciphertext = append(ciphertext, encipherStateFinal.Ciphered...)
fmt.Println("Encrypted message")
decipherInitInfo := &pb.DecryptInitRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: iv},
Key: generateKeyStatus.Key, // you may want to store this
}
decipherStateInit, err := cryptoClient.DecryptInit(context.Background(), decipherInitInfo)
if err != nil {
panic(fmt.Errorf("Failed DecryptInit [%s]", err))
}
decipherDataUpdate := &pb.DecryptUpdateRequest{
State: decipherStateInit.State,
Ciphered: ciphertext[:16],
}
decipherStateUpdate, err := cryptoClient.DecryptUpdate(context.Background(), decipherDataUpdate)
if err != nil {
panic(fmt.Errorf("Failed DecryptUpdate [%s]", err))
}
plaintext := decipherStateUpdate.Plain[:]
decipherDataUpdate = &pb.DecryptUpdateRequest{
State: decipherStateUpdate.State,
Ciphered: ciphertext[16:],
}
decipherStateUpdate, err = cryptoClient.DecryptUpdate(context.Background(), decipherDataUpdate)
if err != nil {
panic(fmt.Errorf("Failed DecryptUpdate [%s]", err))
}
plaintext = append(plaintext, decipherStateUpdate.Plain...)
decipherDataFinal := &pb.DecryptFinalRequest{
State: decipherStateUpdate.State,
}
decipherStateFinal, err := cryptoClient.DecryptFinal(context.Background(), decipherDataFinal)
if err != nil {
panic(fmt.Errorf("Failed DecryptFinal [%s]", err))
}
plaintext = append(plaintext, decipherStateFinal.Plain...)
if !reflect.DeepEqual(plain, plaintext) {
panic(fmt.Errorf("Failed comparing plain text of cipher single"))
}
fmt.Printf("Decrypted message\n%s\n", plaintext)
// Output:
// Generated AES Key
// Generated IV
// Encrypted message
// Decrypted message
// Hello, this is a very long and creative message without any imagination
}
// Example_digest calculates the digest of some plain text
// Flow: connect, digest single-part data, digest multi-part data
func Example_digest() {
conn, err := grpc.Dial(address, callOpts...)
if err != nil {
panic(fmt.Errorf("Could not connect to server: %s", err))
}
defer conn.Close()
cryptoClient := pb.NewCryptoClient(conn)
digestData := []byte("This is the data longer than 64 bytes This is the data longer than 64 bytes")
digestInitRequest := &pb.DigestInitRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_SHA256},
}
digestInitResponse, err := cryptoClient.DigestInit(context.Background(), digestInitRequest)
if err != nil {
panic(fmt.Errorf("Digest init error: %s", err))
}
digestRequest := &pb.DigestRequest{
State: digestInitResponse.State,
Data: digestData,
}
digestResponse, err := cryptoClient.Digest(context.Background(), digestRequest)
if err != nil {
panic(fmt.Errorf("Digest error: %s", err))
} else {
fmt.Printf("Digest data using a single digest operation: %x\n", digestResponse.Digest)
}
// Digest using mutiple operations
digestInitResponse, err = cryptoClient.DigestInit(context.Background(), digestInitRequest)
if err != nil {
panic(fmt.Errorf("Digest init error: %s", err))
}
digestUpdateRequest := &pb.DigestUpdateRequest{
State: digestInitResponse.State,
Data: digestData[:64],
}
digestUpdateResponse, err := cryptoClient.DigestUpdate(context.Background(), digestUpdateRequest)
if err != nil {
panic(fmt.Errorf("Digest update error: %s", err))
}
digestUpdateRequest = &pb.DigestUpdateRequest{
State: digestUpdateResponse.State,
Data: digestData[64:],
}
digestUpdateResponse, err = cryptoClient.DigestUpdate(context.Background(), digestUpdateRequest)
if err != nil {
panic(fmt.Errorf("Digest update error: %s", err))
}
digestFinalRequestInfo := &pb.DigestFinalRequest{
State: digestUpdateResponse.State,
}
digestFinalResponse, err := cryptoClient.DigestFinal(context.Background(), digestFinalRequestInfo)
if err != nil {
panic(fmt.Errorf("Digest final error: %s", err))
} else {
fmt.Printf("Digest data using multiple operations: %x\n", digestFinalResponse.Digest)
}
// Output:
// Digest data using a single digest operation: ad4e0b6e309d192862ec6db692d17072ddd3a98ccd37afe642a04f7ca554c94c
// Digest data using multiple operations: ad4e0b6e309d192862ec6db692d17072ddd3a98ccd37afe642a04f7ca554c94c
}
// Example_signAndVerifyUsingRSAKeyPair signs some data and verifies it
// Flow: connect, generate RSA key pair, sign single-part data, verify single-part data
func Example_signAndVerifyUsingRSAKeyPair() {
conn, err := grpc.Dial(address, callOpts...)
if err != nil {
panic(fmt.Errorf("did not connect: %v", err))
}
defer conn.Close()
cryptoClient := pb.NewCryptoClient(conn)
// Generate RSA key pairs
publicExponent := []byte{0x11}
publicKeyTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_ENCRYPT, true),
util.NewAttribute(ep11.CKA_VERIFY, true), // to verify a signature
util.NewAttribute(ep11.CKA_MODULUS_BITS, uint64(2048)),
util.NewAttribute(ep11.CKA_PUBLIC_EXPONENT, publicExponent),
util.NewAttribute(ep11.CKA_EXTRACTABLE, false),
)
privateKeyTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_PRIVATE, true),
util.NewAttribute(ep11.CKA_SENSITIVE, true),
util.NewAttribute(ep11.CKA_DECRYPT, true),
util.NewAttribute(ep11.CKA_SIGN, true), // to generate a signature
util.NewAttribute(ep11.CKA_EXTRACTABLE, false),
)
generateKeypairRequest := &pb.GenerateKeyPairRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_RSA_PKCS_KEY_PAIR_GEN},
PubKeyTemplate: publicKeyTemplate,
PrivKeyTemplate: privateKeyTemplate,
PrivKeyId: uuid.NewV4().String(),
PubKeyId: uuid.NewV4().String(),
}
generateKeyPairStatus, err := cryptoClient.GenerateKeyPair(context.Background(), generateKeypairRequest)
if err != nil {
panic(fmt.Errorf("GenerateKeyPair error: %s", err))
}
fmt.Println("Generated RSA PKCS key pair")
// Sign data
signInitRequest := &pb.SignInitRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_SHA1_RSA_PKCS},
PrivKey: generateKeyPairStatus.PrivKey,
}
signInitResponse, err := cryptoClient.SignInit(context.Background(), signInitRequest)
if err != nil {
panic(fmt.Errorf("SignInit error: %s", err))
}
signData := sha256.New().Sum([]byte("This data needs to be signed"))
signRequest := &pb.SignRequest{
State: signInitResponse.State,
Data: signData,
}
SignResponse, err := cryptoClient.Sign(context.Background(), signRequest)
if err != nil {
panic(fmt.Errorf("Sign error: %s", err))
}
fmt.Println("Data signed")
verifyInitRequest := &pb.VerifyInitRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_SHA1_RSA_PKCS},
PubKey: generateKeyPairStatus.PubKey,
}
verifyInitResponse, err := cryptoClient.VerifyInit(context.Background(), verifyInitRequest)
if err != nil {
panic(fmt.Errorf("VerifyInit error: %s", err))
}
verifyRequest := &pb.VerifyRequest{
State: verifyInitResponse.State,
Data: signData,
Signature: SignResponse.Signature,
}
_, err = cryptoClient.Verify(context.Background(), verifyRequest)
if ok, ep11Status := util.Convert(err); !ok {
if ep11Status.Code == ep11.CKR_SIGNATURE_INVALID {
panic(fmt.Errorf("Invalid signature"))
} else {
panic(fmt.Errorf("Verify error: [%d]: %s", ep11Status.Code, ep11Status.Detail))
}
}
fmt.Println("Verified")
// Output:
// Generated RSA PKCS key pair
// Data signed
// Verified
}
// Example_signAndVerifyUsingECDSAKeyPair generates an ECDSA key pair and uses the key pair to sign and verify data
// Flow: connect, generate ECDSA key pair, sign single-part data, verify single-part data
func Example_signAndVerifyUsingECDSAKeyPair() {
conn, err := grpc.Dial(address, callOpts...)
if err != nil {
panic(fmt.Errorf("Could not connect to server: %s", err))
}
defer conn.Close()
cryptoClient := pb.NewCryptoClient(conn)
ecParameters, err := asn1.Marshal(util.OIDNamedCurveP256)
if err != nil {
panic(fmt.Errorf("Unable to encode parameter OID: %s", err))
}
publicKeyECTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_EC_PARAMS, ecParameters),
util.NewAttribute(ep11.CKA_VERIFY, true),
util.NewAttribute(ep11.CKA_EXTRACTABLE, false),
)
privateKeyECTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_SIGN, true),
util.NewAttribute(ep11.CKA_EXTRACTABLE, false),
)
generateECKeypairRequest := &pb.GenerateKeyPairRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_EC_KEY_PAIR_GEN},
PubKeyTemplate: publicKeyECTemplate,
PrivKeyTemplate: privateKeyECTemplate,
}
generateKeyPairStatus, err := cryptoClient.GenerateKeyPair(context.Background(), generateECKeypairRequest)
if err != nil {
panic(fmt.Errorf("GenerateKeyPair error: %s", err))
}
fmt.Println("Generated ECDSA PKCS key pair")
// Sign data
signInitRequest := &pb.SignInitRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_ECDSA},
PrivKey: generateKeyPairStatus.PrivKey,
}
signInitResponse, err := cryptoClient.SignInit(context.Background(), signInitRequest)
if err != nil {
panic(fmt.Errorf("SignInit error: %s", err))
}
signData := sha256.New().Sum([]byte("This data needs to be signed"))
signRequest := &pb.SignRequest{
State: signInitResponse.State,
Data: signData,
}
SignResponse, err := cryptoClient.Sign(context.Background(), signRequest)
if err != nil {
panic(fmt.Errorf("Sign error: %s", err))
}
fmt.Println("Data signed")
verifyInitRequest := &pb.VerifyInitRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_ECDSA},
PubKey: generateKeyPairStatus.PubKey,
}
verifyInitResponse, err := cryptoClient.VerifyInit(context.Background(), verifyInitRequest)
if err != nil {
panic(fmt.Errorf("VerifyInit error: %s", err))
}
verifyRequest := &pb.VerifyRequest{
State: verifyInitResponse.State,
Data: signData,
Signature: SignResponse.Signature,
}
_, err = cryptoClient.Verify(context.Background(), verifyRequest)
if ok, ep11Status := util.Convert(err); !ok {
if ep11Status.Code == ep11.CKR_SIGNATURE_INVALID {
panic(fmt.Errorf("Invalid signature"))
} else {
panic(fmt.Errorf("Verify error: [%d]: %s", ep11Status.Code, ep11Status.Detail))
}
}
fmt.Println("Verified")
// Output:
// Generated ECDSA PKCS key pair
// Data signed
// Verified
}
// Example_signAndVerifyToTestErrorHandling signs some data, modifies the signature and verifies the expected returned error code
// Flow: connect, generate ECDSA key pair, sign single-part data, modify signature to force verify error,
// verify single-part data, ensure proper error is returned
func Example_signAndVerifyToTestErrorHandling() {
conn, err := grpc.Dial(address, callOpts...)
if err != nil {
panic(fmt.Errorf("Could not connect to server: %s", err))
}
defer conn.Close()
cryptoClient := pb.NewCryptoClient(conn)
ecParameters, err := asn1.Marshal(util.OIDNamedCurveP256)
if err != nil {
panic(fmt.Errorf("Unable to encode parameter OID: %s", err))
}
publicKeyECTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_EC_PARAMS, ecParameters),
util.NewAttribute(ep11.CKA_VERIFY, true),
util.NewAttribute(ep11.CKA_EXTRACTABLE, false),
)
privateKeyECTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_SIGN, true),
util.NewAttribute(ep11.CKA_EXTRACTABLE, false),
)
generateECKeypairRequest := &pb.GenerateKeyPairRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_EC_KEY_PAIR_GEN},
PubKeyTemplate: publicKeyECTemplate,
PrivKeyTemplate: privateKeyECTemplate,
}
generateKeyPairStatus, err := cryptoClient.GenerateKeyPair(context.Background(), generateECKeypairRequest)
if err != nil {
panic(fmt.Errorf("GenerateKeyPair error: %s", err))
}
fmt.Println("Generated ECDSA PKCS key pair")
// Sign data
signInitRequest := &pb.SignInitRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_ECDSA},
PrivKey: generateKeyPairStatus.PrivKey,
}
signInitResponse, err := cryptoClient.SignInit(context.Background(), signInitRequest)
if err != nil {
panic(fmt.Errorf("SignInit error: %s", err))
}
signData := sha256.New().Sum([]byte("This data needs to be signed"))
signRequest := &pb.SignRequest{
State: signInitResponse.State,
Data: signData,
}
SignResponse, err := cryptoClient.Sign(context.Background(), signRequest)
if err != nil {
panic(fmt.Errorf("Sign error: %s", err))
}
fmt.Println("Data signed")
// Modify signature to force returned error code
SignResponse.Signature[0] = 255
verifyInitRequest := &pb.VerifyInitRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_ECDSA},
PubKey: generateKeyPairStatus.PubKey,
}
verifyInitResponse, err := cryptoClient.VerifyInit(context.Background(), verifyInitRequest)
if err != nil {
panic(fmt.Errorf("VerifyInit error: %s", err))
}
verifyRequest := &pb.VerifyRequest{
State: verifyInitResponse.State,
Data: signData,
Signature: SignResponse.Signature,
}
_, err = cryptoClient.Verify(context.Background(), verifyRequest)
if ok, ep11Status := util.Convert(err); !ok {
if ep11Status.Code == ep11.CKR_SIGNATURE_INVALID {
fmt.Printf("Invalid signature\n")
return
}
panic(fmt.Errorf("Verify error: [%d]: %s", ep11Status.Code, ep11Status.Detail))
}
// Output:
// Generated ECDSA PKCS key pair
// Data signed
// Invalid signature
}
// Example_wrapAndUnWrapKey wraps an AES key with a RSA public key and then unwraps it with the private key
// Flow: connect, generate AES key, generate RSA key pair, wrap/unwrap AES key with RSA key pair
func Example_wrapAndUnwrapKey() {
conn, err := grpc.Dial(address, callOpts...)
if err != nil {
panic(fmt.Errorf("Could not connect to server: %s", err))
}
defer conn.Close()
cryptoClient := pb.NewCryptoClient(conn)
// Generate a AES key
desKeyTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_VALUE_LEN, (uint64)(128/8)),
util.NewAttribute(ep11.CKA_ENCRYPT, true),
util.NewAttribute(ep11.CKA_DECRYPT, true),
util.NewAttribute(ep11.CKA_EXTRACTABLE, true), // must be true to be wrapped
)
generateKeyRequest := &pb.GenerateKeyRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_AES_KEY_GEN},
Template: desKeyTemplate,
KeyId: uuid.NewV4().String(), // optional
}
generateNewKeyStatus, err := cryptoClient.GenerateKey(context.Background(), generateKeyRequest)
if err != nil {
panic(fmt.Errorf("Generate AES key error: %s", err))
} else {
fmt.Println("Generated AES key")
}
// Generate RSA key pairs
publicExponent := []byte{0x11}
publicKeyTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_ENCRYPT, true),
util.NewAttribute(ep11.CKA_WRAP, true), // to wrap a key
util.NewAttribute(ep11.CKA_MODULUS_BITS, uint64(2048)),
util.NewAttribute(ep11.CKA_PUBLIC_EXPONENT, publicExponent),
util.NewAttribute(ep11.CKA_EXTRACTABLE, false),
)
privateKeyTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_PRIVATE, true),
util.NewAttribute(ep11.CKA_SENSITIVE, true),
util.NewAttribute(ep11.CKA_DECRYPT, true),
util.NewAttribute(ep11.CKA_UNWRAP, true), // to unwrap a key
util.NewAttribute(ep11.CKA_EXTRACTABLE, false),
)
generateKeypairRequest := &pb.GenerateKeyPairRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_RSA_PKCS_KEY_PAIR_GEN},
PubKeyTemplate: publicKeyTemplate,
PrivKeyTemplate: privateKeyTemplate,
PrivKeyId: uuid.NewV4().String(),
PubKeyId: uuid.NewV4().String(),
}
generateKeyPairStatus, err := cryptoClient.GenerateKeyPair(context.Background(), generateKeypairRequest)
if err != nil {
panic(fmt.Errorf("GenerateKeyPair error: %s", err))
}
fmt.Println("Generated PKCS key pair")
wrapKeyRequest := &pb.WrapKeyRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_RSA_PKCS},
KeK: generateKeyPairStatus.PubKey,
Key: generateNewKeyStatus.Key,
}
wrapKeyResponse, err := cryptoClient.WrapKey(context.Background(), wrapKeyRequest)
if err != nil {
panic(fmt.Errorf("Wrap AES key error: %s", err))
}
fmt.Println("Wraped AES key")
desUnwrapKeyTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_CLASS, ep11.CKO_SECRET_KEY),
util.NewAttribute(ep11.CKA_KEY_TYPE, ep11.CKK_AES),
util.NewAttribute(ep11.CKA_VALUE_LEN, (uint64)(128/8)),
util.NewAttribute(ep11.CKA_ENCRYPT, true),
util.NewAttribute(ep11.CKA_DECRYPT, true),
util.NewAttribute(ep11.CKA_EXTRACTABLE, true), // must be true to be wrapped
)
unwrapRequest := &pb.UnwrapKeyRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_RSA_PKCS},
KeK: generateKeyPairStatus.PrivKey,
Wrapped: wrapKeyResponse.Wrapped,
Template: desUnwrapKeyTemplate,
}
unWrapedResponse, err := cryptoClient.UnwrapKey(context.Background(), unwrapRequest)
if err != nil {
panic(fmt.Errorf("Unwrap AES key error: %s", err))
}
if !bytes.Equal(generateNewKeyStatus.GetCheckSum()[:3], unWrapedResponse.GetCheckSum()[:3]) {
panic(fmt.Errorf("Unwrap AES key has a different checksum than the original key"))
} else {
fmt.Println("Unwraped AES key")
}
// Output:
// Generated AES key
// Generated PKCS key pair
// Wraped AES key
// Unwraped AES key
}
// Example_deriveKey generates ECDHE key pairs for Bob and Alice and then generates AES keys for both of them.
// The names Alice and Bob are described in https://en.wikipedia.org/wiki/Diffie–Hellman_key_exchange.
// Flow: connect, generate key pairs, derive AES key for Bob, derive AES key for Alice, encrypt with Alice's AES key and decrypt with Bob's AES key
func Example_deriveKey() {
conn, err := grpc.Dial(address, callOpts...)
if err != nil {
panic(fmt.Errorf("Could not connect to server: %s", err))
}
defer conn.Close()
cryptoClient := pb.NewCryptoClient(conn)
// Generate ECDH key pairs for Alice and Bob
ecParameters, err := asn1.Marshal(util.OIDNamedCurveP256)
if err != nil {
panic(fmt.Errorf("Unable to encode parameter OID: %s", err))
}
publicKeyECTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_EC_PARAMS, ecParameters),
util.NewAttribute(ep11.CKA_EXTRACTABLE, false),
)
privateKeyECTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_DERIVE, true),
util.NewAttribute(ep11.CKA_EXTRACTABLE, false),
)
generateECKeypairRequest := &pb.GenerateKeyPairRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_EC_KEY_PAIR_GEN},
PubKeyTemplate: publicKeyECTemplate,
PrivKeyTemplate: privateKeyECTemplate,
}
aliceECKeypairResponse, err := cryptoClient.GenerateKeyPair(context.Background(), generateECKeypairRequest)
if err != nil {
panic(fmt.Errorf("Generate Alice EC key pair error: %s", err))
}
fmt.Println("Generated Alice EC key pair")
bobECKeypairResponse, err := cryptoClient.GenerateKeyPair(context.Background(), generateECKeypairRequest)
if err != nil {
panic(fmt.Errorf("Generate Bob EC key pair error: %s", err))
}
fmt.Println("Generated Bob EC key pair")
// Derive AES key for Alice
deriveKeyTemplate := util.NewAttributeMap(
util.NewAttribute(ep11.CKA_CLASS, uint64(ep11.CKO_SECRET_KEY)),
util.NewAttribute(ep11.CKA_KEY_TYPE, uint64(ep11.CKK_AES)),
util.NewAttribute(ep11.CKA_VALUE_LEN, (uint64)(128/8)),
util.NewAttribute(ep11.CKA_ENCRYPT, true),
util.NewAttribute(ep11.CKA_DECRYPT, true),
)
combinedCoordinates, err := util.GetPubkeyBytesFromSPKI(bobECKeypairResponse.PubKey)
if err != nil {
panic(fmt.Errorf("Bob's EC key cannot obtain coordinates: %s", err))
}
aliceDerivekeyRequest := &pb.DeriveKeyRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_ECDH1_DERIVE, Parameter: combinedCoordinates},
Template: deriveKeyTemplate,
BaseKey: aliceECKeypairResponse.PrivKey,
}
aliceDerivekeyResponse, err := cryptoClient.DeriveKey(context.Background(), aliceDerivekeyRequest)
if err != nil {
panic(fmt.Errorf("Alice EC key derive error: %s", err))
}
// Derive AES key for Bob
combinedCoordinates, err = util.GetPubkeyBytesFromSPKI(aliceECKeypairResponse.PubKey)
if err != nil {
panic(fmt.Errorf("Alice's EC key cannot obtain coordinates: %s", err))
}
bobDerivekeyRequest := &pb.DeriveKeyRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_ECDH1_DERIVE, Parameter: combinedCoordinates},
Template: deriveKeyTemplate,
BaseKey: bobECKeypairResponse.PrivKey,
}
bobDerivekeyResponse, err := cryptoClient.DeriveKey(context.Background(), bobDerivekeyRequest)
if err != nil {
panic(fmt.Errorf("Bob EC Key Derive Error: %s", err))
}
// Encrypt with Alice's key and decrypt with Bob's key
var msg = []byte("hello world!")
rngTemplate := &pb.GenerateRandomRequest{
Len: (uint64)(ep11.AES_BLOCK_SIZE),
}
rng, err := cryptoClient.GenerateRandom(context.Background(), rngTemplate)
if err != nil {
panic(fmt.Errorf("GenerateRandom error: %s", err))
}
iv := rng.Rnd[:ep11.AES_BLOCK_SIZE]
encryptRequest := &pb.EncryptSingleRequest{
Key: aliceDerivekeyResponse.NewKey,
Mech: &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: iv},
Plain: msg,
}
encryptResponse, err := cryptoClient.EncryptSingle(context.Background(), encryptRequest)
if err != nil {
panic(fmt.Errorf("Encrypt error: %s", err))
}
decryptRequest := &pb.DecryptSingleRequest{
Key: bobDerivekeyResponse.NewKey,
Mech: &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: iv},
Ciphered: encryptResponse.Ciphered,
}
decryptResponse, err := cryptoClient.DecryptSingle(context.Background(), decryptRequest)
if err != nil {
panic(fmt.Errorf("Decrypt error: %s", err))
}
if !bytes.Equal(decryptResponse.Plain, msg) {
panic(fmt.Errorf("Decrypted message[%v] is different from the original message: [%v]", decryptResponse.Plain, msg))
} else {
fmt.Println("Alice and Bob get the same derived key")
}
return
// Output:
// Generated Alice EC key pair
// Generated Bob EC key pair
// Alice and Bob get the same derived key
}