-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathKMSEncryptedNestedValueProvider.java
More file actions
118 lines (100 loc) · 4.36 KB
/
KMSEncryptedNestedValueProvider.java
File metadata and controls
118 lines (100 loc) · 4.36 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
/*
* Copyright (C) 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. SecondTou 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 ANSecondT KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package util;
import com.google.cloud.kms.v1.DecryptResponse;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.ByteString;
import org.apache.beam.sdk.options.ValueProvider;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Base64;
import java.util.regex.Pattern;
/**
* {@link KMSEncryptedNestedValueProvider} is a subclass of {@link DualInputNestedValueProvider}
* that allows for taking two {@link ValueProvider} objects - one as an encrypted string and the
* other as a KMS encryption key. If no encryption key is passed, the string is returned, else
* the encryption key is used to decrypt the encrypted string.
*/
public class KMSEncryptedNestedValueProvider
extends DualInputNestedValueProvider<String, String, String> {
private static final Pattern KEYNAME_PATTERN =
Pattern.compile(
"projects/([^/]+)/locations/([a-zA-Z0-9_-]{1,63})/keyRings/"
+ "[a-zA-Z0-9_-]{1,63}/cryptoKeys/[a-zA-Z0-9_-]{1,63}");
/** The log to output status messages to. */
private static final Logger LOG = LoggerFactory.getLogger(KMSEncryptedNestedValueProvider.class);
private static class KmsTranslatorInput
implements SerializableFunction<TranslatorInput<String, String>, String> {
private KmsTranslatorInput() {}
public static KmsTranslatorInput of() {
return new KmsTranslatorInput();
}
@Override
public String apply(TranslatorInput<String, String> input) {
String decrypted;
String unencrypted;
String kmsKey;
unencrypted = input.getX();
kmsKey = input.getY();
if (kmsKey == null || unencrypted.isEmpty()) {
LOG.info("KMS Key is not specified. Using: " + unencrypted);
return unencrypted;
} else if (!testkmsKey(kmsKey)) {
IllegalArgumentException exception =
new IllegalArgumentException("Provided KMS Key %s is invalid");
throw new RuntimeException(exception);
} else {
try {
decrypted = decryptWithKMS(unencrypted /*value*/, kmsKey /*key*/);
} catch (IOException e) {
throw new RuntimeException(e);
}
return decrypted;
}
}
}
/** Creates a {@link KMSEncryptedNestedValueProvider} that wraps
* the key and the encrypted value.
*/
public KMSEncryptedNestedValueProvider(ValueProvider<String> value, ValueProvider<String> key) {
super(value, key, KmsTranslatorInput.of());
}
private static boolean testkmsKey(String kmsKey) {
return KEYNAME_PATTERN.matcher(kmsKey).matches();
}
/** Uses the GCP KMS client to decrypt an encrypted value using a KMS key of the form
* projects/{gcp_project}/locations/{key_region}/keyRings/{key_ring}/cryptoKeys/{kms_key_name}
* The encrypted value should be a base64 encrypted string which has been encrypted using
* the KMS encrypt API call.
* See <a href="https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys/encrypt">
* this KMS API Encrypt Link</a>.
*/
private static String decryptWithKMS(String encryptedValue, String kmsKey) throws IOException {
/*
kmsKey should be in the following format:
projects/{gcp_project}/locations/{key_region}/keyRings/{key_ring}/cryptoKeys/{kms_key_name}
*/
byte[] cipherText = Base64.getDecoder().decode(encryptedValue.getBytes("UTF-8"));
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// Decrypt the ciphertext with Cloud KMS.
DecryptResponse response = client.decrypt(kmsKey, ByteString.copyFrom(cipherText));
// Extract the plaintext from the response.
return new String(response.getPlaintext().toByteArray());
}
}
}