xref: /aosp_15_r20/external/tink/java_src/examples/cleartextkeyset/CleartextKeysetExample.java (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
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 cleartext-keyset-example]
15 package cleartextkeyset;
16 
17 import static java.nio.charset.StandardCharsets.UTF_8;
18 
19 import com.google.crypto.tink.Aead;
20 import com.google.crypto.tink.InsecureSecretKeyAccess;
21 import com.google.crypto.tink.KeysetHandle;
22 import com.google.crypto.tink.TinkJsonProtoKeysetFormat;
23 import com.google.crypto.tink.aead.AeadConfig;
24 import com.google.crypto.tink.aead.PredefinedAeadParameters;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 
29 /**
30  * A command-line utility for generating, storing and using AES128_GCM keysets.
31  *
32  * <h1>WARNING: Loading a Keyset from disk is often a security problem -- hence this needs {@code
33  * InsecureSecretKeyAccess.get()}.
34  *
35  * <p>It requires the following arguments:
36  *
37  * <ul>
38  *   <li>mode: Can be "generate", "encrypt" or "decrypt". If mode is "generate" it will generate,
39  *       encrypt a keyset, store it in key-file. If mode is "encrypt" or "decrypt" it will read and
40  *       decrypt an keyset from key-file, and use it to encrypt or decrypt input-file.
41  *   <li>key-file: Read the encrypted key material from this file.
42  *   <li>input-file: If mode is "encrypt" or "decrypt", read the input from this file.
43  *   <li>output-file: If mode is "encrypt" or "decrypt", write the result to this file.
44  */
45 public final class CleartextKeysetExample {
46   private static final String MODE_ENCRYPT = "encrypt";
47   private static final String MODE_DECRYPT = "decrypt";
48   private static final String MODE_GENERATE = "generate";
49   private static final byte[] EMPTY_ASSOCIATED_DATA = new byte[0];
50 
main(String[] args)51   public static void main(String[] args) throws Exception {
52     if (args.length != 2 && args.length != 4) {
53       System.err.printf("Expected 2 or 4 parameters, got %d\n", args.length);
54       System.err.println(
55           "Usage: java CleartextKeysetExample generate/encrypt/decrypt key-file input-file"
56               + " output-file");
57       System.exit(1);
58     }
59     String mode = args[0];
60     if (!MODE_ENCRYPT.equals(mode) && !MODE_DECRYPT.equals(mode) && !MODE_GENERATE.equals(mode)) {
61       System.err.print("The first argument should be either encrypt, decrypt or generate");
62       System.exit(1);
63     }
64     Path keyFile = Paths.get(args[1]);
65 
66     // Initialise Tink: register all AEAD key types with the Tink runtime
67     AeadConfig.register();
68 
69     if (MODE_GENERATE.equals(mode)) {
70       // [START generate-a-new-keyset]
71       KeysetHandle handle = KeysetHandle.generateNew(PredefinedAeadParameters.AES128_GCM);
72       // [END generate-a-new-keyset]
73 
74       // [START store-a-cleartext-keyset]
75       String serializedKeyset =
76           TinkJsonProtoKeysetFormat.serializeKeyset(handle, InsecureSecretKeyAccess.get());
77       Files.write(keyFile, serializedKeyset.getBytes(UTF_8));
78       // [END store-a-cleartext-keyset]
79       return;
80     }
81 
82     // Use the primitive to encrypt/decrypt files
83 
84     // Read the keyset from disk
85     String serializedKeyset = new String(Files.readAllBytes(keyFile), UTF_8);
86     KeysetHandle handle =
87         TinkJsonProtoKeysetFormat.parseKeyset(serializedKeyset, InsecureSecretKeyAccess.get());
88 
89     // Get the primitive
90     Aead aead = handle.getPrimitive(Aead.class);
91 
92     byte[] input = Files.readAllBytes(Paths.get(args[2]));
93     Path outputFile = Paths.get(args[3]);
94 
95     if (MODE_ENCRYPT.equals(mode)) {
96       byte[] ciphertext = aead.encrypt(input, EMPTY_ASSOCIATED_DATA);
97       Files.write(outputFile, ciphertext);
98     } else if (MODE_DECRYPT.equals(mode)) {
99       byte[] plaintext = aead.decrypt(input, EMPTY_ASSOCIATED_DATA);
100       Files.write(outputFile, plaintext);
101     }
102   }
103 
CleartextKeysetExample()104   private CleartextKeysetExample() {}
105 }
106 // [END cleartext-keyset-example]
107