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.RegistryConfiguration; 22 import com.google.crypto.tink.TinkJsonProtoKeysetFormat; 23 import com.google.crypto.tink.jwt.JwtPublicKeySign; 24 import com.google.crypto.tink.jwt.JwtSignatureConfig; 25 import com.google.crypto.tink.jwt.RawJwt; 26 import java.nio.file.Files; 27 import java.nio.file.Path; 28 import java.nio.file.Paths; 29 import java.time.Instant; 30 31 /** 32 * A command-line utility for signing JSON Web Tokens (JWTs). 33 * 34 * <p>It loads cleartext private keys from disk - this is not recommended! 35 * 36 * <p>It requires the following arguments: 37 * 38 * <ul> 39 * <li>private-keyset-file: Name of the input file containing the private keyset. 40 * <li>audience: The audience claim to be used in the token 41 * <li>token-file: name of the output file containing the signed JWT. 42 */ 43 public final class JwtSign { main(String[] args)44 public static void main(String[] args) throws Exception { 45 if (args.length != 3) { 46 System.err.printf("Expected 3 parameters, got %d\n", args.length); 47 System.err.println("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 = 66 privateKeysetHandle.getPrimitive(RegistryConfiguration.get(), JwtPublicKeySign.class); 67 68 // Use the primitive to sign a token that expires in 100 seconds. 69 RawJwt rawJwt = 70 RawJwt.newBuilder() 71 .addAudience(audience) 72 .setExpiration(Instant.now().plusSeconds(100)) 73 .build(); 74 String signedToken = signer.signAndEncode(rawJwt); 75 Files.write(tokenFile, signedToken.getBytes(UTF_8)); 76 } 77 JwtSign()78 private JwtSign() {} 79 } 80 // [END java-jwt-sign-example] 81