• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2021 Google LLC
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 // [START encrypted-keyset-example]
15 package encryptedkeyset;
16 
17 import static java.nio.charset.StandardCharsets.UTF_8;
18 
19 import com.google.crypto.tink.Aead;
20 import com.google.crypto.tink.KeysetHandle;
21 import com.google.crypto.tink.TinkJsonProtoKeysetFormat;
22 import com.google.crypto.tink.aead.AeadConfig;
23 import com.google.crypto.tink.aead.KmsAeadKeyManager;
24 import com.google.crypto.tink.aead.PredefinedAeadParameters;
25 import com.google.crypto.tink.integration.gcpkms.GcpKmsClient;
26 import java.nio.file.Files;
27 import java.nio.file.Path;
28 import java.nio.file.Paths;
29 import java.util.Optional;
30 
31 /**
32  * A command-line utility for working with encrypted keysets.
33  *
34  * <p>It requires the following arguments:
35  *
36  * <ul>
37  *   <li>mode: Can be "generate", "encrypt" or "decrypt". If mode is "generate", it will generate a
38  *       keyset, encrypt it and store it in the key-file argument. If mode is "encrypt" or
39  *       "decrypt", it will read and decrypt an keyset from the key-file argument, and use it to
40  *       encrypt or decrypt the input-file argument.
41  *   <li>kek-uri: Use this Cloud KMS' key as the key-encrypting-key for envelope encryption.
42  *   <li>gcp-credential-file: Use this JSON credential file to connect to Cloud KMS.
43  *   <li>input-file: If mode is "encrypt" or "decrypt", read the input from this file.
44  *   <li>output-file: If mode is "encrypt" or "decrypt", write the result to this file.
45  */
46 public final class EncryptedKeysetExample {
47   private static final String MODE_ENCRYPT = "encrypt";
48   private static final String MODE_DECRYPT = "decrypt";
49   private static final String MODE_GENERATE = "generate";
50   private static final byte[] EMPTY_ASSOCIATED_DATA = new byte[0];
51 
main(String[] args)52   public static void main(String[] args) throws Exception {
53     if (args.length != 4 && args.length != 6) {
54       System.err.printf("Expected 4 or 6 parameters, got %d\n", args.length);
55       System.err.println(
56           "Usage: java EncryptedKeysetExample generate/encrypt/decrypt key-file kek-uri"
57               + " gcp-credential-file input-file output-file");
58       System.exit(1);
59     }
60     String mode = args[0];
61     if (!MODE_ENCRYPT.equals(mode) && !MODE_DECRYPT.equals(mode) && !MODE_GENERATE.equals(mode)) {
62       System.err.print("The first argument should be either encrypt, decrypt or generate");
63       System.exit(1);
64     }
65     Path keyFile = Paths.get(args[1]);
66     String kekUri = args[2];
67     String gcpCredentialFilename = args[3];
68 
69     // Initialise Tink: register all AEAD key types with the Tink runtime
70     AeadConfig.register();
71 
72     // Read the GCP credentials and set up client
73     GcpKmsClient.register(Optional.of(kekUri), Optional.of(gcpCredentialFilename));
74 
75     // From the key-encryption key (KEK) URI, create a remote AEAD primitive for encrypting Tink
76     // keysets.
77     KeysetHandle kekHandle = KeysetHandle.generateNew(KmsAeadKeyManager.createKeyTemplate(kekUri));
78     Aead kekAead = kekHandle.getPrimitive(Aead.class);
79 
80     if (MODE_GENERATE.equals(mode)) {
81       // [START generate-a-new-keyset]
82       KeysetHandle handle = KeysetHandle.generateNew(PredefinedAeadParameters.AES128_GCM);
83       // [END generate-a-new-keyset]
84 
85       // [START encrypt-a-keyset]
86       String serializedEncryptedKeyset =
87           TinkJsonProtoKeysetFormat.serializeEncryptedKeyset(
88               handle, kekAead, EMPTY_ASSOCIATED_DATA);
89       Files.write(keyFile, serializedEncryptedKeyset.getBytes(UTF_8));
90       // [END encrypt-a-keyset]
91       return;
92     }
93 
94     // Use the primitive to encrypt/decrypt files
95 
96     // Read the encrypted keyset
97     KeysetHandle handle =
98         TinkJsonProtoKeysetFormat.parseEncryptedKeyset(
99             new String(Files.readAllBytes(keyFile), UTF_8), kekAead, EMPTY_ASSOCIATED_DATA);
100 
101     // Get the primitive
102     Aead aead = handle.getPrimitive(Aead.class);
103 
104     Path inputFile = Paths.get(args[4]);
105     Path outputFile = Paths.get(args[5]);
106 
107     if (MODE_ENCRYPT.equals(mode)) {
108       byte[] plaintext = Files.readAllBytes(inputFile);
109       byte[] ciphertext = aead.encrypt(plaintext, EMPTY_ASSOCIATED_DATA);
110       Files.write(outputFile, ciphertext);
111     } else if (MODE_DECRYPT.equals(mode)) {
112       byte[] ciphertext = Files.readAllBytes(inputFile);
113       byte[] plaintext = aead.decrypt(ciphertext, EMPTY_ASSOCIATED_DATA);
114       Files.write(outputFile, plaintext);
115     }
116   }
117 
EncryptedKeysetExample()118   private EncryptedKeysetExample() {}
119 }
120 // [END encrypted-keyset-example]
121