Skip to content

Commit 44bc9de

Browse files
author
Jerjou Cheng
committed
KMS samples.
1 parent 5440235 commit 44bc9de

File tree

5 files changed

+845
-0
lines changed

5 files changed

+845
-0
lines changed

kms/README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Cloud Key Management Service
2+
3+
Google [Cloud Key Management Service](https://cloud.google.com/kms/) is a
4+
cloud-hosted key management service that lets you manage encryption for your
5+
cloud services the same way you do on-premise. You can generate, use, rotate and
6+
destroy AES256 encryption keys. These sample Java applications demonstrate
7+
how to access the KMS API using the Google Java API Client Libraries.
8+
9+
## Quickstart
10+
11+
Install [Maven](http://maven.apache.org/).
12+
13+
Build your project with:
14+
15+
mvn clean compile assembly:single
16+
17+
You can run the quickstart with:
18+
19+
java -cp target/kms-samples-1.0.0-jar-with-dependencies.jar \
20+
com.example.Quickstart [your-project-id]

kms/pom.xml

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>com.google.cloud.kms.samples</groupId>
5+
<artifactId>kms-samples</artifactId>
6+
<packaging>jar</packaging>
7+
8+
<parent>
9+
<artifactId>doc-samples</artifactId>
10+
<groupId>com.google.cloud</groupId>
11+
<version>1.0.0</version>
12+
<relativePath>..</relativePath>
13+
</parent>
14+
15+
<dependencies>
16+
<dependency>
17+
<groupId>com.google.apis</groupId>
18+
<artifactId>google-api-services-cloudkms</artifactId>
19+
<version>v1beta1-rev51-1.18.0-rc</version>
20+
<!--exclusions>
21+
<exclusion> <!- exclude an old version of Guava ->
22+
<groupId>com.google.guava</groupId>
23+
<artifactId>guava-jdk5</artifactId>
24+
</exclusion>
25+
</exclusions-->
26+
</dependency>
27+
<dependency>
28+
<groupId>com.google.api-client</groupId>
29+
<artifactId>google-api-client</artifactId>
30+
<version>1.22.0</version>
31+
</dependency>
32+
<dependency>
33+
<groupId>com.google.http-client</groupId>
34+
<artifactId>google-http-client-jackson2</artifactId>
35+
<version>1.22.0</version>
36+
</dependency>
37+
<dependency>
38+
<groupId>args4j</groupId>
39+
<artifactId>args4j</artifactId>
40+
<version>2.33</version>
41+
</dependency>
42+
43+
<!-- test dependencies -->
44+
<dependency>
45+
<groupId>junit</groupId>
46+
<artifactId>junit</artifactId>
47+
<version>4.12</version>
48+
<scope>test</scope>
49+
</dependency>
50+
<dependency>
51+
<groupId>com.google.truth</groupId>
52+
<artifactId>truth</artifactId>
53+
<version>0.31</version>
54+
<scope>test</scope>
55+
</dependency>
56+
</dependencies>
57+
58+
<properties>
59+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
60+
</properties>
61+
62+
<build>
63+
<sourceDirectory>src/main/java</sourceDirectory>
64+
<resources>
65+
<resource>
66+
<directory>src/main/resources</directory>
67+
</resource>
68+
</resources>
69+
<plugins>
70+
<plugin>
71+
<groupId>org.apache.maven.plugins</groupId>
72+
<artifactId>maven-compiler-plugin</artifactId>
73+
<version>3.2</version>
74+
<configuration>
75+
<source>5</source>
76+
<target>5</target>
77+
</configuration>
78+
</plugin>
79+
<plugin>
80+
<artifactId>maven-assembly-plugin</artifactId>
81+
<configuration>
82+
<descriptorRefs>
83+
<descriptorRef>jar-with-dependencies</descriptorRef>
84+
</descriptorRefs>
85+
</configuration>
86+
</plugin>
87+
</plugins>
88+
</build>
89+
90+
</project>
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
/*
2+
* Copyright (c) 2017 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
15+
package com.example;
16+
17+
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
18+
import com.google.api.client.http.HttpTransport;
19+
import com.google.api.client.http.javanet.NetHttpTransport;
20+
import com.google.api.client.json.JsonFactory;
21+
import com.google.api.client.json.jackson2.JacksonFactory;
22+
import com.google.api.services.cloudkms.v1beta1.CloudKMS;
23+
import com.google.api.services.cloudkms.v1beta1.CloudKMSScopes;
24+
import com.google.api.services.cloudkms.v1beta1.model.DecryptRequest;
25+
import com.google.api.services.cloudkms.v1beta1.model.DecryptResponse;
26+
import com.google.api.services.cloudkms.v1beta1.model.EncryptRequest;
27+
import com.google.api.services.cloudkms.v1beta1.model.EncryptResponse;
28+
29+
import java.io.FileOutputStream;
30+
import java.io.IOException;
31+
import java.nio.file.Files;
32+
import java.nio.file.Paths;
33+
34+
public class CryptFile {
35+
36+
String projectId;
37+
38+
public CryptFile(String projectId) {
39+
this.projectId = projectId;
40+
}
41+
42+
/**
43+
* Creates an authorized CloudKMS client service using Application Default Credentials.
44+
*
45+
* @return an authorized CloudKMS client
46+
* @throws IOException if there's an error getting the default credentials.
47+
*/
48+
public static CloudKMS createAuthorizedClient() throws IOException {
49+
// Create the credential
50+
HttpTransport transport = new NetHttpTransport();
51+
JsonFactory jsonFactory = new JacksonFactory();
52+
// Authorize the client using Application Default Credentials
53+
// @see https://g.co/dv/identity/protocols/application-default-credentials
54+
GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
55+
56+
// Depending on the environment that provides the default credentials (e.g. Compute Engine, App
57+
// Engine), the credentials may require us to specify the scopes we need explicitly.
58+
// Check for this case, and inject the scope if required.
59+
if (credential.createScopedRequired()) {
60+
credential = credential.createScoped(CloudKMSScopes.all());
61+
}
62+
63+
return new CloudKMS.Builder(transport, jsonFactory, credential)
64+
.setApplicationName("CloudKMS CryptFile")
65+
.build();
66+
}
67+
68+
/**
69+
* Encrypts the given bytes, using the specified crypto key.
70+
*/
71+
public byte[] encrypt(String ringId, String keyId, byte[] plaintext)
72+
throws IOException {
73+
String location = "global";
74+
// The resource name of the cryptoKey
75+
String cryptoKeyName = String.format(
76+
"projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
77+
projectId, location, ringId, keyId);
78+
// Create the Cloud KMS client.
79+
CloudKMS kms = createAuthorizedClient();
80+
81+
EncryptRequest request = new EncryptRequest().encodePlaintext(plaintext);
82+
EncryptResponse response = kms.projects().locations().keyRings().cryptoKeys()
83+
.encrypt(cryptoKeyName, request)
84+
.execute();
85+
86+
return response.decodeCiphertext();
87+
}
88+
89+
/**
90+
* Decrypts the given encrypted bytes, using the specified crypto key.
91+
*/
92+
public byte[] decrypt(String ringId, String keyId, byte[] encrypted)
93+
throws IOException {
94+
String location = "global";
95+
// Create the Cloud KMS client.
96+
CloudKMS kms = createAuthorizedClient();
97+
98+
// The resource name of the cryptoKey
99+
String cryptoKeyName = String.format(
100+
"projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
101+
projectId, location, ringId, keyId);
102+
103+
DecryptRequest request = new DecryptRequest().encodeCiphertext(encrypted);
104+
DecryptResponse response = kms.projects().locations().keyRings().cryptoKeys()
105+
.decrypt(cryptoKeyName, request)
106+
.execute();
107+
108+
return response.decodePlaintext();
109+
}
110+
111+
public static void main(String[] args) throws IOException {
112+
// Your Google Cloud Platform project ID
113+
String projectId = args[0];
114+
String command = args[1];
115+
116+
CryptFile cryptFile = new CryptFile(projectId);
117+
118+
if ("encrypt".equals(command)) {
119+
String ringId = args[2];
120+
String keyId = args[3];
121+
String inFile = args[4];
122+
String outFile = args[5];
123+
124+
byte[] encrypted = cryptFile.encrypt(
125+
ringId, keyId,
126+
Files.readAllBytes(Paths.get(inFile)));
127+
128+
FileOutputStream stream = new FileOutputStream(outFile);
129+
try {
130+
stream.write(encrypted);
131+
} finally {
132+
stream.close();
133+
}
134+
135+
} else if ("decrypt".equals(command)) {
136+
String ringId = args[2];
137+
String keyId = args[3];
138+
String inFile = args[4];
139+
String outFile = args[5];
140+
141+
byte[] decrypted = cryptFile.decrypt(
142+
ringId, keyId,
143+
Files.readAllBytes(Paths.get(inFile)));
144+
145+
FileOutputStream stream = new FileOutputStream(outFile);
146+
try {
147+
stream.write(decrypted);
148+
} finally {
149+
stream.close();
150+
}
151+
152+
} else {
153+
throw new RuntimeException("Unrecognized command: " + command);
154+
}
155+
}
156+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
* Copyright (c) 2017 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
15+
package com.example;
16+
17+
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
18+
import com.google.api.client.http.HttpTransport;
19+
import com.google.api.client.http.javanet.NetHttpTransport;
20+
import com.google.api.client.json.JsonFactory;
21+
import com.google.api.client.json.jackson2.JacksonFactory;
22+
import com.google.api.services.cloudkms.v1beta1.CloudKMS;
23+
import com.google.api.services.cloudkms.v1beta1.CloudKMSScopes;
24+
import com.google.api.services.cloudkms.v1beta1.model.KeyRing;
25+
import com.google.api.services.cloudkms.v1beta1.model.ListKeyRingsResponse;
26+
27+
import java.io.IOException;
28+
29+
// [START kms_quickstart]
30+
public class Quickstart {
31+
/**
32+
* Creates an authorized CloudKMS client service using Application Default Credentials.
33+
*
34+
* @return an authorized CloudKMS client
35+
* @throws IOException if there's an error getting the default credentials.
36+
*/
37+
public static CloudKMS createAuthorizedClient() throws IOException {
38+
// Create the credential
39+
HttpTransport transport = new NetHttpTransport();
40+
JsonFactory jsonFactory = new JacksonFactory();
41+
// Authorize the client using Application Default Credentials
42+
// @see https://g.co/dv/identity/protocols/application-default-credentials
43+
GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
44+
45+
// Depending on the environment that provides the default credentials (e.g. Compute Engine, App
46+
// Engine), the credentials may require us to specify the scopes we need explicitly.
47+
// Check for this case, and inject the scope if required.
48+
if (credential.createScopedRequired()) {
49+
credential = credential.createScoped(CloudKMSScopes.all());
50+
}
51+
52+
return new CloudKMS.Builder(transport, jsonFactory, credential)
53+
.setApplicationName("CloudKMS quickstart")
54+
.build();
55+
}
56+
57+
public static void main(String[] args) throws IOException {
58+
// Your Google Cloud Platform project ID
59+
String projectId = args[0];
60+
// Lists keys in the "global" location.
61+
String location = "global";
62+
// The resource name of the location associated with the KeyRings
63+
String parent = String.format("projects/%s/locations/%s", projectId, location);
64+
// Instantiate the client
65+
CloudKMS kms = createAuthorizedClient();
66+
// list all key rings for your project
67+
ListKeyRingsResponse response = kms.projects().locations().keyRings().list(parent).execute();
68+
// Print the key rings
69+
System.out.println("Key Rings: ");
70+
if (null != response.getKeyRings()) {
71+
for (KeyRing keyRing : response.getKeyRings()) {
72+
System.out.println(keyRing.getName());
73+
}
74+
} else {
75+
System.out.println("No keyrings defined.");
76+
}
77+
}
78+
}
79+
// [END kms_quickstart]

0 commit comments

Comments
 (0)