xref: /aosp_15_r20/external/tink/java_src/examples/jwt/JwtGeneratePublicJwkSet.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 java-jwt-generate-public-jwk-set-example]
15 package jwt;
16 
17 import static java.nio.charset.StandardCharsets.UTF_8;
18 
19 import com.google.crypto.tink.InsecureSecretKeyAccess;
20 import com.google.crypto.tink.KeysetHandle;
21 import com.google.crypto.tink.TinkJsonProtoKeysetFormat;
22 import com.google.crypto.tink.jwt.JwkSetConverter;
23 import com.google.crypto.tink.jwt.JwtSignatureConfig;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 
28 /**
29  * A command-line example for generating the public JWT keyset in JWK set format.
30  *
31  * <p>It loads cleartext private keys from disk - this is not recommended!
32  *
33  * <p>It requires the following arguments:
34  *
35  * <ul>
36  *   <li>private-keyset-file: Name of the input file containing the private keyset.
37  *   <li>public-jwkset-file: Name of the output file containing the public key in JWK set format.
38  */
39 public final class JwtGeneratePublicJwkSet {
main(String[] args)40   public static void main(String[] args) throws Exception {
41     if (args.length != 2) {
42       System.err.printf("Expected 2 parameters, got %d\n", args.length);
43       System.err.println(
44           "Usage: java JwtGeneratePublicJwkSet private-keyset-file public-jwk-set-file");
45       System.exit(1);
46     }
47 
48     Path privateKeysetFile = Paths.get(args[0]);
49     Path publicJwkSetFile = Paths.get(args[1]);
50 
51     // Register all JWT signature key types with the Tink runtime.
52     JwtSignatureConfig.register();
53 
54     // Read the keyset into a KeysetHandle.
55     KeysetHandle privateKeysetHandle =
56         TinkJsonProtoKeysetFormat.parseKeyset(
57             new String(Files.readAllBytes(privateKeysetFile), UTF_8),
58             InsecureSecretKeyAccess.get());
59 
60     // Export the public keyset as JWK set.
61     String publicJwkSet =
62         JwkSetConverter.fromPublicKeysetHandle(privateKeysetHandle.getPublicKeysetHandle());
63     Files.write(publicJwkSetFile, publicJwkSet.getBytes(UTF_8));
64   }
65 
JwtGeneratePublicJwkSet()66   private JwtGeneratePublicJwkSet() {}
67 }
68 // [END java-jwt-generate-public-jwk-set-example]
69