aboutsummaryrefslogtreecommitdiff
path: root/java_src/examples
diff options
context:
space:
mode:
authortholenst <tholenst@google.com>2023-05-03 06:43:13 -0700
committerCopybara-Service <copybara-worker@google.com>2023-05-03 06:44:33 -0700
commit264e9ebfafce77f3e610a4b7914ec9d5314366b1 (patch)
treed3de80dd37620394f63f84fe69dae6d69bceef14 /java_src/examples
parente6a9c700a8ba5a336584a3d7fec442f675e76820 (diff)
downloadtink-264e9ebfafce77f3e610a4b7914ec9d5314366b1.tar.gz
Modernize the JWT examples.
1) Avoid readers and writers. 2) Don't catch exceptions and exit. Java exits automatically if an exception is uncought. 3) Don't exit before return. Java exits if you return from main. 4) Use nio instead of io. PiperOrigin-RevId: 529074945
Diffstat (limited to 'java_src/examples')
-rw-r--r--java_src/examples/jwt/BUILD.bazel9
-rw-r--r--java_src/examples/jwt/JwtGeneratePublicJwkSet.java33
-rw-r--r--java_src/examples/jwt/JwtSign.java50
-rw-r--r--java_src/examples/jwt/JwtVerify.java45
4 files changed, 47 insertions, 90 deletions
diff --git a/java_src/examples/jwt/BUILD.bazel b/java_src/examples/jwt/BUILD.bazel
index 4a56b96f2..fe06f8eef 100644
--- a/java_src/examples/jwt/BUILD.bazel
+++ b/java_src/examples/jwt/BUILD.bazel
@@ -11,9 +11,9 @@ java_binary(
srcs = ["JwtSign.java"],
main_class = "jwt.JwtSign",
deps = [
- "@tink_java//src/main/java/com/google/crypto/tink:cleartext_keyset_handle",
- "@tink_java//src/main/java/com/google/crypto/tink:json_keyset_reader",
+ "@tink_java//src/main/java/com/google/crypto/tink:insecure_secret_key_access",
"@tink_java//src/main/java/com/google/crypto/tink:registry_cluster",
+ "@tink_java//src/main/java/com/google/crypto/tink:tink_json_proto_keyset_format",
"@tink_java//src/main/java/com/google/crypto/tink/jwt:jwt_public_key_sign",
"@tink_java//src/main/java/com/google/crypto/tink/jwt:jwt_signature_config",
"@tink_java//src/main/java/com/google/crypto/tink/jwt:raw_jwt",
@@ -25,9 +25,9 @@ java_binary(
srcs = ["JwtGeneratePublicJwkSet.java"],
main_class = "jwt.JwtGeneratePublicJwkSet",
deps = [
- "@tink_java//src/main/java/com/google/crypto/tink:cleartext_keyset_handle",
- "@tink_java//src/main/java/com/google/crypto/tink:json_keyset_reader",
+ "@tink_java//src/main/java/com/google/crypto/tink:insecure_secret_key_access",
"@tink_java//src/main/java/com/google/crypto/tink:registry_cluster",
+ "@tink_java//src/main/java/com/google/crypto/tink:tink_json_proto_keyset_format",
"@tink_java//src/main/java/com/google/crypto/tink/jwt:jwk_set_converter",
"@tink_java//src/main/java/com/google/crypto/tink/jwt:jwt_signature_config",
],
@@ -44,7 +44,6 @@ java_binary(
"@tink_java//src/main/java/com/google/crypto/tink/jwt:jwt_signature_config",
"@tink_java//src/main/java/com/google/crypto/tink/jwt:jwt_validator",
"@tink_java//src/main/java/com/google/crypto/tink/jwt:verified_jwt",
- "@tink_java//src/main/java/com/google/crypto/tink/tinkkey:key_access",
],
)
diff --git a/java_src/examples/jwt/JwtGeneratePublicJwkSet.java b/java_src/examples/jwt/JwtGeneratePublicJwkSet.java
index 824656af6..7260558cf 100644
--- a/java_src/examples/jwt/JwtGeneratePublicJwkSet.java
+++ b/java_src/examples/jwt/JwtGeneratePublicJwkSet.java
@@ -16,16 +16,14 @@ package jwt;
import static java.nio.charset.StandardCharsets.UTF_8;
-import com.google.crypto.tink.CleartextKeysetHandle;
-import com.google.crypto.tink.JsonKeysetReader;
+import com.google.crypto.tink.InsecureSecretKeyAccess;
import com.google.crypto.tink.KeysetHandle;
+import com.google.crypto.tink.TinkJsonProtoKeysetFormat;
import com.google.crypto.tink.jwt.JwkSetConverter;
import com.google.crypto.tink.jwt.JwtSignatureConfig;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.security.GeneralSecurityException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
/**
* A command-line example for generating the public JWT keyset in JWK set format.
@@ -47,29 +45,22 @@ public final class JwtGeneratePublicJwkSet {
System.exit(1);
}
- File privateKeysetFile = new File(args[0]);
- File publicJwkSetFile = new File(args[1]);
+ Path privateKeysetFile = Paths.get(args[0]);
+ Path publicJwkSetFile = Paths.get(args[1]);
// Register all JWT signature key types with the Tink runtime.
JwtSignatureConfig.register();
// Read the keyset into a KeysetHandle.
- KeysetHandle privateKeysetHandle = null;
- try (FileInputStream inputStream = new FileInputStream(privateKeysetFile)) {
- privateKeysetHandle =
- CleartextKeysetHandle.read(JsonKeysetReader.withInputStream(inputStream));
- } catch (GeneralSecurityException | IOException ex) {
- System.err.println("Cannot read keyset, got error: " + ex);
- System.exit(1);
- }
+ KeysetHandle privateKeysetHandle =
+ TinkJsonProtoKeysetFormat.parseKeyset(
+ new String(Files.readAllBytes(privateKeysetFile), UTF_8),
+ InsecureSecretKeyAccess.get());
// Export the public keyset as JWK set.
String publicJwkSet =
JwkSetConverter.fromPublicKeysetHandle(privateKeysetHandle.getPublicKeysetHandle());
- try (FileOutputStream stream = new FileOutputStream(publicJwkSetFile)) {
- stream.write(publicJwkSet.getBytes(UTF_8));
- }
- System.exit(0);
+ Files.write(publicJwkSetFile, publicJwkSet.getBytes(UTF_8));
}
private JwtGeneratePublicJwkSet() {}
diff --git a/java_src/examples/jwt/JwtSign.java b/java_src/examples/jwt/JwtSign.java
index adc160fd3..6183c5a08 100644
--- a/java_src/examples/jwt/JwtSign.java
+++ b/java_src/examples/jwt/JwtSign.java
@@ -16,17 +16,15 @@ package jwt;
import static java.nio.charset.StandardCharsets.UTF_8;
-import com.google.crypto.tink.CleartextKeysetHandle;
-import com.google.crypto.tink.JsonKeysetReader;
+import com.google.crypto.tink.InsecureSecretKeyAccess;
import com.google.crypto.tink.KeysetHandle;
+import com.google.crypto.tink.TinkJsonProtoKeysetFormat;
import com.google.crypto.tink.jwt.JwtPublicKeySign;
import com.google.crypto.tink.jwt.JwtSignatureConfig;
import com.google.crypto.tink.jwt.RawJwt;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.security.GeneralSecurityException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.time.Instant;
/**
@@ -50,42 +48,30 @@ public final class JwtSign {
System.exit(1);
}
- File privateKeysetFile = new File(args[0]);
+ Path privateKeysetFile = Paths.get(args[0]);
String audience = args[1];
- File tokenFile = new File(args[2]);
+ Path tokenFile = Paths.get(args[2]);
// Register all JWT signature key types with the Tink runtime.
JwtSignatureConfig.register();
// Read the private keyset into a KeysetHandle.
- KeysetHandle privateKeysetHandle = null;
- try (FileInputStream inputStream = new FileInputStream(privateKeysetFile)) {
- privateKeysetHandle =
- CleartextKeysetHandle.read(JsonKeysetReader.withInputStream(inputStream));
- } catch (GeneralSecurityException | IOException ex) {
- System.err.println("Cannot read keyset, got error: " + ex);
- System.exit(1);
- }
+ KeysetHandle privateKeysetHandle =
+ TinkJsonProtoKeysetFormat.parseKeyset(
+ new String(Files.readAllBytes(privateKeysetFile), UTF_8),
+ InsecureSecretKeyAccess.get());
// Get the primitive.
- JwtPublicKeySign signer = null;
- try {
- signer = privateKeysetHandle.getPrimitive(JwtPublicKeySign.class);
- } catch (GeneralSecurityException ex) {
- System.err.println("Cannot create primitive, got error: " + ex);
- System.exit(1);
- }
+ JwtPublicKeySign signer = privateKeysetHandle.getPrimitive(JwtPublicKeySign.class);
// Use the primitive to sign a token that expires in 100 seconds.
- RawJwt rawJwt = RawJwt.newBuilder()
- .addAudience(audience)
- .setExpiration(Instant.now().plusSeconds(100))
- .build();
+ RawJwt rawJwt =
+ RawJwt.newBuilder()
+ .addAudience(audience)
+ .setExpiration(Instant.now().plusSeconds(100))
+ .build();
String signedToken = signer.signAndEncode(rawJwt);
- try (FileOutputStream stream = new FileOutputStream(tokenFile)) {
- stream.write(signedToken.getBytes(UTF_8));
- }
- System.exit(0);
+ Files.write(tokenFile, signedToken.getBytes(UTF_8));
}
private JwtSign() {}
diff --git a/java_src/examples/jwt/JwtVerify.java b/java_src/examples/jwt/JwtVerify.java
index c5885b51e..4c8d790d1 100644
--- a/java_src/examples/jwt/JwtVerify.java
+++ b/java_src/examples/jwt/JwtVerify.java
@@ -22,10 +22,9 @@ import com.google.crypto.tink.jwt.JwtPublicKeyVerify;
import com.google.crypto.tink.jwt.JwtSignatureConfig;
import com.google.crypto.tink.jwt.JwtValidator;
import com.google.crypto.tink.jwt.VerifiedJwt;
-import java.io.File;
-import java.io.IOException;
import java.nio.file.Files;
-import java.security.GeneralSecurityException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
@@ -49,24 +48,19 @@ public final class JwtVerify {
System.exit(1);
}
- File publicJwkSetFile = new File(args[0]);
+ Path publicJwkSetFile = Paths.get(args[0]);
String audience = args[1];
- File tokenFile = new File(args[2]);
+ Path tokenFile = Paths.get(args[2]);
// Register all JWT signature key types with the Tink runtime.
JwtSignatureConfig.register();
// Read the public keyset in JWK set format into a KeysetHandle.
- KeysetHandle publicKeysetHandle = null;
- try {
- String publicJwkSet = new String(Files.readAllBytes(publicJwkSetFile.toPath()), UTF_8);
- publicKeysetHandle = JwkSetConverter.toPublicKeysetHandle(publicJwkSet);
- } catch (GeneralSecurityException | IOException ex) {
- System.err.println("Cannot read keyset, got error: " + ex);
- System.exit(1);
- }
+ KeysetHandle publicKeysetHandle =
+ JwkSetConverter.toPublicKeysetHandle(
+ new String(Files.readAllBytes(publicJwkSetFile), UTF_8));
- List<String> lines = Files.readAllLines(tokenFile.toPath());
+ List<String> lines = Files.readAllLines(tokenFile, UTF_8);
if (lines.size() != 1) {
System.err.printf("The signature file should contain only one line, got %d", lines.size());
System.exit(1);
@@ -74,26 +68,13 @@ public final class JwtVerify {
String signedToken = lines.get(0).trim();
// Get the primitive.
- JwtPublicKeyVerify verifier = null;
- try {
- verifier = publicKeysetHandle.getPrimitive(JwtPublicKeyVerify.class);
- } catch (GeneralSecurityException ex) {
- System.err.println("Cannot create primitive, got error: " + ex);
- System.exit(1);
- }
+ JwtPublicKeyVerify verifier = publicKeysetHandle.getPrimitive(JwtPublicKeyVerify.class);
// Use the primitive to verify a token.
- try {
- JwtValidator validator = JwtValidator.newBuilder().expectAudience(audience).build();
- VerifiedJwt verifiedJwt = verifier.verifyAndDecode(signedToken, validator);
- long seconds = ChronoUnit.SECONDS.between(Instant.now(), verifiedJwt.getExpiration());
- System.out.println("Token is valid and expires in " + seconds + " seconds.");
- } catch (GeneralSecurityException ex) {
- System.err.println("JWT verification failed.");
- System.exit(1);
- }
-
- System.exit(0);
+ JwtValidator validator = JwtValidator.newBuilder().expectAudience(audience).build();
+ VerifiedJwt verifiedJwt = verifier.verifyAndDecode(signedToken, validator);
+ long seconds = ChronoUnit.SECONDS.between(Instant.now(), verifiedJwt.getExpiration());
+ System.out.println("Token is valid and expires in " + seconds + " seconds.");
}
private JwtVerify() {}