xref: /aosp_15_r20/external/tink/java_src/examples/jwt/JwtSign.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-sign-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.JwtPublicKeySign;
23 import com.google.crypto.tink.jwt.JwtSignatureConfig;
24 import com.google.crypto.tink.jwt.RawJwt;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.time.Instant;
29 
30 /**
31  * A command-line utility for signing JSON Web Tokens (JWTs).
32  *
33  * <p>It loads cleartext private keys from disk - this is not recommended!
34  *
35  * <p>It requires the following arguments:
36  *
37  * <ul>
38  *   <li>private-keyset-file: Name of the input file containing the private keyset.
39  *   <li>audience: The audience claim to be used in the token
40  *   <li>token-file: name of the output file containing the signed JWT.
41  */
42 public final class JwtSign {
main(String[] args)43   public static void main(String[] args) throws Exception {
44     if (args.length != 3) {
45       System.err.printf("Expected 3 parameters, got %d\n", args.length);
46       System.err.println(
47           "Usage: java JwtSign private-keyset-file audience token-file");
48       System.exit(1);
49     }
50 
51     Path privateKeysetFile = Paths.get(args[0]);
52     String audience = args[1];
53     Path tokenFile = Paths.get(args[2]);
54 
55     // Register all JWT signature key types with the Tink runtime.
56     JwtSignatureConfig.register();
57 
58     // Read the private keyset into a KeysetHandle.
59     KeysetHandle privateKeysetHandle =
60         TinkJsonProtoKeysetFormat.parseKeyset(
61             new String(Files.readAllBytes(privateKeysetFile), UTF_8),
62             InsecureSecretKeyAccess.get());
63 
64     // Get the primitive.
65     JwtPublicKeySign signer = privateKeysetHandle.getPrimitive(JwtPublicKeySign.class);
66 
67     // Use the primitive to sign a token that expires in 100 seconds.
68     RawJwt rawJwt =
69         RawJwt.newBuilder()
70             .addAudience(audience)
71             .setExpiration(Instant.now().plusSeconds(100))
72             .build();
73     String signedToken = signer.signAndEncode(rawJwt);
74     Files.write(tokenFile, signedToken.getBytes(UTF_8));
75   }
76 
JwtSign()77   private JwtSign() {}
78 }
79 // [END java-jwt-sign-example]
80