Skip to content

Commit

Permalink
KMS: Make samples consistent with all languages. (#816)
Browse files Browse the repository at this point in the history
In particular:

* Define keyRingId and cryptoKeyId consistently with the API.
* User defined locationId everywhere.

I opted to keep the file I/O in the Command runner to keep the API
clean, especially when being rendered on
https://cloud.google.com/kms/docs/encrypt-decrypt.

Tracking bug: http://b/64758639
  • Loading branch information
white0ut authored and lesv committed Aug 18, 2017
1 parent 513173a commit 966a24f
Show file tree
Hide file tree
Showing 7 changed files with 164 additions and 183 deletions.
45 changes: 16 additions & 29 deletions kms/src/main/java/com/example/CryptFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,64 +59,51 @@ public static CloudKMS createAuthorizedClient() throws IOException {
.build();
}

/**
* Encrypts the given bytes, using the primary version of the specified crypto key.
*
* The primary version can be updated via the <a
* href="https://g.co/cloud/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys/updatePrimaryVersion">updatePrimaryVersion</a>
* method.
*/
public static byte[] encrypt(String projectId, String ringId, String keyId, byte[] plaintext)
throws IOException {
return encrypt(projectId, ringId, keyId, null, plaintext);
}

// [START kms_encrypt]

/**
* Encrypts the given bytes, using the specified crypto key version.
* Encrypts the given plaintext using the specified crypto key.
*/
public static byte[] encrypt(
String projectId, String ringId, String keyId, String version, byte[] plaintext)
String projectId, String locationId, String keyRingId, String cryptoKeyId, byte[] plaintext)
throws IOException {
String location = "global";
// The resource name of the cryptoKey
String cryptoKeyName = String.format(
String resourceName = String.format(
"projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
projectId, location, ringId, keyId);
if (null != version) {
cryptoKeyName += "/cryptoKeyVersions/" + version;
}
projectId, locationId, keyRingId, cryptoKeyId);

// Create the Cloud KMS client.
CloudKMS kms = createAuthorizedClient();

EncryptRequest request = new EncryptRequest().encodePlaintext(plaintext);
EncryptResponse response = kms.projects().locations().keyRings().cryptoKeys()
.encrypt(cryptoKeyName, request)
.execute();
.encrypt(resourceName, request)
.execute();

return response.decodeCiphertext();
}
// [END kms_encrypt]

// [START kms_decrypt]

/**
* Decrypts the given encrypted bytes, using the specified crypto key.
* Decrypts the provided ciphertext with the specified crypto key.
*/
public static byte[] decrypt(String projectId, String ringId, String keyId, byte[] encrypted)
public static byte[] decrypt(String projectId, String locationId, String keyRingId,
String cryptoKeyId, byte[] ciphertext)
throws IOException {
String location = "global";
// Create the Cloud KMS client.
CloudKMS kms = createAuthorizedClient();

// The resource name of the cryptoKey
String cryptoKeyName = String.format(
"projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
projectId, location, ringId, keyId);
projectId, locationId, keyRingId, cryptoKeyId);

DecryptRequest request = new DecryptRequest().encodeCiphertext(encrypted);
DecryptRequest request = new DecryptRequest().encodeCiphertext(ciphertext);
DecryptResponse response = kms.projects().locations().keyRings().cryptoKeys()
.decrypt(cryptoKeyName, request)
.execute();
.decrypt(cryptoKeyName, request)
.execute();

return response.decodePlaintext();
}
Expand Down
37 changes: 16 additions & 21 deletions kms/src/main/java/com/example/CryptFileCommands.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@
import org.kohsuke.args4j.spi.SubCommandHandler;
import org.kohsuke.args4j.spi.SubCommands;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import java.io.FileOutputStream;
import java.io.IOException;

/**
* Defines the different sub-commands and their parameters, for command-line invocation.
*/
Expand All @@ -33,50 +34,44 @@ class CryptFileCommands {
* An interface for a command-line sub-command.
*/
interface Command {
public void run() throws IOException;
void run() throws IOException;
}

// Most of the commands take some subset of the same arguments, so specify groups of arguments
// as classes for greater code reuse.
static class Args {
@Option(name = "--project-id", aliases = "-p", required = true, usage = "Your GCP project ID")
String projectId;
@Argument(metaVar = "ringId", required = true, index = 0, usage = "The ring id")
String ringId;
@Argument(metaVar = "keyId", required = true, index = 1, usage = "The key id")
String keyId;
@Argument(metaVar = "inFile", required = true, index = 2, usage = "The source file")
@Argument(metaVar = "locationId", required = true, index = 0, usage = "The key location")
String locationId;
@Argument(metaVar = "keyRingId", required = true, index = 1, usage = "The key ring id")
String keyRingId;
@Argument(metaVar = "cryptoKeyId", required = true, index = 2, usage = "The crypto key id")
String cryptoKeyId;
@Argument(metaVar = "inFile", required = true, index = 3, usage = "The source file")
String inFile;
@Argument(metaVar = "outFile", required = true, index = 3, usage = "The destination file")
@Argument(metaVar = "outFile", required = true, index = 4, usage = "The destination file")
String outFile;
}

public static class EncryptCommand extends Args implements Command {
public void run() throws IOException {
byte[] encrypted = CryptFile.encrypt(
projectId, ringId, keyId,
Files.readAllBytes(Paths.get(inFile)));
projectId, locationId, keyRingId, cryptoKeyId, Files.readAllBytes(Paths.get(inFile)));

FileOutputStream stream = new FileOutputStream(outFile);
try {
try (FileOutputStream stream = new FileOutputStream(outFile)) {
stream.write(encrypted);
} finally {
stream.close();
}
}
}

public static class DecryptCommand extends Args implements Command {
public void run() throws IOException {
byte[] decrypted = CryptFile.decrypt(
projectId, ringId, keyId,
Files.readAllBytes(Paths.get(inFile)));
projectId, locationId, keyRingId, cryptoKeyId, Files.readAllBytes(Paths.get(inFile)));

FileOutputStream stream = new FileOutputStream(outFile);
try {
try (FileOutputStream stream = new FileOutputStream(outFile)) {
stream.write(decrypted);
} finally {
stream.close();
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions kms/src/main/java/com/example/Quickstart.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public static CloudKMS createAuthorizedClient() throws IOException {
public static void main(String... args) throws Exception {
String projectId = args[0];
// The location of the Key Rings
String location = "global";
String location = args[1];

// Create the Cloud KMS client.
CloudKMS kms = createAuthorizedClient();
Expand All @@ -80,7 +80,7 @@ public static void main(String... args) throws Exception {
System.out.println(keyRing.getName());
}
} else {
System.out.println("No keyrings defined.");
System.out.println("No key rings defined.");
}
}
}
Expand Down
49 changes: 27 additions & 22 deletions kms/src/main/java/com/example/SnippetCommands.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class SnippetCommands {
* An interface for a command-line sub-command.
*/
interface Command {
public void run() throws IOException;
void run() throws IOException;
}

// Most of the commands take some subset of the same arguments, so specify groups of arguments
Expand All @@ -40,79 +40,84 @@ static class ProjectIdArgs {
String projectId;
}

static class KeyRingArgs extends ProjectIdArgs {
@Argument(metaVar = "ringId", required = true, index = 0, usage = "The ring id")
String ringId;
static class LocationIdArgs extends ProjectIdArgs {
@Argument(metaVar = "locationId", required = true, index = 0, usage = "The location id")
String locationId;
}

static class KeyRingArgs extends LocationIdArgs {
@Argument(metaVar = "keyRingId", required = true, index = 1, usage = "The key ring id")
String keyRingId;
}

static class KeyArgs extends KeyRingArgs {
@Argument(metaVar = "keyId", required = true, index = 1, usage = "The key id")
String keyId;
@Argument(metaVar = "cryptoKeyId", required = true, index = 2, usage = "The crypto key id")
String cryptoKeyId;
}

static class KeyVersionArgs extends KeyArgs {
@Argument(metaVar = "version", required = true, index = 2, usage = "The key version")
@Argument(metaVar = "version", required = true, index = 3, usage = "The key version")
String version;
}


public static class CreateKeyRingCommand extends KeyRingArgs implements Command {
public void run() throws IOException {
Snippets.createKeyRing(projectId, ringId);
Snippets.createKeyRing(projectId, locationId, keyRingId);
}
}

public static class CreateCryptoKeyCommand extends KeyArgs implements Command {
public void run() throws IOException {
Snippets.createCryptoKey(projectId, ringId, keyId);
Snippets.createCryptoKey(projectId, locationId, keyRingId, cryptoKeyId);
}
}

public static class CreateCryptoKeyVersionCommand extends KeyArgs implements Command {
public void run() throws IOException {
Snippets.createCryptoKeyVersion(projectId, ringId, keyId);
Snippets.createCryptoKeyVersion(projectId, locationId, keyRingId, cryptoKeyId);
}
}

public static class ListKeyRingsCommand extends ProjectIdArgs implements Command {
public static class ListKeyRingsCommand extends LocationIdArgs implements Command {
public void run() throws IOException {
Snippets.listKeyRings(projectId);
Snippets.listKeyRings(projectId, locationId);
}
}

public static class ListCryptoKeysCommand extends KeyRingArgs implements Command {
public void run() throws IOException {
Snippets.listCryptoKeys(projectId, ringId);
Snippets.listCryptoKeys(projectId, locationId, keyRingId);
}
}

public static class ListCryptoKeyVersionsCommand extends KeyArgs implements Command {
public void run() throws IOException {
Snippets.listCryptoKeyVersions(projectId, ringId, keyId);
Snippets.listCryptoKeyVersions(projectId, locationId, keyRingId, cryptoKeyId);
}
}

public static class DisableCryptoKeyVersionCommand extends KeyVersionArgs implements Command {
public void run() throws IOException {
Snippets.disableCryptoKeyVersion(projectId, ringId, keyId, version);
Snippets.disableCryptoKeyVersion(projectId, locationId, keyRingId, cryptoKeyId, version);
}
}

public static class DestroyCryptoKeyVersionCommand extends KeyVersionArgs implements Command {
public void run() throws IOException {
Snippets.destroyCryptoKeyVersion(projectId, ringId, keyId, version);
Snippets.destroyCryptoKeyVersion(projectId, locationId, keyRingId, cryptoKeyId, version);
}
}

public static class GetKeyRingPolicyCommand extends KeyRingArgs implements Command {
public void run() throws IOException {
Snippets.getKeyRingPolicy(projectId, ringId);
Snippets.getKeyRingPolicy(projectId, locationId, keyRingId);
}
}

public static class GetCryptoKeyPolicyCommand extends KeyArgs implements Command {
public void run() throws IOException {
Snippets.getCryptoKeyPolicy(projectId, ringId, keyId);
Snippets.getCryptoKeyPolicy(projectId, locationId, keyRingId, cryptoKeyId);
}
}

Expand All @@ -128,7 +133,7 @@ public static class AddMemberToKeyRingPolicyCommand extends KeyRingArgs implemen
String role;

public void run() throws IOException {
Snippets.addMemberToKeyRingPolicy(projectId, ringId, member, role);
Snippets.addMemberToKeyRingPolicy(projectId, locationId, keyRingId, member, role);
}
}

Expand All @@ -144,7 +149,7 @@ public static class AddMemberToCryptoKeyPolicyCommand extends KeyArgs implements
String role;

public void run() throws IOException {
Snippets.addMemberToCryptoKeyPolicy(projectId, ringId, keyId, member, role);
Snippets.addMemberToCryptoKeyPolicy(projectId, locationId, keyRingId, cryptoKeyId, member, role);
}
}

Expand All @@ -160,7 +165,7 @@ public static class RemoveMemberFromKeyRingPolicyCommand extends KeyRingArgs imp
String role;

public void run() throws IOException {
Snippets.removeMemberFromKeyRingPolicy(projectId, ringId, member, role);
Snippets.removeMemberFromKeyRingPolicy(projectId, locationId, keyRingId, member, role);
}
}

Expand All @@ -176,7 +181,7 @@ public static class RemoveMemberFromCryptoKeyPolicyCommand extends KeyArgs imple
String role;

public void run() throws IOException {
Snippets.removeMemberFromCryptoKeyPolicy(projectId, ringId, keyId, member, role);
Snippets.removeMemberFromCryptoKeyPolicy(projectId, locationId, keyRingId, cryptoKeyId, member, role);
}
}

Expand Down
Loading

0 comments on commit 966a24f

Please sign in to comment.