forked from GoogleCloudPlatform/java-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnippets.java
More file actions
583 lines (462 loc) · 19.8 KB
/
Snippets.java
File metadata and controls
583 lines (462 loc) · 19.8 KB
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
/*
* Copyright 2017 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.
*/
package com.example;
import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState;
import com.google.cloud.kms.v1.CryptoKeyVersionName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyManagementServiceClient.ListCryptoKeyVersionsPagedResponse;
import com.google.cloud.kms.v1.KeyManagementServiceClient.ListCryptoKeysPagedResponse;
import com.google.cloud.kms.v1.KeyManagementServiceClient.ListKeyRingsPagedResponse;
import com.google.cloud.kms.v1.KeyRing;
import com.google.cloud.kms.v1.KeyRingName;
import com.google.cloud.kms.v1.LocationName;
import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
public class Snippets {
// [START kms_create_keyring]
/**
* Creates a new key ring with the given id.
*/
public static KeyRing createKeyRing(String projectId, String locationId, String keyRingId)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the location associated with the KeyRing.
String parent = LocationName.format(projectId, locationId);
// Create the KeyRing for your project.
KeyRing keyRing = client.createKeyRing(parent, keyRingId, KeyRing.newBuilder().build());
return keyRing;
}
}
// [END kms_create_keyring]
// [START kms_create_cryptokey]
/**
* Creates a new crypto key with the given id.
*/
public static CryptoKey createCryptoKey(String projectId, String locationId, String keyRingId,
String cryptoKeyId)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the location associated with the KeyRing.
String parent = KeyRingName.format(projectId, locationId, keyRingId);
// This will allow the API access to the key for encryption and decryption.
CryptoKey cryptoKey = CryptoKey.newBuilder()
.setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
.build();
// Create the CryptoKey for your project.
CryptoKey createdKey = client.createCryptoKey(parent, cryptoKeyId, cryptoKey);
return createdKey;
}
}
// [END kms_create_cryptokey]
// [START kms_create_cryptokey_version]
/**
* Creates a new crypto key version for the given id.
*/
public static CryptoKeyVersion createCryptoKeyVersion(
String projectId, String locationId, String keyRingId, String cryptoKeyId)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey
String cryptoKey = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);
CryptoKeyVersion version = CryptoKeyVersion.newBuilder().build();
CryptoKeyVersion newVersion = client.createCryptoKeyVersion(cryptoKey, version);
return newVersion;
}
}
// [END kms_create_cryptokey_version]
// [START kms_disable_cryptokey_version]
/**
* Disables the given version of the crypto key.
*/
public static CryptoKeyVersion disableCryptoKeyVersion(
String projectId, String locationId, String keyRingId, String cryptoKeyId, String version)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
String versionName = CryptoKeyVersionName.format(
projectId, locationId, keyRingId, cryptoKeyId, version);
// Retrieve the current state
CryptoKeyVersion current = client.getCryptoKeyVersion(versionName);
// Build a copy that updates the state to disabled
CryptoKeyVersion updated = CryptoKeyVersion.newBuilder()
.setName(current.getName())
.setState(CryptoKeyVersionState.DISABLED)
.build();
// Create a FieldMask that only allows 'state' to be updated
FieldMask fieldMask = FieldMaskUtil.fromString(CryptoKeyVersion.class, "state");
// Update the version state
CryptoKeyVersion response = client.updateCryptoKeyVersion(updated, fieldMask);
return response;
}
}
// [END kms_disable_cryptokey_version]
// [START kms_enable_cryptokey_version]
/**
* Enables the given version of the crypto key.
*/
public static CryptoKeyVersion enableCryptoKeyVersion(
String projectId, String locationId, String keyRingId, String cryptoKeyId, String version)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
String versionName = CryptoKeyVersionName.format(
projectId, locationId, keyRingId, cryptoKeyId, version);
// Retrieve the current state
CryptoKeyVersion current = client.getCryptoKeyVersion(versionName);
// Build a copy that updates the state to enabled
CryptoKeyVersion updated = CryptoKeyVersion.newBuilder()
.setName(current.getName())
.setState(CryptoKeyVersionState.ENABLED)
.build();
// Create a FieldMask that only allows 'state' to be updated
FieldMask fieldMask = FieldMaskUtil.fromString(CryptoKeyVersion.class, "state");
// Update the version state
CryptoKeyVersion response = client.updateCryptoKeyVersion(updated, fieldMask);
return response;
}
}
// [END kms_enable_cryptokey_version]
// [START kms_destroy_cryptokey_version]
/**
* Marks the given version of a crypto key to be destroyed at a scheduled future point.
*/
public static CryptoKeyVersion destroyCryptoKeyVersion(
String projectId, String locationId, String keyRingId, String cryptoKeyId, String version)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
String versionName = CryptoKeyVersionName.format(
projectId, locationId, keyRingId, cryptoKeyId, version);
// Destroy the cryptoKey version
CryptoKeyVersion destroyed = client.destroyCryptoKeyVersion(versionName);
return destroyed;
}
}
// [END kms_destroy_cryptokey_version]
// [START kms_restore_cryptokey_version]
/**
* Restores the given version of a crypto key that is currently scheduled for destruction.
*/
public static CryptoKeyVersion restoreCryptoKeyVersion(
String projectId, String locationId, String keyRingId, String cryptoKeyId, String version)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
String versionName = CryptoKeyVersionName.format(
projectId, locationId, keyRingId, cryptoKeyId, version);
CryptoKeyVersion restored = client.restoreCryptoKeyVersion(versionName);
return restored;
}
}
// [END kms_restore_cryptokey_version]
// [START kms_get_cryptokey_policy]
/**
* Retrieves the IAM policy for the given crypto key.
*/
public static Policy getCryptoKeyPolicy(
String projectId, String locationId, String keyRingId, String cryptoKeyId)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
String keyName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);
// Get the current IAM policy and add the new account to it.
Policy iamPolicy = client.getIamPolicy(keyName);
return iamPolicy;
}
}
// [END kms_get_cryptokey_policy]
// [START kms_get_keyring_policy]
/**
* Retrieves the IAM policy for the given crypto key.
*/
public static Policy getKeyRingPolicy(String projectId, String locationId, String keyRingId)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
String keyRingName = KeyRingName.format(projectId, locationId, keyRingId);
// Get the current IAM policy and add the new account to it.
Policy iamPolicy = client.getIamPolicy(keyRingName);
return iamPolicy;
}
}
// [END kms_get_keyring_policy]
// [START kms_add_member_to_cryptokey_policy]
/**
* Adds the given member to the given key, with the given role.
*
* @param projectId The id of the project.
* @param locationId The location id of the key.
* @param keyRingId The id of the keyring.
* @param cryptoKeyId The id of the crypto key.
* @param member The member to add. Must be in the proper format, eg:
*
* allUsers user:$userEmail serviceAccount:$serviceAccountEmail
*
* See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
* @param role Must be in one of the following formats: roles/[role]
* organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
*
* See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
*/
public static Policy addMemberToCryptoKeyPolicy(
String projectId, String locationId, String keyRingId, String cryptoKeyId, String member,
String role)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
String keyName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);
// Get the current IAM policy
Policy iamPolicy = client.getIamPolicy(keyName);
// Create a new binding with the selected role and member
Binding newBinding = Binding.newBuilder()
.setRole(role)
.addMembers(member)
.build();
// Create a new IAM policy containing the existing settings plus the new binding.
Policy newPolicy = Policy.newBuilder()
.mergeFrom(iamPolicy)
.addBindings(newBinding)
.build();
// Set the new IAM Policy.
Policy policyResult = client.setIamPolicy(keyName, newPolicy);
return policyResult;
}
}
// [END kms_add_member_to_cryptokey_policy]
// [START kms_add_member_to_keyring_policy]
/**
* Adds the given member to the given keyring, with the given role.
*
* @param projectId The id of the project.
* @param locationId The location id of the key.
* @param keyRingId The id of the keyring.
* @param member The member to add. Must be in the proper format, eg:
*
* allUsers user:$userEmail serviceAccount:$serviceAccountEmail
*
* See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
* @param role Must be in one of the following formats: roles/[role]
* organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
*
* See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
*/
public static Policy addMemberToKeyRingPolicy(
String projectId, String locationId, String keyRingId, String member, String role)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
String keyRingName = KeyRingName.format(projectId, locationId, keyRingId);
// Get the current IAM policy
Policy iamPolicy = client.getIamPolicy(keyRingName);
// Create a new binding with the selected role and member
Binding newBinding = Binding.newBuilder()
.setRole(role)
.addMembers(member)
.build();
// Create a new IAM policy containing the existing settings plus the new binding.
Policy newPolicy = Policy.newBuilder()
.mergeFrom(iamPolicy)
.addBindings(newBinding)
.build();
// Set the new IAM Policy.
Policy policyResult = client.setIamPolicy(keyRingName, newPolicy);
return policyResult;
}
}
// [END kms_add_member_to_keyring_policy]
// [START kms_remove_member_from_cryptokey_policy]
/**
* Removes the given member from the given policy.
*/
public static Policy removeMemberFromCryptoKeyPolicy(
String projectId, String locationId, String keyRingId, String cryptoKeyId, String member,
String role)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
String keyName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);
// Get the current IAM policy
Policy iamPolicy = client.getIamPolicy(keyName);
// Create a bindings list that filters out the provided member
List<Binding> newBindings = new ArrayList<>();
for (Binding binding : iamPolicy.getBindingsList()) {
if (!binding.getRole().equals(role)) {
newBindings.add(binding);
continue;
}
Binding.Builder builder = Binding.newBuilder().setRole(binding.getRole());
for (String bindingMember : binding.getMembersList()) {
if (!member.equals(bindingMember)) {
builder.addMembers(bindingMember);
}
}
newBindings.add(builder.build());
}
Policy newIamPolicy = Policy.newBuilder()
.addAllBindings(newBindings)
.build();
// Set the new IAM Policy.
Policy result = client.setIamPolicy(keyName, newIamPolicy);
return result;
}
}
// [END kms_remove_member_from_cryptokey_policy]
// [START kms_remove_member_from_keyring_policy]
/**
* Removes the given member from the given policy.
*/
public static Policy removeMemberFromKeyRingPolicy(
String projectId, String locationId, String keyRingId, String member, String role)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
String keyRingName = KeyRingName.format(projectId, locationId, keyRingId);
// Get the current IAM policy
Policy iamPolicy = client.getIamPolicy(keyRingName);
// Create a bindings list that filters out the provided member
List<Binding> newBindings = new ArrayList<>();
for (Binding binding : iamPolicy.getBindingsList()) {
if (!binding.getRole().equals(role)) {
newBindings.add(binding);
} else {
Binding.Builder builder = Binding.newBuilder().setRole(binding.getRole());
for (String bindingMember : binding.getMembersList()) {
if (!member.equals(bindingMember)) {
builder.addMembers(bindingMember);
}
}
newBindings.add(builder.build());
}
}
Policy newIamPolicy = Policy.newBuilder()
.addAllBindings(newBindings)
.build();
// Set the new IAM Policy.
Policy result = client.setIamPolicy(keyRingName, newIamPolicy);
return result;
}
}
// [END kms_remove_member_from_keyring_policy]
/**
* Lists all the key rings in the given project.
*/
public static List<KeyRing> listKeyRings(String projectId, String locationId) throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the location to search.
String parent = LocationName.format(projectId, locationId);
// Retrieve a paginated list of KeyRings
ListKeyRingsPagedResponse response = client.listKeyRings(parent);
ArrayList<KeyRing> results = new ArrayList<>();
// Iterate over all KeyRings (subsequent pages are retrieved automatically)
for (KeyRing keyRing : response.iterateAll()) {
results.add(keyRing);
}
return results;
}
}
/**
* Lists all crypto keys in the given key ring.
*/
public static List<CryptoKey> listCryptoKeys(
String projectId, String locationId, String keyRingId)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the KeyRing to search.
String parent = KeyRingName.format(projectId, locationId, keyRingId);
// Retrieve a paginated list of CryptoKeys
ListCryptoKeysPagedResponse response = client.listCryptoKeys(parent);
ArrayList<CryptoKey> keys = new ArrayList<>();
// Iterate over all CryptoKeys (subsequent pages are retrieved automatically)
for (CryptoKey cryptoKey : response.iterateAll()) {
keys.add(cryptoKey);
}
return keys;
}
}
/**
* Lists all the versions for the given crypto key.
*/
public static List<CryptoKeyVersion> listCryptoKeyVersions(
String projectId, String locationId, String keyRingId, String cryptoKeyId)
throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the CryptoKey to search.
String parent = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);
// Retrieve a paginated list of CryptoKeyVersions
ListCryptoKeyVersionsPagedResponse response = client.listCryptoKeyVersions(parent);
ArrayList<CryptoKeyVersion> results = new ArrayList<>();
// Iterate over all CryptoKeyVersions (subsequent pages are retrieved automatically)
for (CryptoKeyVersion version : response.iterateAll()) {
results.add(version);
}
return results;
}
}
/**
* Sets a version as the primary version for a crypto key.
*/
public static CryptoKey setPrimaryVersion(String projectId, String locationId, String keyRingId,
String cryptoKeyId, String versionId) throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the CryptoKey to update.
String resourceName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);
// Update the primary CryptoKey version
CryptoKey key = client.updateCryptoKeyPrimaryVersion(resourceName, versionId);
return key;
}
}
public static void main(String[] args) throws IOException, CmdLineException {
SnippetCommands commands = new SnippetCommands();
CmdLineParser parser = new CmdLineParser(commands);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.out.println(e);
System.out.println();
e.getParser().printUsage(System.err);
System.exit(1);
}
commands.command.run();
}
}