-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
deid.py
1228 lines (1065 loc) · 40.6 KB
/
deid.py
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
# Copyright 2023 Google LLC
#
# 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.
"""Uses of the Data Loss Prevention API for deidentifying sensitive data."""
from __future__ import print_function
import argparse
# [START dlp_deidentify_masking]
def deidentify_with_mask(
project, input_str, info_types, masking_character=None, number_to_mask=0
):
"""Uses the Data Loss Prevention API to deidentify sensitive data in a
string by masking it with a character.
Args:
project: The Google Cloud project id to use as a parent resource.
input_str: The string to deidentify (will be treated as text).
masking_character: The character to mask matching sensitive data with.
number_to_mask: The maximum number of sensitive characters to mask in
a match. If omitted or set to zero, the API will default to no
maximum.
Returns:
None; the response from the API is printed to the terminal.
"""
# Import the client library
import google.cloud.dlp
# Instantiate a client
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# Construct inspect configuration dictionary
inspect_config = {"info_types": [{"name": info_type} for info_type in info_types]}
# Construct deidentify configuration dictionary
deidentify_config = {
"info_type_transformations": {
"transformations": [
{
"primitive_transformation": {
"character_mask_config": {
"masking_character": masking_character,
"number_to_mask": number_to_mask,
}
}
}
]
}
}
# Construct item
item = {"value": input_str}
# Call the API
response = dlp.deidentify_content(
request={
"parent": parent,
"deidentify_config": deidentify_config,
"inspect_config": inspect_config,
"item": item,
}
)
# Print out the results.
print(response.item.value)
# [END dlp_deidentify_masking]
# [START dlp_deidentify_redact]
def deidentify_with_redact(
project,
input_str,
info_types,
):
"""Uses the Data Loss Prevention API to deidentify sensitive data in a
string by redacting matched input values.
Args:
project: The Google Cloud project id to use as a parent resource.
input_str: The string to deidentify (will be treated as text).
info_types: A list of strings representing info types to look for.
Returns:
None; the response from the API is printed to the terminal.
"""
import google.cloud.dlp
# Instantiate a client
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# Construct inspect configuration dictionary
inspect_config = {"info_types": [{"name": info_type} for info_type in info_types]}
# Construct deidentify configuration dictionary
deidentify_config = {
"info_type_transformations": {
"transformations": [{"primitive_transformation": {"redact_config": {}}}]
}
}
# Construct item
item = {"value": input_str}
# Call the API
response = dlp.deidentify_content(
request={
"parent": parent,
"deidentify_config": deidentify_config,
"inspect_config": inspect_config,
"item": item,
}
)
# Print out the results.
print(response.item.value)
# [END dlp_deidentify_redact]
# [START dlp_deidentify_replace]
def deidentify_with_replace(
project,
input_str,
info_types,
replacement_str="REPLACEMENT_STR",
):
"""Uses the Data Loss Prevention API to deidentify sensitive data in a
string by replacing matched input values with a value you specify.
Args:
project: The Google Cloud project id to use as a parent resource.
input_str: The string to deidentify (will be treated as text).
info_types: A list of strings representing info types to look for.
replacement_str: The string to replace all values that match given
info types.
Returns:
None; the response from the API is printed to the terminal.
"""
import google.cloud.dlp
# Instantiate a client
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# Construct inspect configuration dictionary
inspect_config = {"info_types": [{"name": info_type} for info_type in info_types]}
# Construct deidentify configuration dictionary
deidentify_config = {
"info_type_transformations": {
"transformations": [
{
"primitive_transformation": {
"replace_config": {
"new_value": {"string_value": replacement_str}
}
}
}
]
}
}
# Construct item
item = {"value": input_str}
# Call the API
response = dlp.deidentify_content(
request={
"parent": parent,
"deidentify_config": deidentify_config,
"inspect_config": inspect_config,
"item": item,
}
)
# Print out the results.
print(response.item.value)
# [END dlp_deidentify_replace]
# [START dlp_deidentify_fpe]
def deidentify_with_fpe(
project,
input_str,
info_types,
alphabet=None,
surrogate_type=None,
key_name=None,
wrapped_key=None,
):
"""Uses the Data Loss Prevention API to deidentify sensitive data in a
string using Format Preserving Encryption (FPE).
Args:
project: The Google Cloud project id to use as a parent resource.
input_str: The string to deidentify (will be treated as text).
alphabet: The set of characters to replace sensitive ones with. For
more information, see https://cloud.google.com/dlp/docs/reference/
rest/v2beta2/organizations.deidentifyTemplates#ffxcommonnativealphabet
surrogate_type: The name of the surrogate custom info type to use. Only
necessary if you want to reverse the deidentification process. Can
be essentially any arbitrary string, as long as it doesn't appear
in your dataset otherwise.
key_name: The name of the Cloud KMS key used to encrypt ('wrap') the
AES-256 key. Example:
key_name = 'projects/YOUR_GCLOUD_PROJECT/locations/YOUR_LOCATION/
keyRings/YOUR_KEYRING_NAME/cryptoKeys/YOUR_KEY_NAME'
wrapped_key: The encrypted ('wrapped') AES-256 key to use. This key
should be encrypted using the Cloud KMS key specified by key_name.
Returns:
None; the response from the API is printed to the terminal.
"""
# Import the client library
import google.cloud.dlp
# Instantiate a client
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# The wrapped key is base64-encoded, but the library expects a binary
# string, so decode it here.
import base64
wrapped_key = base64.b64decode(wrapped_key)
# Construct FPE configuration dictionary
crypto_replace_ffx_fpe_config = {
"crypto_key": {
"kms_wrapped": {"wrapped_key": wrapped_key, "crypto_key_name": key_name}
},
"common_alphabet": alphabet,
}
# Add surrogate type
if surrogate_type:
crypto_replace_ffx_fpe_config["surrogate_info_type"] = {"name": surrogate_type}
# Construct inspect configuration dictionary
inspect_config = {"info_types": [{"name": info_type} for info_type in info_types]}
# Construct deidentify configuration dictionary
deidentify_config = {
"info_type_transformations": {
"transformations": [
{
"primitive_transformation": {
"crypto_replace_ffx_fpe_config": crypto_replace_ffx_fpe_config
}
}
]
}
}
# Convert string to item
item = {"value": input_str}
# Call the API
response = dlp.deidentify_content(
request={
"parent": parent,
"deidentify_config": deidentify_config,
"inspect_config": inspect_config,
"item": item,
}
)
# Print results
print(response.item.value)
# [END dlp_deidentify_fpe]
# [START dlp_deidentify_deterministic]
def deidentify_with_deterministic(
project,
input_str,
info_types,
surrogate_type=None,
key_name=None,
wrapped_key=None,
):
"""Deidentifies sensitive data in a string using deterministic encryption.
Args:
project: The Google Cloud project id to use as a parent resource.
input_str: The string to deidentify (will be treated as text).
surrogate_type: The name of the surrogate custom info type to use. Only
necessary if you want to reverse the deidentification process. Can
be essentially any arbitrary string, as long as it doesn't appear
in your dataset otherwise.
key_name: The name of the Cloud KMS key used to encrypt ('wrap') the
AES-256 key. Example:
key_name = 'projects/YOUR_GCLOUD_PROJECT/locations/YOUR_LOCATION/
keyRings/YOUR_KEYRING_NAME/cryptoKeys/YOUR_KEY_NAME'
wrapped_key: The encrypted ('wrapped') AES-256 key to use. This key
should be encrypted using the Cloud KMS key specified by key_name.
Returns:
None; the response from the API is printed to the terminal.
"""
import base64
# Import the client library
import google.cloud.dlp
# Instantiate a client
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# The wrapped key is base64-encoded, but the library expects a binary
# string, so decode it here.
wrapped_key = base64.b64decode(wrapped_key)
# Construct Deterministic encryption configuration dictionary
crypto_replace_deterministic_config = {
"crypto_key": {
"kms_wrapped": {"wrapped_key": wrapped_key, "crypto_key_name": key_name}
},
}
# Add surrogate type
if surrogate_type:
crypto_replace_deterministic_config["surrogate_info_type"] = {
"name": surrogate_type
}
# Construct inspect configuration dictionary
inspect_config = {"info_types": [{"name": info_type} for info_type in info_types]}
# Construct deidentify configuration dictionary
deidentify_config = {
"info_type_transformations": {
"transformations": [
{
"primitive_transformation": {
"crypto_deterministic_config": crypto_replace_deterministic_config
}
}
]
}
}
# Convert string to item
item = {"value": input_str}
# Call the API
response = dlp.deidentify_content(
request={
"parent": parent,
"deidentify_config": deidentify_config,
"inspect_config": inspect_config,
"item": item,
}
)
# Print results
print(response.item.value)
# [END dlp_deidentify_deterministic]
# [START dlp_reidentify_fpe]
def reidentify_with_fpe(
project,
input_str,
alphabet=None,
surrogate_type=None,
key_name=None,
wrapped_key=None,
):
"""Uses the Data Loss Prevention API to reidentify sensitive data in a
string that was encrypted by Format Preserving Encryption (FPE).
Args:
project: The Google Cloud project id to use as a parent resource.
input_str: The string to deidentify (will be treated as text).
alphabet: The set of characters to replace sensitive ones with. For
more information, see https://cloud.google.com/dlp/docs/reference/
rest/v2beta2/organizations.deidentifyTemplates#ffxcommonnativealphabet
surrogate_type: The name of the surrogate custom info type to used
during the encryption process.
key_name: The name of the Cloud KMS key used to encrypt ('wrap') the
AES-256 key. Example:
keyName = 'projects/YOUR_GCLOUD_PROJECT/locations/YOUR_LOCATION/
keyRings/YOUR_KEYRING_NAME/cryptoKeys/YOUR_KEY_NAME'
wrapped_key: The encrypted ('wrapped') AES-256 key to use. This key
should be encrypted using the Cloud KMS key specified by key_name.
Returns:
None; the response from the API is printed to the terminal.
"""
# Import the client library
import google.cloud.dlp
# Instantiate a client
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# The wrapped key is base64-encoded, but the library expects a binary
# string, so decode it here.
import base64
wrapped_key = base64.b64decode(wrapped_key)
# Construct Deidentify Config
reidentify_config = {
"info_type_transformations": {
"transformations": [
{
"primitive_transformation": {
"crypto_replace_ffx_fpe_config": {
"crypto_key": {
"kms_wrapped": {
"wrapped_key": wrapped_key,
"crypto_key_name": key_name,
}
},
"common_alphabet": alphabet,
"surrogate_info_type": {"name": surrogate_type},
}
}
}
]
}
}
inspect_config = {
"custom_info_types": [
{"info_type": {"name": surrogate_type}, "surrogate_type": {}}
]
}
# Convert string to item
item = {"value": input_str}
# Call the API
response = dlp.reidentify_content(
request={
"parent": parent,
"reidentify_config": reidentify_config,
"inspect_config": inspect_config,
"item": item,
}
)
# Print results
print(response.item.value)
# [END dlp_reidentify_fpe]
# [START dlp_reidentify_deterministic]
def reidentify_with_deterministic(
project,
input_str,
surrogate_type=None,
key_name=None,
wrapped_key=None,
):
"""Re-identifies content that was previously de-identified through deterministic encryption.
Args:
project: The Google Cloud project ID to use as a parent resource.
input_str: The string to be re-identified. Provide the entire token. Example:
EMAIL_ADDRESS_TOKEN(52):AVAx2eIEnIQP5jbNEr2j9wLOAd5m4kpSBR/0jjjGdAOmryzZbE/q
surrogate_type: The name of the surrogate custom infoType used
during the encryption process.
key_name: The name of the Cloud KMS key used to encrypt ("wrap") the
AES-256 key. Example:
keyName = 'projects/YOUR_GCLOUD_PROJECT/locations/YOUR_LOCATION/
keyRings/YOUR_KEYRING_NAME/cryptoKeys/YOUR_KEY_NAME'
wrapped_key: The encrypted ("wrapped") AES-256 key previously used to encrypt the content.
This key must have been encrypted using the Cloud KMS key specified by key_name.
Returns:
None; the response from the API is printed to the terminal.
"""
import base64
# Import the client library
import google.cloud.dlp
# Instantiate a client
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# The wrapped key is base64-encoded, but the library expects a binary
# string, so decode it here.
wrapped_key = base64.b64decode(wrapped_key)
# Construct reidentify Configuration
reidentify_config = {
"info_type_transformations": {
"transformations": [
{
"primitive_transformation": {
"crypto_deterministic_config": {
"crypto_key": {
"kms_wrapped": {
"wrapped_key": wrapped_key,
"crypto_key_name": key_name,
}
},
"surrogate_info_type": {"name": surrogate_type},
}
}
}
]
}
}
inspect_config = {
"custom_info_types": [
{"info_type": {"name": surrogate_type}, "surrogate_type": {}}
]
}
# Convert string to item
item = {"value": input_str}
# Call the API
response = dlp.reidentify_content(
request={
"parent": parent,
"reidentify_config": reidentify_config,
"inspect_config": inspect_config,
"item": item,
}
)
# Print results
print(response.item.value)
# [END dlp_reidentify_deterministic]
# [START dlp_deidentify_free_text_with_fpe_using_surrogate]
def deidentify_free_text_with_fpe_using_surrogate(
project,
input_str,
alphabet="NUMERIC",
info_type="PHONE_NUMBER",
surrogate_type="PHONE_TOKEN",
unwrapped_key="YWJjZGVmZ2hpamtsbW5vcA==",
):
"""Uses the Data Loss Prevention API to deidentify sensitive data in a
string using Format Preserving Encryption (FPE).
The encryption is performed with an unwrapped key.
Args:
project: The Google Cloud project id to use as a parent resource.
input_str: The string to deidentify (will be treated as text).
alphabet: The set of characters to replace sensitive ones with. For
more information, see https://cloud.google.com/dlp/docs/reference/
rest/v2beta2/organizations.deidentifyTemplates#ffxcommonnativealphabet
info_type: The name of the info type to de-identify
surrogate_type: The name of the surrogate custom info type to use. Can
be essentially any arbitrary string, as long as it doesn't appear
in your dataset otherwise.
unwrapped_key: The base64-encoded AES-256 key to use.
Returns:
None; the response from the API is printed to the terminal.
"""
# Import the client library
import google.cloud.dlp
# Instantiate a client
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# The unwrapped key is base64-encoded, but the library expects a binary
# string, so decode it here.
import base64
unwrapped_key = base64.b64decode(unwrapped_key)
# Construct de-identify config
transformation = {
"info_types": [{"name": info_type}],
"primitive_transformation": {
"crypto_replace_ffx_fpe_config": {
"crypto_key": {"unwrapped": {"key": unwrapped_key}},
"common_alphabet": alphabet,
"surrogate_info_type": {"name": surrogate_type},
}
},
}
deidentify_config = {
"info_type_transformations": {"transformations": [transformation]}
}
# Construct the inspect config, trying to finding all PII with likelihood
# higher than UNLIKELY
inspect_config = {
"info_types": [{"name": info_type}],
"min_likelihood": google.cloud.dlp_v2.Likelihood.UNLIKELY,
}
# Convert string to item
item = {"value": input_str}
# Call the API
response = dlp.deidentify_content(
request={
"parent": parent,
"deidentify_config": deidentify_config,
"inspect_config": inspect_config,
"item": item,
}
)
# Print results
print(response.item.value)
# [END dlp_deidentify_free_text_with_fpe_using_surrogate]
# [START dlp_reidentify_free_text_with_fpe_using_surrogate]
def reidentify_free_text_with_fpe_using_surrogate(
project,
input_str,
alphabet="NUMERIC",
surrogate_type="PHONE_TOKEN",
unwrapped_key="YWJjZGVmZ2hpamtsbW5vcA==",
):
"""Uses the Data Loss Prevention API to reidentify sensitive data in a
string that was encrypted by Format Preserving Encryption (FPE) with
surrogate type. The encryption is performed with an unwrapped key.
Args:
project: The Google Cloud project id to use as a parent resource.
input_str: The string to deidentify (will be treated as text).
alphabet: The set of characters to replace sensitive ones with. For
more information, see https://cloud.google.com/dlp/docs/reference/
rest/v2beta2/organizations.deidentifyTemplates#ffxcommonnativealphabet
surrogate_type: The name of the surrogate custom info type to used
during the encryption process.
unwrapped_key: The base64-encoded AES-256 key to use.
Returns:
None; the response from the API is printed to the terminal.
"""
# Import the client library
import google.cloud.dlp
# Instantiate a client
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# The unwrapped key is base64-encoded, but the library expects a binary
# string, so decode it here.
import base64
unwrapped_key = base64.b64decode(unwrapped_key)
# Construct Deidentify Config
transformation = {
"primitive_transformation": {
"crypto_replace_ffx_fpe_config": {
"crypto_key": {"unwrapped": {"key": unwrapped_key}},
"common_alphabet": alphabet,
"surrogate_info_type": {"name": surrogate_type},
}
}
}
reidentify_config = {
"info_type_transformations": {"transformations": [transformation]}
}
inspect_config = {
"custom_info_types": [
{"info_type": {"name": surrogate_type}, "surrogate_type": {}}
]
}
# Convert string to item
item = {"value": input_str}
# Call the API
response = dlp.reidentify_content(
request={
"parent": parent,
"reidentify_config": reidentify_config,
"inspect_config": inspect_config,
"item": item,
}
)
# Print results
print(response.item.value)
# [END dlp_reidentify_free_text_with_fpe_using_surrogate]
# [START dlp_deidentify_date_shift]
def deidentify_with_date_shift(
project,
input_csv_file=None,
output_csv_file=None,
date_fields=None,
lower_bound_days=None,
upper_bound_days=None,
context_field_id=None,
wrapped_key=None,
key_name=None,
):
"""Uses the Data Loss Prevention API to deidentify dates in a CSV file by
pseudorandomly shifting them.
Args:
project: The Google Cloud project id to use as a parent resource.
input_csv_file: The path to the CSV file to deidentify. The first row
of the file must specify column names, and all other rows must
contain valid values.
output_csv_file: The path to save the date-shifted CSV file.
date_fields: The list of (date) fields in the CSV file to date shift.
Example: ['birth_date', 'register_date']
lower_bound_days: The maximum number of days to shift a date backward
upper_bound_days: The maximum number of days to shift a date forward
context_field_id: (Optional) The column to determine date shift amount
based on. If this is not specified, a random shift amount will be
used for every row. If this is specified, then 'wrappedKey' and
'keyName' must also be set. Example:
contextFieldId = [{ 'name': 'user_id' }]
key_name: (Optional) The name of the Cloud KMS key used to encrypt
('wrap') the AES-256 key. Example:
key_name = 'projects/YOUR_GCLOUD_PROJECT/locations/YOUR_LOCATION/
keyRings/YOUR_KEYRING_NAME/cryptoKeys/YOUR_KEY_NAME'
wrapped_key: (Optional) The encrypted ('wrapped') AES-256 key to use.
This key should be encrypted using the Cloud KMS key specified by
key_name.
Returns:
None; the response from the API is printed to the terminal.
"""
# Import the client library
import google.cloud.dlp
# Instantiate a client
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# Convert date field list to Protobuf type
def map_fields(field):
return {"name": field}
if date_fields:
date_fields = map(map_fields, date_fields)
else:
date_fields = []
# Read and parse the CSV file
import csv
from datetime import datetime
f = []
with open(input_csv_file, "r") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
f.append(row)
# Helper function for converting CSV rows to Protobuf types
def map_headers(header):
return {"name": header}
def map_data(value):
try:
date = datetime.strptime(value, "%m/%d/%Y")
return {
"date_value": {"year": date.year, "month": date.month, "day": date.day}
}
except ValueError:
return {"string_value": value}
def map_rows(row):
return {"values": map(map_data, row)}
# Using the helper functions, convert CSV rows to protobuf-compatible
# dictionaries.
csv_headers = map(map_headers, f[0])
csv_rows = map(map_rows, f[1:])
# Construct the table dict
table_item = {"table": {"headers": csv_headers, "rows": csv_rows}}
# Construct date shift config
date_shift_config = {
"lower_bound_days": lower_bound_days,
"upper_bound_days": upper_bound_days,
}
# If using a Cloud KMS key, add it to the date_shift_config.
# The wrapped key is base64-encoded, but the library expects a binary
# string, so decode it here.
if context_field_id and key_name and wrapped_key:
import base64
date_shift_config["context"] = {"name": context_field_id}
date_shift_config["crypto_key"] = {
"kms_wrapped": {
"wrapped_key": base64.b64decode(wrapped_key),
"crypto_key_name": key_name,
}
}
elif context_field_id or key_name or wrapped_key:
raise ValueError(
"""You must set either ALL or NONE of
[context_field_id, key_name, wrapped_key]!"""
)
# Construct Deidentify Config
deidentify_config = {
"record_transformations": {
"field_transformations": [
{
"fields": date_fields,
"primitive_transformation": {
"date_shift_config": date_shift_config
},
}
]
}
}
# Write to CSV helper methods
def write_header(header):
return header.name
def write_data(data):
return data.string_value or "%s/%s/%s" % (
data.date_value.month,
data.date_value.day,
data.date_value.year,
)
# Call the API
response = dlp.deidentify_content(
request={
"parent": parent,
"deidentify_config": deidentify_config,
"item": table_item,
}
)
# Write results to CSV file
with open(output_csv_file, "w") as csvfile:
write_file = csv.writer(csvfile, delimiter=",")
write_file.writerow(map(write_header, response.item.table.headers))
for row in response.item.table.rows:
write_file.writerow(map(write_data, row.values))
# Print status
print("Successfully saved date-shift output to {}".format(output_csv_file))
# [END dlp_deidentify_date_shift]
# [START dlp_deidentify_replace_infotype]
def deidentify_with_replace_infotype(project, item, info_types):
"""Uses the Data Loss Prevention API to deidentify sensitive data in a
string by replacing it with the info type.
Args:
project: The Google Cloud project id to use as a parent resource.
item: The string to deidentify (will be treated as text).
info_types: A list of strings representing info types to look for.
A full list of info type categories can be fetched from the API.
Returns:
None; the response from the API is printed to the terminal.
"""
# Import the client library
import google.cloud.dlp
# Instantiate a client
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# Construct inspect configuration dictionary
inspect_config = {"info_types": [{"name": info_type} for info_type in info_types]}
# Construct deidentify configuration dictionary
deidentify_config = {
"info_type_transformations": {
"transformations": [
{"primitive_transformation": {"replace_with_info_type_config": {}}}
]
}
}
# Call the API
response = dlp.deidentify_content(
request={
"parent": parent,
"deidentify_config": deidentify_config,
"inspect_config": inspect_config,
"item": {"value": item},
}
)
# Print out the results.
print(response.item.value)
# [END dlp_deidentify_replace_infotype]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(
dest="content", help="Select how to submit content to the API."
)
subparsers.required = True
mask_parser = subparsers.add_parser(
"deid_mask",
help="Deidentify sensitive data in a string by masking it with a " "character.",
)
mask_parser.add_argument(
"--info_types",
nargs="+",
help="Strings representing info types to look for. A full list of "
"info categories and types is available from the API. Examples "
'include "FIRST_NAME", "LAST_NAME", "EMAIL_ADDRESS". '
"If unspecified, the three above examples will be used.",
default=["FIRST_NAME", "LAST_NAME", "EMAIL_ADDRESS"],
)
mask_parser.add_argument(
"project",
help="The Google Cloud project id to use as a parent resource.",
)
mask_parser.add_argument("item", help="The string to deidentify.")
mask_parser.add_argument(
"-n",
"--number_to_mask",
type=int,
default=0,
help="The maximum number of sensitive characters to mask in a match. "
"If omitted the request or set to 0, the API will mask any mathcing "
"characters.",
)
mask_parser.add_argument(
"-m",
"--masking_character",
help="The character to mask matching sensitive data with.",
)
replace_parser = subparsers.add_parser(
"deid_replace",
help="Deidentify sensitive data in a string by replacing it with "
"another string.",
)
replace_parser.add_argument(
"--info_types",
nargs="+",
help="Strings representing info types to look for. A full list of "
"info categories and types is available from the API. Examples "
'include "FIRST_NAME", "LAST_NAME", "EMAIL_ADDRESS". '
"If unspecified, the three above examples will be used.",
default=["FIRST_NAME", "LAST_NAME", "EMAIL_ADDRESS"],
)
replace_parser.add_argument(
"project",
help="The Google Cloud project id to use as a parent resource.",
)
replace_parser.add_argument("item", help="The string to deidentify.")
replace_parser.add_argument(
"replacement_str", help="The string to " "replace all matched values with."