/
kms.go
1101 lines (904 loc) · 34.5 KB
/
kms.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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package kms
/*
* Copyright 2020-2023 Aldelo, LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// =================================================================================================================
// AWS CREDENTIAL:
// use $> aws configure (to set aws access key and secret to target machine)
// Store AWS Access ID and Secret Key into Default Profile Using '$ aws configure' cli
//
// To Install & Setup AWS CLI on Host:
// 1) https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-linux.html
// On Ubuntu, if host does not have zip and unzip:
// $> sudo apt install zip
// $> sudo apt install unzip
// On Ubuntu, to install AWS CLI v2:
// $> curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
// $> unzip awscliv2.zip
// $> sudo ./aws/install
// 2) $> aws configure set region awsRegionName --profile default
// 3) $> aws configure
// follow prompts to enter Access ID and Secret Key
//
// AWS Region Name Reference:
// us-west-2, us-east-1, ap-northeast-1, etc
// See: https://docs.aws.amazon.com/general/latest/gr/rande.html
// =================================================================================================================
import (
"context"
"errors"
util "github.com/aldelo/common"
"github.com/aldelo/common/crypto"
awshttp2 "github.com/aldelo/common/wrapper/aws"
"github.com/aldelo/common/wrapper/aws/awsregion"
"github.com/aldelo/common/wrapper/xray"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
awsxray "github.com/aws/aws-xray-sdk-go/xray"
"net/http"
)
// ================================================================================================================
// STRUCTS
// ================================================================================================================
// KMS struct encapsulates the AWS KMS access functionality
type KMS struct {
// define the AWS region that KMS is located at
AwsRegion awsregion.AWSRegion
// custom http2 client options
HttpOptions *awshttp2.HttpClientSettings
// define kms key name
AesKmsKeyName string
RsaKmsKeyName string
SignatureKmsKeyName string
// store aws session object
sess *session.Session
// store kms client object
kmsClient *kms.KMS
_parentSegment *xray.XRayParentSegment
}
// ================================================================================================================
// STRUCTS FUNCTIONS
// ================================================================================================================
// ----------------------------------------------------------------------------------------------------------------
// utility functions
// ----------------------------------------------------------------------------------------------------------------
// Connect will establish a connection to the KMS service
func (k *KMS) Connect(parentSegment ...*xray.XRayParentSegment) (err error) {
if xray.XRayServiceOn() {
if len(parentSegment) > 0 {
k._parentSegment = parentSegment[0]
}
seg := xray.NewSegment("KMS-Connect", k._parentSegment)
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("KDS-AWS-Region", k.AwsRegion)
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
err = k.connectInternal()
if err == nil {
awsxray.AWS(k.kmsClient.Client)
}
return err
} else {
return k.connectInternal()
}
}
// Connect will establish a connection to the KMS service
func (k *KMS) connectInternal() error {
// clean up prior session reference
k.sess = nil
if !k.AwsRegion.Valid() || k.AwsRegion == awsregion.UNKNOWN {
return errors.New("Connect To KMS Failed: (AWS Session Error) " + "Region is Required")
}
// create custom http2 client if needed
var httpCli *http.Client
var httpErr error
if k.HttpOptions == nil {
k.HttpOptions = new(awshttp2.HttpClientSettings)
}
// use custom http2 client
h2 := &awshttp2.AwsHttp2Client{
Options: k.HttpOptions,
}
if httpCli, httpErr = h2.NewHttp2Client(); httpErr != nil {
return errors.New("Connect to KMS Failed: (AWS Session Error) " + "Create Custom Http2 Client Errored = " + httpErr.Error())
}
// establish aws session connection and keep session object in struct
if sess, err := session.NewSession(
&aws.Config{
Region: aws.String(k.AwsRegion.Key()),
HTTPClient: httpCli,
}); err != nil {
// aws session error
return errors.New("Connect To KMS Failed: (AWS Session Error) " + err.Error())
} else {
// aws session obtained
k.sess = sess
// create cached objects for shared use
k.kmsClient = kms.New(k.sess)
if k.kmsClient == nil {
return errors.New("Connect To KMS Client Failed: (New KMS Client Connection) " + "Connection Object Nil")
}
// session stored to struct
return nil
}
}
// Disconnect will disjoin from aws session by clearing it
func (k *KMS) Disconnect() {
k.kmsClient = nil
k.sess = nil
}
// UpdateParentSegment updates this struct's xray parent segment, if no parent segment, set nil
func (k *KMS) UpdateParentSegment(parentSegment *xray.XRayParentSegment) {
k._parentSegment = parentSegment
}
// ----------------------------------------------------------------------------------------------------------------
// kms-cmk encrypt/decrypt via aes 256 functions
// ----------------------------------------------------------------------------------------------------------------
// EncryptViaCmkAes256 will use kms cmk to encrypt plainText using aes 256 symmetric kms cmk key, and return cipherText string,
// the cipherText can only be decrypted with aes 256 symmetric kms cmk key
func (k *KMS) EncryptViaCmkAes256(plainText string) (cipherText string, err error) {
var segCtx context.Context
segCtx = nil
seg := xray.NewSegmentNullable("KMS-EncryptViaCmkAes256", k._parentSegment)
if seg != nil {
segCtx = seg.Ctx
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("KMS-EncryptViaCmkAes256-AES-KMS-KeyName", k.AesKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-EncryptViaCmkAes256-PlainText-Length", len(plainText))
_ = seg.Seg.AddMetadata("KMS-EncryptViaCmkAes256-Result-CipherText-Length", len(cipherText))
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validate
if k.kmsClient == nil {
err = errors.New("EncryptViaCmkAes256 with KMS CMK Failed: " + "KMS Client is Required")
return "", err
}
if len(k.AesKmsKeyName) <= 0 {
err = errors.New("EncryptViaCmkAes256 with KMS CMK Failed: " + "AES KMS Key Name is Required")
return "", err
}
if len(plainText) <= 0 {
err = errors.New("EncryptViaCmkAes256 with KMS CMK Failed: " + "PlainText is Required")
return "", err
}
// prepare key info
keyId := "alias/" + k.AesKmsKeyName
// encrypt symmetric using kms cmk
var encryptedOutput *kms.EncryptOutput
var e error
if segCtx == nil {
encryptedOutput, e = k.kmsClient.Encrypt(&kms.EncryptInput{
EncryptionAlgorithm: aws.String("SYMMETRIC_DEFAULT"),
KeyId: aws.String(keyId),
Plaintext: []byte(plainText),
})
} else {
encryptedOutput, e = k.kmsClient.EncryptWithContext(segCtx,
&kms.EncryptInput{
EncryptionAlgorithm: aws.String("SYMMETRIC_DEFAULT"),
KeyId: aws.String(keyId),
Plaintext: []byte(plainText),
})
}
if e != nil {
err = errors.New("EncryptViaCmkAes256 with KMS CMK Failed: (Symmetric Encrypt) " + e.Error())
return "", err
}
// return encrypted cipher text blob
cipherText = util.ByteToHex(encryptedOutput.CiphertextBlob)
return cipherText, nil
}
// ReEncryptViaCmkAes256 will re-encrypt sourceCipherText using the new targetKmsKeyName via kms, (must be targeting aes 256 key)
// the re-encrypted cipherText is then returned
func (k *KMS) ReEncryptViaCmkAes256(sourceCipherText string, targetKmsKeyName string) (targetCipherText string, err error) {
var segCtx context.Context
segCtx = nil
seg := xray.NewSegmentNullable("KMS-ReEncryptViaCmkAes256", k._parentSegment)
if seg != nil {
segCtx = seg.Ctx
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("KMS-ReEncryptViaCmkAes256-Source-AES-KMS-KeyName", k.AesKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-ReEncryptViaCmkAes256-Target-AES-KMS-KeyName", targetKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-ReEncryptViaCmkAes256-SourceCipherText-Length", len(sourceCipherText))
_ = seg.Seg.AddMetadata("KMS-ReEncryptViaCmkAes256-Result-Target-CipherText-Length", len(targetCipherText))
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validate
if k.kmsClient == nil {
err = errors.New("ReEncryptViaCmkAes256 with KMS CMK Failed: " + "KMS Client is Required")
return "", err
}
if len(k.AesKmsKeyName) <= 0 {
err = errors.New("ReEncryptViaCmkAes256 with KMS CMK Failed: " + "AES KMS Key Name is Required")
return "", err
}
if len(sourceCipherText) <= 0 {
err = errors.New("ReEncryptViaCmkAes256 with KMS CMK Failed: " + "Source CipherText is Required")
return "", err
}
if len(targetKmsKeyName) <= 0 {
err = errors.New("ReEncryptViaCmkAes256 with KMS CMK Failed: " + "Target KMS Key Name is Required")
return "", err
}
// prepare key info
keyId := "alias/" + k.AesKmsKeyName
// convert hex to bytes
cipherBytes, ce := util.HexToByte(sourceCipherText)
if ce != nil {
err = errors.New("ReEncryptViaCmkAes256 with KMS CMK Failed: (Unmarshal Source CipherText Hex To Byte) " + ce.Error())
return "", err
}
// re-encrypt symmetric kms cmk
var reEncryptOutput *kms.ReEncryptOutput
var e error
if segCtx == nil {
reEncryptOutput, e = k.kmsClient.ReEncrypt(&kms.ReEncryptInput{
SourceEncryptionAlgorithm: aws.String("SYMMETRIC_DEFAULT"),
SourceKeyId: aws.String(keyId),
DestinationEncryptionAlgorithm: aws.String("SYMMETRIC_DEFAULT"),
DestinationKeyId: aws.String("alias/" + targetKmsKeyName),
CiphertextBlob: cipherBytes,
})
} else {
reEncryptOutput, e = k.kmsClient.ReEncryptWithContext(segCtx,
&kms.ReEncryptInput{
SourceEncryptionAlgorithm: aws.String("SYMMETRIC_DEFAULT"),
SourceKeyId: aws.String(keyId),
DestinationEncryptionAlgorithm: aws.String("SYMMETRIC_DEFAULT"),
DestinationKeyId: aws.String("alias/" + targetKmsKeyName),
CiphertextBlob: cipherBytes,
})
}
if e != nil {
err = errors.New("ReEncryptViaCmkAes256 with KMS CMK Failed: (Symmetric ReEncrypt) " + e.Error())
return "", err
}
// return encrypted cipher text blob
targetCipherText = util.ByteToHex(reEncryptOutput.CiphertextBlob)
return targetCipherText, nil
}
// DecryptViaCmkAes256 will use kms cmk to decrypt cipherText using symmetric aes 256 kms cmk key, and return plainText string,
// the cipherText can only be decrypted with the symmetric aes 256 kms cmk key
func (k *KMS) DecryptViaCmkAes256(cipherText string) (plainText string, err error) {
var segCtx context.Context
segCtx = nil
seg := xray.NewSegmentNullable("KMS-DecryptViaCmkAes256", k._parentSegment)
if seg != nil {
segCtx = seg.Ctx
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("KMS-DecryptViaCmkAes256-AES-KMS-KeyName", k.AesKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-DecryptViaCmkAes256-CipherText-Length", len(cipherText))
_ = seg.Seg.AddMetadata("KMS-DecryptViaCmkAes256-Result-PlainText-Length", len(plainText))
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validate
if k.kmsClient == nil {
err = errors.New("DecryptViaCmkAes256 with KMS CMK Failed: " + "KMS Client is Required")
return "", err
}
if len(k.AesKmsKeyName) <= 0 {
err = errors.New("DecryptViaCmkAes256 with KMS CMK Failed: " + "AES KMS Key Name is Required")
return "", err
}
if len(cipherText) <= 0 {
err = errors.New("DecryptViaCmkAes256 with KMS CMK Failed: " + "Cipher Text is Required")
return "", err
}
// prepare key info
keyId := "alias/" + k.AesKmsKeyName
cipherBytes, ce := util.HexToByte(cipherText)
if ce != nil {
err = errors.New("DecryptViaCmkAes256 with KMS CMK Failed: (Unmarshal CipherText Hex To Byte) " + ce.Error())
return "", err
}
// decrypt symmetric using kms cmk
var decryptedOutput *kms.DecryptOutput
var e error
if segCtx == nil {
decryptedOutput, e = k.kmsClient.Decrypt(&kms.DecryptInput{
EncryptionAlgorithm: aws.String("SYMMETRIC_DEFAULT"),
KeyId: aws.String(keyId),
CiphertextBlob: cipherBytes,
})
} else {
decryptedOutput, e = k.kmsClient.DecryptWithContext(segCtx,
&kms.DecryptInput{
EncryptionAlgorithm: aws.String("SYMMETRIC_DEFAULT"),
KeyId: aws.String(keyId),
CiphertextBlob: cipherBytes,
})
}
if e != nil {
err = errors.New("DecryptViaCmkAes256 with KMS CMK Failed: (Symmetric Decrypt) " + e.Error())
return "", err
}
// return decrypted cipher text blob
plainText = string(decryptedOutput.Plaintext)
return plainText, nil
}
// ----------------------------------------------------------------------------------------------------------------
// kms-cmk encrypt/decrypt via rsa 2048 public/private key functions
// ----------------------------------------------------------------------------------------------------------------
// EncryptViaCmkRsa2048 will use kms cmk to encrypt plainText with asymmetric rsa 2048 kms cmk public key, and return cipherText string,
// the cipherText can only be decrypted with the paired asymmetric rsa 2048 kms cmk private key
//
// *** To Encrypt using Public Key Outside of KMS ***
// 1. Copy Public Key from AWS KMS for the given RSA CMK
// 2. Using External RSA Public Key Crypto Encrypt Function with the given Public Key to Encrypt
func (k *KMS) EncryptViaCmkRsa2048(plainText string) (cipherText string, err error) {
var segCtx context.Context
segCtx = nil
seg := xray.NewSegmentNullable("KMS-EncryptViaCmkRsa2048", k._parentSegment)
if seg != nil {
segCtx = seg.Ctx
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("KMS-EncryptViaCmkRsa2048-RSA-KMS-KeyName", k.RsaKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-EncryptViaCmkRsa2048-PlainText-Length", len(plainText))
_ = seg.Seg.AddMetadata("KMS-EncryptViaCmkRsa2048-Result-CipherText-Length", len(cipherText))
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validate
if k.kmsClient == nil {
err = errors.New("EncryptViaCmkRsa2048 with KMS CMK Failed: " + "KMS Client is Required")
return "", err
}
if len(k.RsaKmsKeyName) <= 0 {
err = errors.New("EncryptViaCmkRsa2048 with KMS CMK Failed: " + "RSA KMS Key Name is Required")
return "", err
}
if len(plainText) <= 0 {
err = errors.New("EncryptViaCmkRsa2048 with KMS CMK Failed: " + "PlainText is Required")
return "", err
}
if len(plainText) > 214 {
err = errors.New("EncryptViaCmkRsa2048 with KMS CMK Failed: " + "PlainText Cannot Exceed 214 Bytes")
return "", err
}
// prepare key info
keyId := "alias/" + k.RsaKmsKeyName
// encrypt asymmetric using kms cmk
var encryptedOutput *kms.EncryptOutput
var e error
if segCtx == nil {
encryptedOutput, e = k.kmsClient.Encrypt(&kms.EncryptInput{
EncryptionAlgorithm: aws.String("RSAES_OAEP_SHA_256"),
KeyId: aws.String(keyId),
Plaintext: []byte(plainText),
})
} else {
encryptedOutput, e = k.kmsClient.EncryptWithContext(segCtx,
&kms.EncryptInput{
EncryptionAlgorithm: aws.String("RSAES_OAEP_SHA_256"),
KeyId: aws.String(keyId),
Plaintext: []byte(plainText),
})
}
if e != nil {
err = errors.New("EncryptViaCmkRsa2048 with KMS CMK Failed: (Asymmetric Encrypt) " + e.Error())
return "", err
}
// return encrypted cipher text blob
cipherText = util.ByteToHex(encryptedOutput.CiphertextBlob)
return cipherText, nil
}
// ReEncryptViaCmkRsa2048 will re-encrypt sourceCipherText using the new targetKmsKeyName via kms, (must be targeting rsa 2048 key)
// the re-encrypted cipherText is then returned
func (k *KMS) ReEncryptViaCmkRsa2048(sourceCipherText string, targetKmsKeyName string) (targetCipherText string, err error) {
var segCtx context.Context
segCtx = nil
seg := xray.NewSegmentNullable("KMS-ReEncryptViaCmkRsa2048", k._parentSegment)
if seg != nil {
segCtx = seg.Ctx
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("KMS-ReEncryptViaCmkRsa2048-Source-RSA-KMS-KeyName", k.AesKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-ReEncryptViaCmkRsa2048-Target-RSA-KMS-KeyName", targetKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-ReEncryptViaCmkRsa2048-Source-CipherText-Length", len(sourceCipherText))
_ = seg.Seg.AddMetadata("KMS-ReEncryptViaCmkRsa2048-Result-Target-CipherText-Length", len(targetCipherText))
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validate
if k.kmsClient == nil {
err = errors.New("ReEncryptViaCmkRsa2048 with KMS CMK Failed: " + "KMS Client is Required")
return "", err
}
if len(k.RsaKmsKeyName) <= 0 {
err = errors.New("ReEncryptViaCmkRsa2048 with KMS CMK Failed: " + "RSA KMS Key Name is Required")
return "", err
}
if len(sourceCipherText) <= 0 {
err = errors.New("ReEncryptViaCmkRsa2048 with KMS CMK Failed: " + "Source CipherText is Required")
return "", err
}
if len(targetKmsKeyName) <= 0 {
err = errors.New("ReEncryptViaCmkRsa2048 with KMS CMK Failed: " + "Target KMS Key Name is Required")
return "", err
}
// prepare key info
keyId := "alias/" + k.RsaKmsKeyName
// convert hex to bytes
cipherBytes, ce := util.HexToByte(sourceCipherText)
if ce != nil {
err = errors.New("ReEncryptViaCmkRsa2048 with KMS CMK Failed: (Unmarshal Source CipherText Hex To Byte) " + ce.Error())
return "", err
}
// re-encrypt asymmetric kms cmk
var reEncryptOutput *kms.ReEncryptOutput
var e error
if segCtx == nil {
reEncryptOutput, e = k.kmsClient.ReEncrypt(&kms.ReEncryptInput{
SourceEncryptionAlgorithm: aws.String("RSAES_OAEP_SHA_256"),
SourceKeyId: aws.String(keyId),
DestinationEncryptionAlgorithm: aws.String("RSAES_OAEP_SHA_256"),
DestinationKeyId: aws.String("alias/" + targetKmsKeyName),
CiphertextBlob: cipherBytes,
})
} else {
reEncryptOutput, e = k.kmsClient.ReEncryptWithContext(segCtx,
&kms.ReEncryptInput{
SourceEncryptionAlgorithm: aws.String("RSAES_OAEP_SHA_256"),
SourceKeyId: aws.String(keyId),
DestinationEncryptionAlgorithm: aws.String("RSAES_OAEP_SHA_256"),
DestinationKeyId: aws.String("alias/" + targetKmsKeyName),
CiphertextBlob: cipherBytes,
})
}
if e != nil {
err = errors.New("ReEncryptViaCmkRsa2048 with KMS CMK Failed: (Asymmetric ReEncrypt) " + e.Error())
return "", err
}
// return encrypted cipher text blob
targetCipherText = util.ByteToHex(reEncryptOutput.CiphertextBlob)
return targetCipherText, nil
}
// DecryptViaCmkRsa2048 will use kms cmk to decrypt cipherText using asymmetric rsa 2048 kms cmk private key, and return plainText string,
// the cipherText can only be decrypted with the asymmetric rsa 2048 kms cmk private key
func (k *KMS) DecryptViaCmkRsa2048(cipherText string) (plainText string, err error) {
var segCtx context.Context
segCtx = nil
seg := xray.NewSegmentNullable("KMS-DecryptViaCmkRsa2048", k._parentSegment)
if seg != nil {
segCtx = seg.Ctx
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("KMS-DecryptViaCmkRsa2048-RSA-KMS-KeyName", k.RsaKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-DecryptViaCmkRsa2048-CipherText-Length", len(cipherText))
_ = seg.Seg.AddMetadata("KMS-DecryptViaCmkRsa2048-Result-PlainText-Length", len(plainText))
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validate
if k.kmsClient == nil {
err = errors.New("DecryptViaCmkRsa2048 with KMS CMK Failed: " + "KMS Client is Required")
return "", err
}
if len(k.RsaKmsKeyName) <= 0 {
err = errors.New("DecryptViaCmkRsa2048 with KMS CMK Failed: " + "RSA KMS Key Name is Required")
return "", err
}
if len(cipherText) <= 0 {
err = errors.New("DecryptViaCmkRsa2048 with KMS CMK Failed: " + "Cipher Text is Required")
return "", err
}
// prepare key info
keyId := "alias/" + k.RsaKmsKeyName
cipherBytes, ce := util.HexToByte(cipherText)
if ce != nil {
err = errors.New("DecryptViaCmkRsa2048 with KMS CMK Failed: (Unmarshal CipherText Hex To Byte) " + ce.Error())
return "", err
}
// decrypt symmetric using kms cmk
var decryptedOutput *kms.DecryptOutput
var e error
if segCtx == nil {
decryptedOutput, e = k.kmsClient.Decrypt(&kms.DecryptInput{
EncryptionAlgorithm: aws.String("RSAES_OAEP_SHA_256"),
KeyId: aws.String(keyId),
CiphertextBlob: cipherBytes,
})
} else {
decryptedOutput, e = k.kmsClient.DecryptWithContext(segCtx,
&kms.DecryptInput{
EncryptionAlgorithm: aws.String("RSAES_OAEP_SHA_256"),
KeyId: aws.String(keyId),
CiphertextBlob: cipherBytes,
})
}
if e != nil {
err = errors.New("DecryptViaCmkRsa2048 with KMS CMK Failed: (Asymmetric Decrypt) " + e.Error())
return "", err
}
// return decrypted cipher text blob
plainText = string(decryptedOutput.Plaintext)
return plainText, nil
}
// ----------------------------------------------------------------------------------------------------------------
// kms-cmk sign/verify via rsa 2048 private/public key functions
// ----------------------------------------------------------------------------------------------------------------
// SignViaCmkRsa2048 will sign dataToSign using KMS CMK RSA Sign/Verify Key (Private Key on KMS will be used to securely sign)
func (k *KMS) SignViaCmkRsa2048(dataToSign string) (signature string, err error) {
var segCtx context.Context
segCtx = nil
seg := xray.NewSegmentNullable("KMS-SignViaCmkRsa2048", k._parentSegment)
if seg != nil {
segCtx = seg.Ctx
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("KMS-SignViaCmkRsa2048-Signature-KMS-KeyName", k.SignatureKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-SignViaCmkRsa2048-DataToSign-Length", len(dataToSign))
_ = seg.Seg.AddMetadata("KMS-SignViaCmkRsa2048-Result-Signature", signature)
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validate
if k.kmsClient == nil {
err = errors.New("SignViaCmkRsa2048 with KMS Failed: " + "KMS Client is Required")
return "", err
}
if len(k.SignatureKmsKeyName) <= 0 {
err = errors.New("SignViaCmkRsa2048 with KMS Failed: " + "Signature KMS Key Name is Required")
return "", err
}
if len(dataToSign) <= 0 {
err = errors.New("SignViaCmkRsa2048 with KMS Failed: " + "Data To Sign is Required")
return "", err
}
// prepare key info
keyId := "alias/" + k.SignatureKmsKeyName
// perform sign action using kms rsa sign/verify cmk
var signOutput *kms.SignOutput
var e error
if segCtx == nil {
signOutput, e = k.kmsClient.Sign(&kms.SignInput{
KeyId: aws.String(keyId),
SigningAlgorithm: aws.String("RSASSA_PKCS1_V1_5_SHA_256"),
MessageType: aws.String("RAW"),
Message: []byte(dataToSign),
})
} else {
signOutput, e = k.kmsClient.SignWithContext(segCtx,
&kms.SignInput{
KeyId: aws.String(keyId),
SigningAlgorithm: aws.String("RSASSA_PKCS1_V1_5_SHA_256"),
MessageType: aws.String("RAW"),
Message: []byte(dataToSign),
})
}
if e != nil {
err = errors.New("SignViaCmkRsa2048 with KMS Failed: (Sign Action) " + e.Error())
return "", err
}
// return signature
signature = util.ByteToHex(signOutput.Signature)
return signature, nil
}
// VerifyViaCmkRsa2048 will verify dataToVerify with signature using KMS CMK RSA Sign/Verify Key (Public Key on KMS will be used securely to verify)
//
// signatureToVerify = prior signed signature in hex to verify against the dataToVerify parameter
//
// *** To Verify using Public Key Outside of KMS ***
// 1. Copy Public Key from AWS KMS for the given RSA CMK
// 2. Using External RSA Public Key Crypto Verify Function with the given Public Key to Verify
func (k *KMS) VerifyViaCmkRsa2048(dataToVerify string, signatureToVerify string) (signatureValid bool, err error) {
var segCtx context.Context
segCtx = nil
seg := xray.NewSegmentNullable("KMS-VerifyViaCmkRsa2048", k._parentSegment)
if seg != nil {
segCtx = seg.Ctx
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("KMS-VerifyViaCmkRsa2048-Signature-KMS-KeyName", k.SignatureKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-VerifyViaCmkRsa2048-DataToVerify-Length", len(dataToVerify))
_ = seg.Seg.AddMetadata("KMS-VerifyViaCmkRsa2048-Signature-To-Verify", signatureToVerify)
_ = seg.Seg.AddMetadata("KMS-VerifyViaCmkRsa2048-Result-SignatureValid", signatureValid)
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validate
if k.kmsClient == nil {
err = errors.New("VerifyViaCmkRsa2048 with KMS Failed: " + "KMS Client is Required")
return false, err
}
if len(k.SignatureKmsKeyName) <= 0 {
err = errors.New("VerifyViaCmkRsa2048 with KMS Failed: " + "Signature KMS Key Name is Required")
return false, err
}
if len(dataToVerify) <= 0 {
err = errors.New("VerifyViaCmkRsa2048 with KMS Failed: " + "Data To Verify is Required")
return false, err
}
if len(signatureToVerify) <= 0 {
err = errors.New("VerifyViaCmkRsa2048 with KMS Failed: " + "Signature To Verify is Required")
return false, err
}
// prepare key info
keyId := "alias/" + k.SignatureKmsKeyName
signatureBytes, ce := util.HexToByte(signatureToVerify)
if ce != nil {
err = errors.New("VerifyViaCmkRsa2048 with KMS Failed: (Marshal SignatureToVerify Hex To Byte) " + ce.Error())
return false, err
}
// perform verify action using kms rsa sign/verify cmk
var verifyOutput *kms.VerifyOutput
var e error
if segCtx == nil {
verifyOutput, e = k.kmsClient.Verify(&kms.VerifyInput{
KeyId: aws.String(keyId),
SigningAlgorithm: aws.String("RSASSA_PKCS1_V1_5_SHA_256"),
MessageType: aws.String("RAW"),
Message: []byte(dataToVerify),
Signature: signatureBytes,
})
} else {
verifyOutput, e = k.kmsClient.VerifyWithContext(segCtx,
&kms.VerifyInput{
KeyId: aws.String(keyId),
SigningAlgorithm: aws.String("RSASSA_PKCS1_V1_5_SHA_256"),
MessageType: aws.String("RAW"),
Message: []byte(dataToVerify),
Signature: signatureBytes,
})
}
if e != nil {
err = errors.New("VerifyViaCmkRsa2048 with KMS Failed: (Verify Action) " + e.Error())
return false, err
}
// return verify result
signatureValid = *verifyOutput.SignatureValid
return signatureValid, nil
}
// ----------------------------------------------------------------------------------------------------------------
// kms data-key encrypt/decrypt aes 256 functions
// ----------------------------------------------------------------------------------------------------------------
// GenerateDataKeyAes256 will return an encrypted data key generated by kms cmk,
// this data key is encrypted, and able to decrypt only via kms cmk (therefore it is safe to store in memory or at rest)
//
// cipherKey = encrypted data key in hex (must use KMS CMK to decrypt such key)
func (k *KMS) GenerateDataKeyAes256() (cipherKey string, err error) {
var segCtx context.Context
segCtx = nil
seg := xray.NewSegmentNullable("KMS-GenerateDataKeyAes256", k._parentSegment)
if seg != nil {
segCtx = seg.Ctx
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("KMS-GenerateDataKeyAes256-AES-KMS-KeyName", k.AesKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-GenerateDataKeyAes256-Result-CipherKey-Length", len(cipherKey))
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validate
if k.kmsClient == nil {
err = errors.New("GenerateDataKeyAes256 with KMS Failed: " + "KMS Client is Required")
return "", err
}
if len(k.AesKmsKeyName) <= 0 {
err = errors.New("GenerateDataKeyAes256 with KMS Failed: " + "AES KMS Key Name is Required")
return "", err
}
// prepare key info
keyId := "alias/" + k.AesKmsKeyName
keySpec := "AES_256" // always use AES 256
dataKeyInput := kms.GenerateDataKeyWithoutPlaintextInput{
KeyId: aws.String(keyId),
KeySpec: aws.String(keySpec),
}
// generate data key
var dataKeyOutput *kms.GenerateDataKeyWithoutPlaintextOutput
var e error
if segCtx == nil {
dataKeyOutput, e = k.kmsClient.GenerateDataKeyWithoutPlaintext(&dataKeyInput)
} else {
dataKeyOutput, e = k.kmsClient.GenerateDataKeyWithoutPlaintextWithContext(segCtx, &dataKeyInput)
}
if e != nil {
err = errors.New("GenerateDataKeyAes256 with KMS Failed: (Gen Data Key) " + e.Error())
return "", err
}
// return encrypted key via cipherKey
cipherKey = util.ByteToHex(dataKeyOutput.CiphertextBlob)
return cipherKey, nil
}
// EncryptWithDataKeyAes256 will encrypt plainText using cipherKey that was generated via GenerateDataKeyAes256()
//
// cipherKey = encrypted data key in hex (must use KMS CMK to decrypt such key)
func (k *KMS) EncryptWithDataKeyAes256(plainText string, cipherKey string) (cipherText string, err error) {
var segCtx context.Context
segCtx = nil
seg := xray.NewSegmentNullable("KMS-EncryptWithDataKeyAes256", k._parentSegment)
if seg != nil {
segCtx = seg.Ctx
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("KMS-EncryptWithDataKeyAes256-AES-KMS-KeyName", k.AesKmsKeyName)
_ = seg.Seg.AddMetadata("KMS-EncryptWithDataKeyAes256-PlainText-Length", len(plainText))
_ = seg.Seg.AddMetadata("KMS-EncryptWithDataKeyAes256-CipherKey-Length", len(cipherKey))
_ = seg.Seg.AddMetadata("KMS-EncryptWithDataKeyAes256-Result-CipherText-Length", len(cipherText))
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validate
if k.kmsClient == nil {
err = errors.New("EncryptWithDataKeyAes256 with KMS Failed: " + "KMS Client is Required")
return "", err
}
if len(k.AesKmsKeyName) <= 0 {
err = errors.New("EncryptWithDataKeyAes256 with KMS Failed: " + "AES KMS Key Name is Required")
return "", err
}
if len(plainText) <= 0 {
err = errors.New("EncryptWithDataKeyAes256 with KMS Failed: " + "PlainText is Required")
return "", err
}
if len(cipherKey) <= 0 {
err = errors.New("EncryptWithDataKeyAes256 with KMS Failed: " + "CipherKey is Required")
return "", err
}
// prepare key info
keyId := "alias/" + k.AesKmsKeyName
cipherBytes, ce := util.HexToByte(cipherKey)
if ce != nil {
err = errors.New("EncryptWithDataKeyAes256 with KMS Failed: (Unmarshal CipherKey Hex To Byte) " + ce.Error())
return "", err
}
// decrypt cipherKey using kms cmk
var dataKeyOutput *kms.DecryptOutput
var e error
if segCtx == nil {
dataKeyOutput, e = k.kmsClient.Decrypt(&kms.DecryptInput{
EncryptionAlgorithm: aws.String("SYMMETRIC_DEFAULT"),
KeyId: aws.String(keyId),
CiphertextBlob: cipherBytes,
})
} else {
dataKeyOutput, e = k.kmsClient.DecryptWithContext(segCtx,
&kms.DecryptInput{
EncryptionAlgorithm: aws.String("SYMMETRIC_DEFAULT"),
KeyId: aws.String(keyId),
CiphertextBlob: cipherBytes,
})
}
if e != nil {
err = errors.New("EncryptWithDataKeyAes256 with KMS Failed: (Decrypt Data Key) " + e.Error())
return "", err
}
// perform encryption action using decrypted plaintext data key
buf, e := crypto.AesGcmEncrypt(plainText, string(dataKeyOutput.Plaintext))
// clean up data key from memory immediately
dataKeyOutput.SetPlaintext([]byte{})
dataKeyOutput = nil
// evaluate encrypted result
if e != nil {
err = errors.New("EncryptWithDataKeyAes256 with KMS Failed: (Encrypt Data) " + e.Error())
return "", err
} else {
cipherText = buf
}