diff --git a/LICENSE b/LICENSE index c8d79ce..5f0f70b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015 RootServices +Copyright (c) 2020 TokenSmith Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 79a823e..830e403 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,22 @@ [JSON Web Tokens](https://tools.ietf.org/html/rfc7519) --------------------------------------------------------------------------------------------------------------------- -[![Build Status](https://travis-ci.org/RootServices/jwt.svg?branch=development)](https://travis-ci.org/RootServices/jwt) +[![Build Status](https://travis-ci.org/TokenSmith/jwt.svg?branch=development)](https://travis-ci.org/TokenSmith/jwt) Documentation ------------ - More documentation is available [here](http://rootservices.github.io/jwt/). + More documentation is available [here](http://tokensmith.github.io/jwt/). Quick Start ----------- This is a Java implementation of JWT, JWS, and JWE. + + - [Unsecured JWT](#unsecured-jwt) + - [Read a compact JWT](#read-a-compact-jwt) + - [Asymmetric Key](#asymmetric-key) + - [Symmetric Key](#symmetric-key) + - [Generate Key](#generate-key) ## Unsecured JWT ```java @@ -19,17 +25,40 @@ UnsecureCompactBuilder compactBuilder = new UnsecureCompactBuilder(); Claim claim = new Claim(); claim.setUriIsRoot(true); -ByteArrayOutputStream encodedJwt = compactBuilder.claims(claim).build(); +ByteArrayOutputStream encodedJwt = compactBuilder + .claims(claim) + .build(); ``` +## Read a compact JWT +```java +JwtAppFactory appFactory = new JwtAppFactory(); + +String jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZX0.TeZ3DKSE-gplbaoA8CK_RMojt8CfA1MTYaM_ZuOeGNw"; +JwtSerde jwtSerde = appFactory.jwtSerde(); + +JsonWebToken jsonWebToken; +try { + jsonWebToken = jwtSerde.stringToJwt(jwt, Claim.class); +} catch (InvalidJWT | JsonToJwtException e) { + // may not have been a jwt + // may not have been able to deserialize the header or claims. + throw e; +} + +// Can access claims in, jsonWebToken. +``` + ## JWS Compact Serialization ### Asymmetric key + +#### Create ```java SecureCompactBuilder compactBuilder = new SecureCompactBuilder(); -RSAKeyPair key = Factory.makeRSAKeyPair(); -key.setKeyId(Optional.of("test-key-id")); +KeyGenerator keyGenerator = jwtAppFactory.keyGenerator(); +SymmetricKey key = keyGenerator.symmetricKey(Optional.of(""test-key-id""), Use.SIGNATURE); Claim claim = new Claim(); claim.setUriIsRoot(true); @@ -40,7 +69,29 @@ ByteArrayOutputStream actual = compactBuilder.alg(Algorithm.RS256) .build(); ``` +#### Verify Signature +```java +RSAPublicKey publicKey = new RSAPublicKey( + Optional.of("test-key-id"), + Use.SIGNATURE, + new BigInteger("20446702916744654562596343388758805860065209639960173505037453331270270518732245089773723012043203236097095623402044690115755377345254696448759605707788965848889501746836211206270643833663949992536246985362693736387185145424787922241585721992924045675229348655595626434390043002821512765630397723028023792577935108185822753692574221566930937805031155820097146819964920270008811327036286786392793593121762425048860211859763441770446703722015857250621107855398693133264081150697423188751482418465308470313958250757758547155699749157985955379381294962058862159085915015369381046959790476428631998204940879604226680285601"), + new BigInteger("65537") +); + +JwtAppFactory appFactory = new JwtAppFactory(); +VerifySignature verifySignature; + +try { + verifySignature = appFactory.verifySignature(Algorithm.RS256, publicKey); +} catch (SignatureException e) { + throw e; +} + +boolean isSignatureValid = verifySignature.run(jsonWebToken); +``` ### Symmetric key + +#### Create ```java SecureCompactBuilder compactBuilder = new SecureCompactBuilder(); @@ -55,10 +106,29 @@ ByteArrayOutputStream actual = compactBuilder.alg(Algorithm.HS256) .claims(claim) .build(); ``` - +#### Verify Signature +```java +SymmetricKey key = new SymmetricKey( + Optional.of("test-key-id"), + "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow", + Use.SIGNATURE +); + +JwtAppFactory appFactory = new JwtAppFactory(); +VerifySignature verifySignature = null; +try { + verifySignature = appFactory.verifySignature(Algorithm.HS256, key); +} catch (SignatureException e) { + throw e; +} + +boolean isSignatureValid = verifySignature.run(jsonWebToken); +``` ## JWE Compact Serialization ### Asymmetric key + +#### Create ```java EncryptedCompactBuilder compactBuilder = new EncryptedCompactBuilder(); @@ -75,6 +145,8 @@ ByteArrayOutputStream actual = compactBuilder.encAlg(EncryptionAlgorithm.AES_GCM ``` ### Symmetric key + +#### Create ```java EncryptedCompactBuilder compactBuilder = new EncryptedCompactBuilder(); @@ -89,3 +161,21 @@ ByteArrayOutputStream actual = compactBuilder.encAlg(EncryptionAlgorithm.AES_GCM .cek(key) .build(); ``` + +## Generate Key + +### Symmetric Key +```java +JwtAppFactory jwtAppFactory = new JwtAppFactory(); + +KeyGenerator keyGenerator = jwtAppFactory.keyGenerator(); +SymmetricKey key = keyGenerator.symmetricKey(Optional.of("123"), Use.SIGNATURE); +``` + +### Asymmetric Key +```java +JwtAppFactory jwtAppFactory = new JwtAppFactory(); + +KeyGenerator keyGenerator = jwtAppFactory.keyGenerator(); +RSAKeyPair key = subject.rsaKeyPair(KeyGenerator.RSA_1024, Optional.of("123"), Use.SIGNATURE); +``` diff --git a/build.gradle b/build.gradle index 3e67a6c..de6b314 100644 --- a/build.gradle +++ b/build.gradle @@ -5,22 +5,23 @@ plugins { } repositories { + maven { url "https://oss.sonatype.org/content/repositories/snapshots" } + maven { url "https://oss.sonatype.org/content/repositories/releases" } + mavenCentral() mavenLocal() - maven { - url = 'http://repo.maven.apache.org/maven2' - } } group = 'net.tokensmith' -version = '1.3.2' -description = 'Interface used in Otter Web Framework to help serializing to/from JSON' +version = '1.3.3' +description = 'Java implementation of JWT' sourceCompatibility = 12 targetCompatibility = 12 ext { - jacksonVersion = '2.9.10' - log4jVersion = '2.12.1' + jacksonVersion = '2.11.0' + log4jVersion = '2.13.3' + slf4jVersion = '1.7.30' mockitoVersion = '2.28.2' } @@ -29,8 +30,10 @@ dependencies { implementation "com.fasterxml.jackson.core:jackson-databind:${jacksonVersion}" implementation "com.fasterxml.jackson.datatype:jackson-datatype-jdk8:${jacksonVersion}" implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:${jacksonVersion}" - implementation "org.apache.logging.log4j:log4j-api:${log4jVersion}" - implementation "org.apache.logging.log4j:log4j-core:${log4jVersion}" + compile "org.slf4j:slf4j-simple:${slf4jVersion}" + compile "org.apache.logging.log4j:log4j-1.2-api:${log4jVersion}" + compile "org.apache.logging.log4j:log4j-api:${log4jVersion}" + compile "org.apache.logging.log4j:log4j-core:${log4jVersion}" testImplementation group: 'junit', name: 'junit', version:'4.12' testImplementation group: 'org.hamcrest', name: 'hamcrest-all', version:'1.3' @@ -61,18 +64,18 @@ publishing { name = 'jwt' packaging = 'jar' description = 'Java Implementation of JSON Web Tokens' - url = 'https://github.com/RootServices/jwt' + url = 'https://github.com/TokenSmith/jwt' scm { - connection = 'git@github.com:RootServices/jwt.git' - developerConnection = 'git@github.com:RootServices/jwt.git' - url = 'https://github.com/RootServices/jwt' + connection = 'git@github.com:TokenSmith/jwt.git' + developerConnection = 'git@github.com:TokenSmith/jwt.git' + url = 'https://github.com/TokenSmith/jwt' } licenses { license { name = 'The MIT License (MIT)' - url = 'https://github.com/RootServices/jwt/blob/development/LICENSE' + url = 'https://github.com/TokenSmith/jwt/blob/development/LICENSE' } } @@ -115,3 +118,7 @@ javadoc { } } +tasks.withType(JavaCompile) { + options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" +} + diff --git a/src/main/java/net/tokensmith/jwt/builder/compact/EncryptedCompactBuilder.java b/src/main/java/net/tokensmith/jwt/builder/compact/EncryptedCompactBuilder.java index 0385c30..7c5494c 100644 --- a/src/main/java/net/tokensmith/jwt/builder/compact/EncryptedCompactBuilder.java +++ b/src/main/java/net/tokensmith/jwt/builder/compact/EncryptedCompactBuilder.java @@ -5,8 +5,6 @@ import net.tokensmith.jwt.entity.jwk.SymmetricKey; import net.tokensmith.jwt.entity.jwt.header.Algorithm; import net.tokensmith.jwt.entity.jwt.header.Header; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import net.tokensmith.jwt.builder.exception.CompactException; import net.tokensmith.jwt.config.JwtAppFactory; import net.tokensmith.jwt.jwe.entity.JWE; @@ -15,13 +13,15 @@ import net.tokensmith.jwt.jws.signer.factory.rsa.exception.PublicKeyException; import net.tokensmith.jwt.serialization.exception.EncryptException; import net.tokensmith.jwt.serialization.exception.JsonToJwtException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.util.Base64; import java.util.Optional; public class EncryptedCompactBuilder { - private static final Logger LOGGER = LogManager.getLogger(EncryptedCompactBuilder.class); + private static final Logger LOGGER = LoggerFactory.getLogger(EncryptedCompactBuilder.class); public static final String UNABLE_TO_BUILD_COMPACT_JWE = "Unable to build compact jwe"; private static JwtAppFactory jwtAppFactory = new JwtAppFactory(); diff --git a/src/main/java/net/tokensmith/jwt/builder/compact/SecureCompactBuilder.java b/src/main/java/net/tokensmith/jwt/builder/compact/SecureCompactBuilder.java index 8d7d29e..8dd19ff 100644 --- a/src/main/java/net/tokensmith/jwt/builder/compact/SecureCompactBuilder.java +++ b/src/main/java/net/tokensmith/jwt/builder/compact/SecureCompactBuilder.java @@ -3,18 +3,18 @@ import net.tokensmith.jwt.entity.jwk.Key; import net.tokensmith.jwt.entity.jwt.Claims; import net.tokensmith.jwt.entity.jwt.header.Algorithm; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import net.tokensmith.jwt.builder.exception.CompactException; import net.tokensmith.jwt.config.JwtAppFactory; import net.tokensmith.jwt.exception.SignatureException; import net.tokensmith.jwt.jws.serialization.SecureJwtSerializer; import net.tokensmith.jwt.serialization.exception.JwtToJsonException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; public class SecureCompactBuilder { - private static final Logger LOGGER = LogManager.getLogger(SecureCompactBuilder.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SecureCompactBuilder.class); public static final String UNABLE_TO_BUILD_COMPACT_JWT = "Unable to build compact jwt"; private static JwtAppFactory jwtAppFactory = new JwtAppFactory(); diff --git a/src/main/java/net/tokensmith/jwt/config/JwtAppFactory.java b/src/main/java/net/tokensmith/jwt/config/JwtAppFactory.java index 9eeeb73..d2bce8d 100644 --- a/src/main/java/net/tokensmith/jwt/config/JwtAppFactory.java +++ b/src/main/java/net/tokensmith/jwt/config/JwtAppFactory.java @@ -19,9 +19,11 @@ import net.tokensmith.jwt.jwe.serialization.direct.JweDirectSerializer; import net.tokensmith.jwt.jwe.serialization.rsa.JweRsaDeserializer; import net.tokensmith.jwt.jwe.serialization.rsa.JweRsaSerializer; -import net.tokensmith.jwt.jwk.PrivateKeyFactory; -import net.tokensmith.jwt.jwk.PublicKeyFactory; -import net.tokensmith.jwt.jwk.SecretKeyFactory; +import net.tokensmith.jwt.jwk.PrivateKeyTranslator; +import net.tokensmith.jwt.jwk.PublicKeyTranslator; +import net.tokensmith.jwt.jwk.generator.KeyGenerator; +import net.tokensmith.jwt.jwk.generator.jdk.RSAPrivateCrtKeyGenerator; +import net.tokensmith.jwt.jwk.generator.jdk.SecretKeyGenerator; import net.tokensmith.jwt.jws.signer.Signer; import net.tokensmith.jwt.jws.signer.factory.SignerFactory; import net.tokensmith.jwt.jws.signer.factory.exception.InvalidAlgorithmException; @@ -36,20 +38,20 @@ import net.tokensmith.jwt.serialization.JwtSerde; import net.tokensmith.jwt.serialization.Serdes; import net.tokensmith.jwt.serialization.UnSecureJwtSerializer; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import net.tokensmith.jwt.jws.serialization.SecureJwtSerializer; -import net.tokensmith.jwt.jws.signer.factory.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.crypto.Cipher; import java.security.KeyFactory; +import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.util.Base64; public class JwtAppFactory { - private static final Logger LOGGER = LogManager.getLogger(JwtAppFactory.class); + private static final Logger LOGGER = LoggerFactory.getLogger(JwtAppFactory.class); public static final String KEY_WAS_INVALID = "Could not construct Signer. Key was invalid."; public static final String ALG_WAS_INVALID = "Could not construct Signer. Algorithm was invalid."; public static final String RSA = "RSA"; @@ -125,8 +127,8 @@ public JweDirectDesializer jweDirectDesializer() { ); } - public PublicKeyFactory publicKeyFactory() { - return new PublicKeyFactory(rsaKeyFactory()); + public PublicKeyTranslator publicKeyFactory() { + return new PublicKeyTranslator(rsaKeyFactory()); } public PublicKeySignatureFactory publicKeySignatureFactory() { @@ -137,8 +139,8 @@ public MacFactory macFactory() { return new MacFactory(urlDecoder()); } - public PrivateKeyFactory privateKeyFactory() { - return new PrivateKeyFactory(rsaKeyFactory()); + public PrivateKeyTranslator privateKeyFactory() { + return new PrivateKeyTranslator(rsaKeyFactory()); } public PrivateKeySignatureFactory privateKeySignatureFactory() { @@ -189,7 +191,7 @@ public SecureJwtSerializer secureJwtSerializer(Algorithm alg, Key jwk) throws Si public JweRsaSerializer jweRsaSerializer(RSAPublicKey jwk) throws PublicKeyException, CipherException { java.security.interfaces.RSAPublicKey jdkKey; try { - jdkKey = publicKeyFactory().makePublicKey(jwk); + jdkKey = publicKeyFactory().to(jwk); } catch (PublicKeyException e) { throw e; } @@ -205,7 +207,7 @@ public JweRsaSerializer jweRsaSerializer(RSAPublicKey jwk) throws PublicKeyExcep serdes(), encoder(), rsaEncryptCipher, - new SecretKeyFactory(), + new SecretKeyGenerator(), cipherSymmetricFactory() ); } @@ -223,6 +225,14 @@ public UnSecureJwtSerializer unSecureJwtSerializer() { return new UnSecureJwtSerializer(unsecureJwtFactory(), jwtSerde()); } + public KeyGenerator keyGenerator() { + return new KeyGenerator(new SecretKeyGenerator(), rsaPrivateCrtKeyGenerator()); + } + + protected RSAPrivateCrtKeyGenerator rsaPrivateCrtKeyGenerator() { + return new RSAPrivateCrtKeyGenerator(keyPairGenerator(), rsaKeyFactory()); + } + protected KeyFactory rsaKeyFactory() { if (this.RSAKeyFactory == null) { try { @@ -234,4 +244,14 @@ protected KeyFactory rsaKeyFactory() { } return RSAKeyFactory; } + + protected KeyPairGenerator keyPairGenerator() { + KeyPairGenerator keyPairGenerator = null; + try { + keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + } catch (NoSuchAlgorithmException e) { + LOGGER.error(e.getMessage(), e); + } + return keyPairGenerator; + } } diff --git a/src/main/java/net/tokensmith/jwt/entity/jwk/RSAKeyPair.java b/src/main/java/net/tokensmith/jwt/entity/jwk/RSAKeyPair.java index 331d963..e61fc96 100644 --- a/src/main/java/net/tokensmith/jwt/entity/jwk/RSAKeyPair.java +++ b/src/main/java/net/tokensmith/jwt/entity/jwk/RSAKeyPair.java @@ -1,5 +1,6 @@ package net.tokensmith.jwt.entity.jwk; +import javax.swing.text.html.Option; import java.math.BigInteger; import java.util.Optional; @@ -25,8 +26,8 @@ public class RSAKeyPair extends Key { private BigInteger dq; private BigInteger qi; - public RSAKeyPair(Optional keyId, KeyType keyType, Use use, BigInteger n, BigInteger e, BigInteger d, BigInteger p, BigInteger q, BigInteger dp, BigInteger dq, BigInteger qi) { - super(keyId, keyType, use); + public RSAKeyPair(Optional keyId, Use use, BigInteger n, BigInteger e, BigInteger d, BigInteger p, BigInteger q, BigInteger dp, BigInteger dq, BigInteger qi) { + super(keyId, KeyType.RSA, use); this.n = n; this.e = e; this.d = d; @@ -101,4 +102,71 @@ public BigInteger getQi() { public void setQi(BigInteger qi) { this.qi = qi; } + + public static class Builder { + private Optional keyId = Optional.empty(); + private Use use; + private BigInteger n; // modulus + private BigInteger e; // public exponent + private BigInteger d; // private exponent + private BigInteger p; + private BigInteger q; + private BigInteger dp; + private BigInteger dq; + private BigInteger qi; + + public Builder keyId(Optional keyId) { + this.keyId = keyId; + return this; + } + + public Builder use(Use use) { + this.use = use; + return this; + } + + public Builder n(BigInteger n) { + this.n = n; + return this; + } + + public Builder e(BigInteger e) { + this.e = e; + return this; + } + + public Builder d(BigInteger d) { + this.d = d; + return this; + } + + public Builder p(BigInteger p) { + this.p = p; + return this; + } + + public Builder q(BigInteger q) { + this.q = q; + return this; + } + + public Builder dp(BigInteger dp) { + this.dp = dp; + return this; + } + + public Builder dq(BigInteger dq) { + this.dq = dq; + return this; + } + + public Builder qi(BigInteger qi) { + this.qi = qi; + return this; + } + + public RSAKeyPair build() { + return new RSAKeyPair(keyId, use, n, e, d, p, q, dp, dq, qi); + } + } } diff --git a/src/main/java/net/tokensmith/jwt/entity/jwk/RSAPublicKey.java b/src/main/java/net/tokensmith/jwt/entity/jwk/RSAPublicKey.java index e0aebcc..3c3efc7 100644 --- a/src/main/java/net/tokensmith/jwt/entity/jwk/RSAPublicKey.java +++ b/src/main/java/net/tokensmith/jwt/entity/jwk/RSAPublicKey.java @@ -10,8 +10,8 @@ public class RSAPublicKey extends Key { private BigInteger n; // modulus private BigInteger e; // public exponent - public RSAPublicKey(Optional keyId, KeyType keyType, Use use, BigInteger n, BigInteger e) { - super(keyId, keyType, use); + public RSAPublicKey(Optional keyId, Use use, BigInteger n, BigInteger e) { + super(keyId, KeyType.RSA, use); this.n = n; this.e = e; } @@ -31,4 +31,35 @@ public BigInteger getE() { public void setE(BigInteger e) { this.e = e; } + + public static class Builder { + protected Optional keyId = Optional.empty(); + private Use use; + private BigInteger n; // modulus + private BigInteger e; // public exponent + + public Builder keyId(Optional keyId) { + this.keyId = keyId; + return this; + } + + public Builder use(Use use) { + this.use = use; + return this; + } + + public Builder n(BigInteger n) { + this.n = n; + return this; + } + + public Builder e(BigInteger e) { + this.e = e; + return this; + } + + public RSAPublicKey build() { + return new RSAPublicKey(keyId, use, n, e); + } + } } diff --git a/src/main/java/net/tokensmith/jwt/entity/jwk/SymmetricKey.java b/src/main/java/net/tokensmith/jwt/entity/jwk/SymmetricKey.java index 3d717ee..c85c006 100644 --- a/src/main/java/net/tokensmith/jwt/entity/jwk/SymmetricKey.java +++ b/src/main/java/net/tokensmith/jwt/entity/jwk/SymmetricKey.java @@ -3,11 +3,18 @@ import java.util.Optional; /** - * Created by tommackenzie on 11/4/15. + * Represents a symmetric key. */ public class SymmetricKey extends Key { private String key; + /** + * Construct a Symmetric Key. + * + * @param keyId the id of the key + * @param key the base64, url encoded, without padding symmetric key value + * @param use how the key will be used, sign, encrypt. + */ public SymmetricKey(Optional keyId, String key, Use use) { super(keyId, KeyType.OCT, use); this.key = key; @@ -20,4 +27,29 @@ public String getKey() { public void setKey(String key) { this.key = key; } + + public static class Builder { + protected Optional keyId = Optional.empty(); + private Use use; + private String key; + + public Builder keyId(Optional keyId) { + this.keyId = keyId; + return this; + } + + public Builder use(Use use) { + this.use = use; + return this; + } + + public Builder key(String key) { + this.key = key; + return this; + } + + public SymmetricKey build() { + return new SymmetricKey(keyId, key, use); + } + } } diff --git a/src/main/java/net/tokensmith/jwt/entity/jwt/JsonWebToken.java b/src/main/java/net/tokensmith/jwt/entity/jwt/JsonWebToken.java index a0d8339..ae8a6d1 100644 --- a/src/main/java/net/tokensmith/jwt/entity/jwt/JsonWebToken.java +++ b/src/main/java/net/tokensmith/jwt/entity/jwt/JsonWebToken.java @@ -8,20 +8,20 @@ /** * Created by tommackenzie on 8/9/15. */ -public class JsonWebToken { +public class JsonWebToken { private Header header; - private Claims claims; + private T claims; private Optional signature = Optional.empty(); private Optional jwt = Optional.empty(); public JsonWebToken() {} - public JsonWebToken(Header header, Claims claims) { + public JsonWebToken(Header header, T claims) { this.header = header; this.claims = claims; } - public JsonWebToken(Header header, Claims claims, Optional jwt) { + public JsonWebToken(Header header, T claims, Optional jwt) { this.header = header; this.claims = claims; this.jwt = jwt; @@ -35,11 +35,11 @@ public void setHeader(Header header) { this.header = header; } - public Claims getClaims() { + public T getClaims() { return claims; } - public void setClaims(Claims claims) { + public void setClaims(T claims) { this.claims = claims; } diff --git a/src/main/java/net/tokensmith/jwt/factory/SecureJwtFactory.java b/src/main/java/net/tokensmith/jwt/factory/SecureJwtFactory.java index c5de3c9..02dcf4c 100644 --- a/src/main/java/net/tokensmith/jwt/factory/SecureJwtFactory.java +++ b/src/main/java/net/tokensmith/jwt/factory/SecureJwtFactory.java @@ -22,13 +22,13 @@ public SecureJwtFactory(Signer signer, Algorithm algorithm, Optional key this.keyId = keyId; } - public JsonWebToken makeJwt(Claims claimNames) throws JwtToJsonException { + public JsonWebToken makeJwt(T claimNames) throws JwtToJsonException { Header header = new Header(); header.setAlgorithm(algorithm); header.setType(Optional.of(TokenType.JWT)); header.setKeyId(keyId); - JsonWebToken jwt = new JsonWebToken(); + JsonWebToken jwt = new JsonWebToken<>(); jwt.setHeader(header); jwt.setClaims(claimNames); diff --git a/src/main/java/net/tokensmith/jwt/factory/UnSecureJwtFactory.java b/src/main/java/net/tokensmith/jwt/factory/UnSecureJwtFactory.java index 91420ff..4acf92a 100644 --- a/src/main/java/net/tokensmith/jwt/factory/UnSecureJwtFactory.java +++ b/src/main/java/net/tokensmith/jwt/factory/UnSecureJwtFactory.java @@ -13,11 +13,11 @@ */ public class UnSecureJwtFactory { - public JsonWebToken makeJwt(Claims claimNames) { + public JsonWebToken makeJwt(T claimNames) { Header header = new Header(); header.setAlgorithm(Algorithm.NONE); - JsonWebToken jwt = new JsonWebToken(); + JsonWebToken jwt = new JsonWebToken(); jwt.setHeader(header); jwt.setClaims(claimNames); jwt.setSignature(Optional.empty()); diff --git a/src/main/java/net/tokensmith/jwt/jwe/serialization/direct/JweDirectDesializer.java b/src/main/java/net/tokensmith/jwt/jwe/serialization/direct/JweDirectDesializer.java index b1fa9a7..db5ea6d 100644 --- a/src/main/java/net/tokensmith/jwt/jwe/serialization/direct/JweDirectDesializer.java +++ b/src/main/java/net/tokensmith/jwt/jwe/serialization/direct/JweDirectDesializer.java @@ -43,7 +43,7 @@ public JWE stringToJWE(String compactJWE, Key key) throws JsonToJwtException, De Header header; try { - header = (Header) serdes.jsonBytesToObject(protectedHeader, Header.class); + header = serdes.jsonBytesTo(protectedHeader, Header.class); } catch (JsonException e) { throw new JsonToJwtException(COMPACT_JWE_INVALID, e); } diff --git a/src/main/java/net/tokensmith/jwt/jwe/serialization/rsa/JweRsaDeserializer.java b/src/main/java/net/tokensmith/jwt/jwe/serialization/rsa/JweRsaDeserializer.java index 41c8d36..1a2b353 100644 --- a/src/main/java/net/tokensmith/jwt/jwe/serialization/rsa/JweRsaDeserializer.java +++ b/src/main/java/net/tokensmith/jwt/jwe/serialization/rsa/JweRsaDeserializer.java @@ -14,7 +14,7 @@ import net.tokensmith.jwt.serialization.exception.JsonToJwtException; import net.tokensmith.jwt.jwe.serialization.JweDeserializer; import net.tokensmith.jwt.jwe.serialization.exception.KeyException; -import net.tokensmith.jwt.jwk.PrivateKeyFactory; +import net.tokensmith.jwt.jwk.PrivateKeyTranslator; import net.tokensmith.jwt.jws.signer.factory.rsa.exception.PrivateKeyException; @@ -28,14 +28,14 @@ public class JweRsaDeserializer implements JweDeserializer { private Serdes serdes; private Base64.Decoder decoder; - private PrivateKeyFactory privateKeyFactory; + private PrivateKeyTranslator privateKeyTranslator; private CipherRSAFactory cipherRSAFactory; private CipherSymmetricFactory cipherSymmetricFactory; - public JweRsaDeserializer(Serdes serdes, Base64.Decoder decoder, PrivateKeyFactory privateKeyFactory, CipherRSAFactory cipherRSAFactory, CipherSymmetricFactory cipherSymmetricFactory) { + public JweRsaDeserializer(Serdes serdes, Base64.Decoder decoder, PrivateKeyTranslator privateKeyTranslator, CipherRSAFactory cipherRSAFactory, CipherSymmetricFactory cipherSymmetricFactory) { this.serdes = serdes; this.decoder = decoder; - this.privateKeyFactory = privateKeyFactory; + this.privateKeyTranslator = privateKeyTranslator; this.cipherRSAFactory = cipherRSAFactory; this.cipherSymmetricFactory = cipherSymmetricFactory; } @@ -50,7 +50,7 @@ public JWE stringToJWE(String compactJWE, Key key) throws JsonToJwtException, De Header header; try { - header = (Header) serdes.jsonBytesToObject(protectedHeader, Header.class); + header = serdes.jsonBytesTo(protectedHeader, Header.class); } catch (JsonException e) { throw new JsonToJwtException(COMPACT_JWE_INVALID, e); } @@ -58,7 +58,7 @@ public JWE stringToJWE(String compactJWE, Key key) throws JsonToJwtException, De RSAKeyPair keyPair = (RSAKeyPair) key; RSAPrivateCrtKey jdkKey; try { - jdkKey = privateKeyFactory.makePrivateKey(keyPair); + jdkKey = privateKeyTranslator.to(keyPair); } catch (PrivateKeyException e) { throw new KeyException("", e); } diff --git a/src/main/java/net/tokensmith/jwt/jwe/serialization/rsa/JweRsaSerializer.java b/src/main/java/net/tokensmith/jwt/jwe/serialization/rsa/JweRsaSerializer.java index eca7e1e..dcc60a1 100644 --- a/src/main/java/net/tokensmith/jwt/jwe/serialization/rsa/JweRsaSerializer.java +++ b/src/main/java/net/tokensmith/jwt/jwe/serialization/rsa/JweRsaSerializer.java @@ -10,7 +10,7 @@ import net.tokensmith.jwt.serialization.exception.JsonException; import net.tokensmith.jwt.serialization.exception.JsonToJwtException; import net.tokensmith.jwt.jwk.KeyAlgorithm; -import net.tokensmith.jwt.jwk.SecretKeyFactory; +import net.tokensmith.jwt.jwk.generator.jdk.SecretKeyGenerator; import net.tokensmith.jwt.jwk.exception.SecretKeyException; import javax.crypto.BadPaddingException; @@ -30,14 +30,14 @@ public class JweRsaSerializer implements JweSerializer { private Serdes serdes; private Base64.Encoder encoder; private Cipher RSAEncryptCipher; - private SecretKeyFactory secretKeyFactory; + private SecretKeyGenerator secretKeyGenerator; private CipherSymmetricFactory cipherSymmetricFactory; - public JweRsaSerializer(Serdes serdes, Base64.Encoder encoder, Cipher RSAEncryptCipher, SecretKeyFactory secretKeyFactory, CipherSymmetricFactory cipherSymmetricFactory) { + public JweRsaSerializer(Serdes serdes, Base64.Encoder encoder, Cipher RSAEncryptCipher, SecretKeyGenerator secretKeyGenerator, CipherSymmetricFactory cipherSymmetricFactory) { this.serdes = serdes; this.encoder = encoder; this.RSAEncryptCipher = RSAEncryptCipher; - this.secretKeyFactory = secretKeyFactory; + this.secretKeyGenerator = secretKeyGenerator; this.cipherSymmetricFactory = cipherSymmetricFactory; } @@ -55,7 +55,7 @@ public ByteArrayOutputStream JWEToCompact(JWE jwe) throws JsonToJwtException, Ci SecretKey cek; try { - cek = secretKeyFactory.makeKey(KeyAlgorithm.AES); + cek = secretKeyGenerator.makeKey(KeyAlgorithm.AES); } catch (SecretKeyException e) { throw new EncryptException(FAILED_TO_CREATE_CONTENT_ENCRYPTION_KEY, e); } diff --git a/src/main/java/net/tokensmith/jwt/jwk/PrivateKeyFactory.java b/src/main/java/net/tokensmith/jwt/jwk/PrivateKeyTranslator.java similarity index 63% rename from src/main/java/net/tokensmith/jwt/jwk/PrivateKeyFactory.java rename to src/main/java/net/tokensmith/jwt/jwk/PrivateKeyTranslator.java index 93de359..074cff4 100644 --- a/src/main/java/net/tokensmith/jwt/jwk/PrivateKeyFactory.java +++ b/src/main/java/net/tokensmith/jwt/jwk/PrivateKeyTranslator.java @@ -1,9 +1,9 @@ package net.tokensmith.jwt.jwk; import net.tokensmith.jwt.entity.jwk.RSAKeyPair; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import net.tokensmith.jwt.jws.signer.factory.rsa.exception.PrivateKeyException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.security.KeyFactory; import java.security.interfaces.RSAPrivateCrtKey; @@ -12,12 +12,12 @@ import java.security.spec.RSAPrivateKeySpec; -public class PrivateKeyFactory { - private static final Logger LOGGER = LogManager.getLogger(PrivateKeyFactory.class); +public class PrivateKeyTranslator { + private static final Logger LOGGER = LoggerFactory.getLogger(PrivateKeyTranslator.class); public static final String PRIVATE_KEY_ERROR_MSG = "Could not make RSAPrivateCrtKey"; private KeyFactory RSAKeyFactory; - public PrivateKeyFactory(KeyFactory RSAKeyFactory) { + public PrivateKeyTranslator(KeyFactory RSAKeyFactory) { this.RSAKeyFactory = RSAKeyFactory; } @@ -25,22 +25,22 @@ public PrivateKeyFactory(KeyFactory RSAKeyFactory) { * Returns a, RSAPrivateCrtKey, which is built from the input parameter, jwk. * A RSAPrivateCrtKey is needed per, https://tools.ietf.org/html/rfc7517#section-9.3 * - * @param jwk a RSAKeyPair + * @param from a RSAKeyPair * @return an instance of RSAPrivateCrtKey * @throws PrivateKeyException if jwk is invalid. */ - public RSAPrivateCrtKey makePrivateKey(RSAKeyPair jwk) throws PrivateKeyException { + public RSAPrivateCrtKey to(RSAKeyPair from) throws PrivateKeyException { RSAPrivateKeySpec keySpec; keySpec = new RSAPrivateCrtKeySpec( - jwk.getN(), // modulus - jwk.getE(), // publicExponent - jwk.getD(), // privateExponent - jwk.getP(), // primeP - jwk.getQ(), // primeQ - jwk.getDp(), // primeExponentP - jwk.getDq(), // primeExponentQ - jwk.getQi() // crtCoefficient + from.getN(), // modulus + from.getE(), // publicExponent + from.getD(), // privateExponent + from.getP(), // primeP + from.getQ(), // primeQ + from.getDp(), // primeExponentP + from.getDq(), // primeExponentQ + from.getQi() // crtCoefficient ); RSAPrivateCrtKey privateKey; diff --git a/src/main/java/net/tokensmith/jwt/jwk/PublicKeyFactory.java b/src/main/java/net/tokensmith/jwt/jwk/PublicKeyTranslator.java similarity index 62% rename from src/main/java/net/tokensmith/jwt/jwk/PublicKeyFactory.java rename to src/main/java/net/tokensmith/jwt/jwk/PublicKeyTranslator.java index 0750d97..6bdb382 100644 --- a/src/main/java/net/tokensmith/jwt/jwk/PublicKeyFactory.java +++ b/src/main/java/net/tokensmith/jwt/jwk/PublicKeyTranslator.java @@ -7,16 +7,22 @@ import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; -public class PublicKeyFactory { +public class PublicKeyTranslator { private KeyFactory RSAKeyFactory; - public PublicKeyFactory(KeyFactory RSAKeyFactory) { + public PublicKeyTranslator(KeyFactory RSAKeyFactory) { this.RSAKeyFactory = RSAKeyFactory; } - public java.security.interfaces.RSAPublicKey makePublicKey(RSAPublicKey jwk) throws PublicKeyException { + /** + * Translate net.tokensmith.jwt.entity.jwk.RSAPublicKey to a, java.security.interfaces.RSAPublicKey + * @param from the tokensmith PublicKey (Json Web Key) + * @return its translated instance to java.security.interfaces.RSAPublicKey + * @throws PublicKeyException if there was a problem with the translation. + */ + public java.security.interfaces.RSAPublicKey to(RSAPublicKey from) throws PublicKeyException { - RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(jwk.getN(), jwk.getE()); + RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(from.getN(), from.getE()); java.security.interfaces.RSAPublicKey publicKey = null; try { publicKey = (java.security.interfaces.RSAPublicKey) RSAKeyFactory.generatePublic(rsaPublicKeySpec); diff --git a/src/main/java/net/tokensmith/jwt/jwk/generator/KeyGenerator.java b/src/main/java/net/tokensmith/jwt/jwk/generator/KeyGenerator.java new file mode 100644 index 0000000..35cbcd1 --- /dev/null +++ b/src/main/java/net/tokensmith/jwt/jwk/generator/KeyGenerator.java @@ -0,0 +1,91 @@ +package net.tokensmith.jwt.jwk.generator; + +import net.tokensmith.jwt.entity.jwk.RSAKeyPair; +import net.tokensmith.jwt.entity.jwk.SymmetricKey; +import net.tokensmith.jwt.entity.jwk.Use; +import net.tokensmith.jwt.jwk.KeyAlgorithm; +import net.tokensmith.jwt.jwk.exception.SecretKeyException; +import net.tokensmith.jwt.jwk.generator.exception.KeyGenerateException; +import net.tokensmith.jwt.jwk.generator.jdk.RSAPrivateCrtKeyGenerator; +import net.tokensmith.jwt.jwk.generator.jdk.SecretKeyGenerator; + +import javax.crypto.SecretKey; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.spec.InvalidKeySpecException; +import java.util.Base64; +import java.util.Optional; +import java.util.UUID; + +/** + * Generates keys + * + */ +public class KeyGenerator { + public static int RSA_1024 = 1024; + public static int RSA_2048 = 2048; + public static int RSA_4096 = 4096; + + private SecretKeyGenerator secretKeyGenerator; + private RSAPrivateCrtKeyGenerator rsaKeyGenerator; + + public KeyGenerator(SecretKeyGenerator secretKeyGenerator, RSAPrivateCrtKeyGenerator rsaKeyGenerator) { + this.secretKeyGenerator = secretKeyGenerator; + this.rsaKeyGenerator = rsaKeyGenerator; + } + + private SecretKey secretKey() throws SecretKeyException { + return secretKeyGenerator.makeKey(KeyAlgorithm.AES); + } + + public SymmetricKey symmetricKey(Optional keyId, Use use) throws KeyGenerateException { + SecretKey secretKey = null; + try { + secretKey = secretKey(); + } catch (SecretKeyException e) { + throw new KeyGenerateException("Could not generate secret key", e); + } + + return translate(secretKey, keyId, use); + } + + public RSAKeyPair rsaKeyPair(int keySize, Optional keyId, Use use) throws KeyGenerateException { + RSAPrivateCrtKey jdkKey; + try { + jdkKey = rsaKeyGenerator.generate(keySize); + } catch (InvalidKeySpecException e) { + throw new KeyGenerateException("Could not generate RSA key pair", e); + + } + return translate(jdkKey, keyId, use); + } + + private SymmetricKey translate(SecretKey from, Optional keyId, Use use) { + String encodedKey = Base64 + .getUrlEncoder() + .withoutPadding() + .encodeToString(from.getEncoded()); + + return new SymmetricKey.Builder() + .keyId(keyId) + .use(use) + .key(encodedKey) + .build(); + } + + private RSAKeyPair translate(RSAPrivateCrtKey from, Optional keyId, Use use) { + return new RSAKeyPair.Builder() + .keyId(keyId) + .use(use) + .n(from.getModulus()) + .e(from.getPublicExponent()) + .d(from.getPrivateExponent()) + .p(from.getPrimeP()) + .q(from.getPrimeQ()) + .dp(from.getPrimeExponentP()) + .dq(from.getPrimeExponentQ()) + .qi(from.getCrtCoefficient()) + .build(); + } +} diff --git a/src/main/java/net/tokensmith/jwt/jwk/generator/exception/KeyGenerateException.java b/src/main/java/net/tokensmith/jwt/jwk/generator/exception/KeyGenerateException.java new file mode 100644 index 0000000..4efa0b0 --- /dev/null +++ b/src/main/java/net/tokensmith/jwt/jwk/generator/exception/KeyGenerateException.java @@ -0,0 +1,7 @@ +package net.tokensmith.jwt.jwk.generator.exception; + +public class KeyGenerateException extends Exception { + public KeyGenerateException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/net/tokensmith/jwt/jwk/generator/jdk/RSAPrivateCrtKeyGenerator.java b/src/main/java/net/tokensmith/jwt/jwk/generator/jdk/RSAPrivateCrtKeyGenerator.java new file mode 100644 index 0000000..fa0ac1c --- /dev/null +++ b/src/main/java/net/tokensmith/jwt/jwk/generator/jdk/RSAPrivateCrtKeyGenerator.java @@ -0,0 +1,53 @@ +package net.tokensmith.jwt.jwk.generator.jdk; + +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.RSAPrivateCrtKeySpec; + +public class RSAPrivateCrtKeyGenerator { + private KeyPairGenerator keyPairGenerator; + private KeyFactory keyFactory; + + + public RSAPrivateCrtKeyGenerator(KeyPairGenerator keyPairGenerator, KeyFactory keyFactory) { + this.keyPairGenerator = keyPairGenerator; + this.keyFactory = keyFactory; + } + + protected synchronized PrivateKey makePrivateKey(int keySize) { + + // not thread safe so its synchronized ^ + keyPairGenerator.initialize(keySize); + KeyPair keyPair = keyPairGenerator.genKeyPair(); + + return keyPair.getPrivate(); + } + + protected RSAPrivateCrtKey makeRSAPrivateCrtKey(PrivateKey privateKey) throws InvalidKeySpecException{ + + RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = null; + try { + rsaPrivateCrtKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateCrtKeySpec.class); + } catch (InvalidKeySpecException e) { + throw e; + } + + RSAPrivateCrtKey rsaPrivateCrtKey = null; + try { + rsaPrivateCrtKey = (RSAPrivateCrtKey) keyFactory.generatePrivate(rsaPrivateCrtKeySpec); + } catch (InvalidKeySpecException e) { + throw e; + } + + return rsaPrivateCrtKey; + } + + public RSAPrivateCrtKey generate(int keySize) throws InvalidKeySpecException { + PrivateKey privateKey = makePrivateKey(keySize); + return makeRSAPrivateCrtKey(privateKey); + } +} diff --git a/src/main/java/net/tokensmith/jwt/jwk/SecretKeyFactory.java b/src/main/java/net/tokensmith/jwt/jwk/generator/jdk/SecretKeyGenerator.java similarity index 80% rename from src/main/java/net/tokensmith/jwt/jwk/SecretKeyFactory.java rename to src/main/java/net/tokensmith/jwt/jwk/generator/jdk/SecretKeyGenerator.java index 34f3790..6177ba0 100644 --- a/src/main/java/net/tokensmith/jwt/jwk/SecretKeyFactory.java +++ b/src/main/java/net/tokensmith/jwt/jwk/generator/jdk/SecretKeyGenerator.java @@ -1,5 +1,6 @@ -package net.tokensmith.jwt.jwk; +package net.tokensmith.jwt.jwk.generator.jdk; +import net.tokensmith.jwt.jwk.KeyAlgorithm; import net.tokensmith.jwt.jwk.exception.SecretKeyException; import javax.crypto.KeyGenerator; @@ -7,9 +8,9 @@ import java.security.NoSuchAlgorithmException; -public class SecretKeyFactory { +public class SecretKeyGenerator { public static final String MESSAGE = "Could not construct key generator"; - private static int keySize = 256; + private static int KEY_SIZE = 256; public SecretKey makeKey(KeyAlgorithm keyAlgorithm) throws SecretKeyException { // docs say KeyGenerators can be reused as long as they use the same init values. @@ -21,7 +22,7 @@ public SecretKey makeKey(KeyAlgorithm keyAlgorithm) throws SecretKeyException { throw new SecretKeyException(MESSAGE, e); } - keyGenerator.init(keySize); + keyGenerator.init(KEY_SIZE); return keyGenerator.generateKey(); } diff --git a/src/main/java/net/tokensmith/jwt/jws/serialization/SecureJwtSerializer.java b/src/main/java/net/tokensmith/jwt/jws/serialization/SecureJwtSerializer.java index 8893f8a..4a509d9 100644 --- a/src/main/java/net/tokensmith/jwt/jws/serialization/SecureJwtSerializer.java +++ b/src/main/java/net/tokensmith/jwt/jws/serialization/SecureJwtSerializer.java @@ -23,8 +23,8 @@ public String compactJwtToString(Claims claims) throws JwtToJsonException { return compactJwt(claims).toString(); } - public ByteArrayOutputStream compactJwt(Claims claims) throws JwtToJsonException { - JsonWebToken jsonWebToken; + public ByteArrayOutputStream compactJwt(T claims) throws JwtToJsonException { + JsonWebToken jsonWebToken; try { jsonWebToken = secureJwtFactory.makeJwt(claims); } catch (JwtToJsonException e) { diff --git a/src/main/java/net/tokensmith/jwt/jws/signer/Signer.java b/src/main/java/net/tokensmith/jwt/jws/signer/Signer.java index 0a9f5b4..847f3a1 100644 --- a/src/main/java/net/tokensmith/jwt/jws/signer/Signer.java +++ b/src/main/java/net/tokensmith/jwt/jws/signer/Signer.java @@ -1,5 +1,6 @@ package net.tokensmith.jwt.jws.signer; +import net.tokensmith.jwt.entity.jwt.Claims; import net.tokensmith.jwt.entity.jwt.JsonWebToken; import net.tokensmith.jwt.serialization.JwtSerde; import net.tokensmith.jwt.serialization.exception.JwtToJsonException; @@ -18,7 +19,7 @@ public Signer(JwtSerde jwtSerde, Encoder encoder) { this.encoder = encoder; } - public byte[] run(JsonWebToken jwt) throws JwtToJsonException { + public byte[] run(JsonWebToken jwt) throws JwtToJsonException { byte[] signInput = jwtSerde.makeSignInput(jwt.getHeader(), jwt.getClaims()); return run(signInput); } diff --git a/src/main/java/net/tokensmith/jwt/jws/signer/factory/SignerFactory.java b/src/main/java/net/tokensmith/jwt/jws/signer/factory/SignerFactory.java index f45f942..99c521b 100644 --- a/src/main/java/net/tokensmith/jwt/jws/signer/factory/SignerFactory.java +++ b/src/main/java/net/tokensmith/jwt/jws/signer/factory/SignerFactory.java @@ -45,21 +45,21 @@ public Signer makeSigner(Algorithm alg, Key jwk) throws InvalidAlgorithmExceptio Signer signer = null; if (jwk.getKeyType() == KeyType.OCT) { - signer = makeMacSigner(alg, jwk); + signer = makeMacSigner(alg, (SymmetricKey) jwk); } else if ( jwk.getKeyType() == KeyType.RSA) { signer = makeRSASigner(alg, (RSAKeyPair) jwk); } return signer; } - public Signer makeMacSigner(Algorithm alg, Key key) throws InvalidAlgorithmException, InvalidJsonWebKeyException { + public Signer makeMacSigner(Algorithm alg, SymmetricKey key) throws InvalidAlgorithmException, InvalidJsonWebKeyException { Mac mac; SignAlgorithm signAlgorithm = SignAlgorithm.valueOf(alg.getValue()); try { - mac = macFactory.makeMac(signAlgorithm, (SymmetricKey) key); + mac = macFactory.makeMac(signAlgorithm, key); } catch (SecurityKeyException e) { - throw new InvalidJsonWebKeyException("", e); + throw new InvalidJsonWebKeyException("jwk is invalid", e); } catch (InvalidAlgorithmException e) { throw e; } @@ -74,9 +74,7 @@ private Signer makeRSASigner(Algorithm alg, RSAKeyPair keyPair) throws InvalidAl try { signature = privateKeySignatureFactory.makeSignature(signAlgorithm, keyPair); - } catch (PrivateKeyException e) { - throw new InvalidJsonWebKeyException("", e); - } catch (RSAPrivateKeyException e) { + } catch (PrivateKeyException | RSAPrivateKeyException e) { throw new InvalidJsonWebKeyException("", e); } catch (InvalidAlgorithmException e) { throw e; diff --git a/src/main/java/net/tokensmith/jwt/jws/signer/factory/hmac/MacFactory.java b/src/main/java/net/tokensmith/jwt/jws/signer/factory/hmac/MacFactory.java index 41b1921..745e047 100644 --- a/src/main/java/net/tokensmith/jwt/jws/signer/factory/hmac/MacFactory.java +++ b/src/main/java/net/tokensmith/jwt/jws/signer/factory/hmac/MacFactory.java @@ -27,7 +27,12 @@ public Key makeKey(SignAlgorithm alg, SymmetricKey jwk) { } public Mac makeMac(SignAlgorithm alg, SymmetricKey jwk) throws InvalidAlgorithmException, SecurityKeyException { - java.security.Key securityKey = makeKey(alg, jwk); + java.security.Key securityKey; + try { + securityKey = makeKey(alg, jwk); + } catch (IllegalArgumentException e) { + throw new SecurityKeyException("Inappropriate key for SecretKeySpec", e); + } Mac mac; try { diff --git a/src/main/java/net/tokensmith/jwt/jws/signer/factory/rsa/PublicKeySignatureFactory.java b/src/main/java/net/tokensmith/jwt/jws/signer/factory/rsa/PublicKeySignatureFactory.java index bf62016..4bfbc51 100644 --- a/src/main/java/net/tokensmith/jwt/jws/signer/factory/rsa/PublicKeySignatureFactory.java +++ b/src/main/java/net/tokensmith/jwt/jws/signer/factory/rsa/PublicKeySignatureFactory.java @@ -3,6 +3,7 @@ import net.tokensmith.jwt.entity.jwk.RSAPublicKey; import net.tokensmith.jwt.jws.signer.SignAlgorithm; import net.tokensmith.jwt.jws.signer.factory.exception.InvalidAlgorithmException; +import net.tokensmith.jwt.jws.signer.factory.exception.InvalidJsonWebKeyException; import net.tokensmith.jwt.jws.signer.factory.rsa.exception.PublicKeyException; import net.tokensmith.jwt.jws.signer.factory.rsa.exception.RSAPublicKeyException; @@ -35,8 +36,13 @@ public java.security.interfaces.RSAPublicKey makePublicKey(RSAPublicKey jwk) thr return publicKey; } - public Signature makeSignature(SignAlgorithm alg, RSAPublicKey jwk) throws PublicKeyException, InvalidAlgorithmException, RSAPublicKeyException { - java.security.interfaces.RSAPublicKey securityPublicKey = makePublicKey(jwk); + public Signature makeSignature(SignAlgorithm alg, RSAPublicKey jwk) throws InvalidAlgorithmException, RSAPublicKeyException, InvalidJsonWebKeyException { + java.security.PublicKey securityPublicKey; + try { + securityPublicKey = makePublicKey(jwk); + } catch (PublicKeyException e) { + throw new InvalidJsonWebKeyException("jwk is invalid", e); + } Signature signature; try { diff --git a/src/main/java/net/tokensmith/jwt/jws/verifier/VerifyMacSignature.java b/src/main/java/net/tokensmith/jwt/jws/verifier/VerifyMacSignature.java index cfac2e1..55dfaf0 100644 --- a/src/main/java/net/tokensmith/jwt/jws/verifier/VerifyMacSignature.java +++ b/src/main/java/net/tokensmith/jwt/jws/verifier/VerifyMacSignature.java @@ -1,5 +1,6 @@ package net.tokensmith.jwt.jws.verifier; +import net.tokensmith.jwt.entity.jwt.Claims; import net.tokensmith.jwt.entity.jwt.JsonWebToken; import net.tokensmith.jwt.jws.signer.Signer; @@ -16,7 +17,7 @@ public VerifyMacSignature(Signer macSigner) { } @Override - public boolean run(JsonWebToken token) { + public boolean run(JsonWebToken token) { byte[] generatedSignature = null; byte[] actualSignature = null; diff --git a/src/main/java/net/tokensmith/jwt/jws/verifier/VerifyRsaSignature.java b/src/main/java/net/tokensmith/jwt/jws/verifier/VerifyRsaSignature.java index 330bad3..9a618c7 100644 --- a/src/main/java/net/tokensmith/jwt/jws/verifier/VerifyRsaSignature.java +++ b/src/main/java/net/tokensmith/jwt/jws/verifier/VerifyRsaSignature.java @@ -1,5 +1,6 @@ package net.tokensmith.jwt.jws.verifier; +import net.tokensmith.jwt.entity.jwt.Claims; import net.tokensmith.jwt.entity.jwt.JsonWebToken; import java.security.Signature; @@ -19,7 +20,7 @@ public VerifyRsaSignature(Signature signature, Base64.Decoder decoder) { } @Override - public boolean run(JsonWebToken token) { + public boolean run(JsonWebToken token) { boolean isVerified = false; diff --git a/src/main/java/net/tokensmith/jwt/jws/verifier/VerifySignature.java b/src/main/java/net/tokensmith/jwt/jws/verifier/VerifySignature.java index 327accc..73f537f 100644 --- a/src/main/java/net/tokensmith/jwt/jws/verifier/VerifySignature.java +++ b/src/main/java/net/tokensmith/jwt/jws/verifier/VerifySignature.java @@ -1,5 +1,6 @@ package net.tokensmith.jwt.jws.verifier; +import net.tokensmith.jwt.entity.jwt.Claims; import net.tokensmith.jwt.entity.jwt.JsonWebToken; import java.nio.charset.Charset; @@ -14,5 +15,5 @@ protected byte[] createSignInput(String input) { return (inputParts[0] + "." + inputParts[1]).getBytes(Charset.forName("UTF-8")); } - public abstract boolean run(JsonWebToken token); + public abstract boolean run(JsonWebToken token); } diff --git a/src/main/java/net/tokensmith/jwt/jws/verifier/factory/VerifySignatureFactory.java b/src/main/java/net/tokensmith/jwt/jws/verifier/factory/VerifySignatureFactory.java index ab1b00e..e46830c 100644 --- a/src/main/java/net/tokensmith/jwt/jws/verifier/factory/VerifySignatureFactory.java +++ b/src/main/java/net/tokensmith/jwt/jws/verifier/factory/VerifySignatureFactory.java @@ -3,6 +3,7 @@ import net.tokensmith.jwt.entity.jwk.Key; import net.tokensmith.jwt.entity.jwk.KeyType; import net.tokensmith.jwt.entity.jwk.RSAPublicKey; +import net.tokensmith.jwt.entity.jwk.SymmetricKey; import net.tokensmith.jwt.entity.jwt.header.Algorithm; import net.tokensmith.jwt.exception.SignatureException; import net.tokensmith.jwt.jws.signer.SignAlgorithm; @@ -40,14 +41,14 @@ public VerifySignature makeVerifySignature(Algorithm algorithm, Key key) throws VerifySignature verifySignature = null; if (key.getKeyType() == KeyType.OCT) { - verifySignature = makeVerifyMacSignature(algorithm, key); + verifySignature = makeVerifyMacSignature(algorithm, (SymmetricKey) key); } else if (key.getKeyType() == KeyType.RSA){ verifySignature = makeVerifyRsaSignature(algorithm, (RSAPublicKey) key); } return verifySignature; } - private VerifySignature makeVerifyMacSignature(Algorithm algorithm, Key key) throws SignatureException { + private VerifySignature makeVerifyMacSignature(Algorithm algorithm, SymmetricKey key) throws SignatureException { Signer macSigner; try { macSigner = signerFactory.makeMacSigner(algorithm, key); @@ -67,12 +68,10 @@ private VerifySignature makeVerifyRsaSignature(Algorithm algorithm, RSAPublicKey try { signature = publicKeySignatureFactory.makeSignature(signAlgorithm, key); - } catch (PublicKeyException e) { - throw new SignatureException(KEY_WAS_INVALID, e); - } catch (RSAPublicKeyException e) { - throw new SignatureException(KEY_WAS_INVALID, e); } catch (InvalidAlgorithmException e) { throw new SignatureException(ALG_WAS_INVALID, e); + } catch (InvalidJsonWebKeyException | RSAPublicKeyException e) { + throw new SignatureException(KEY_WAS_INVALID, e); } return new VerifyRsaSignature(signature, decoder); diff --git a/src/main/java/net/tokensmith/jwt/serialization/HeaderDeserializer.java b/src/main/java/net/tokensmith/jwt/serialization/HeaderDeserializer.java index c539cd1..0bbbaca 100644 --- a/src/main/java/net/tokensmith/jwt/serialization/HeaderDeserializer.java +++ b/src/main/java/net/tokensmith/jwt/serialization/HeaderDeserializer.java @@ -31,7 +31,7 @@ public Header toHeader(String encodedJwt) throws JsonToJwtException, InvalidJWT Header header; try { - header = (Header) serdes.jsonBytesToObject(headerJson, Header.class); + header = serdes.jsonBytesTo(headerJson, Header.class); } catch (JsonException e) { throw new JsonToJwtException(INVALID_HEADER, e); } diff --git a/src/main/java/net/tokensmith/jwt/serialization/JwtSerde.java b/src/main/java/net/tokensmith/jwt/serialization/JwtSerde.java index ebad25c..5e569d3 100644 --- a/src/main/java/net/tokensmith/jwt/serialization/JwtSerde.java +++ b/src/main/java/net/tokensmith/jwt/serialization/JwtSerde.java @@ -37,7 +37,6 @@ public class JwtSerde { private Serdes serdes; private Encoder encoder; private Decoder decoder; - private final String DELIMITTER = "."; private final byte[] DELIMITER = ".".getBytes(); public JwtSerde(Serdes serdes, Encoder encoder, Decoder decoder) { @@ -77,7 +76,7 @@ protected List membersForSigning(Header header, Claims claims) throws Jw return members; } - public ByteArrayOutputStream compactJwt(JsonWebToken jwt) throws JwtToJsonException { + public ByteArrayOutputStream compactJwt(JsonWebToken jwt) throws JwtToJsonException { List members = membersForSigning(jwt.getHeader(), jwt.getClaims()); @@ -93,9 +92,9 @@ public ByteArrayOutputStream compactJwt(JsonWebToken jwt) throws JwtToJsonExcept return compactJwt; } - public JsonWebToken stringToJwt(String jwtAsText, Class claimClass) throws JsonToJwtException, InvalidJWT { + public JsonWebToken stringToJwt(String jwtAsText, Class claimClass) throws JsonToJwtException, InvalidJWT { String[] jwtParts = jwtAsText.split(JWT_SPLITTER); - JsonWebToken jwt; + JsonWebToken jwt; if (jwtParts.length == JWT_LENGTH) { jwt = jwt(jwtParts, claimClass, jwtAsText); @@ -110,26 +109,24 @@ public JsonWebToken stringToJwt(String jwtAsText, Class claimClass) throws JsonT return jwt; } - protected JsonWebToken jwt(String[] jwtParts, Class claimClass, String jwtAsText) throws JsonToJwtException { + protected JsonWebToken jwt(String[] jwtParts, Class claimClass, String jwtAsText) throws JsonToJwtException { byte[] headerJson = decoder.decode(jwtParts[0]); byte[] claimsJson = decoder.decode(jwtParts[1]); Header header; - Claims claim; + T claim; try { - header = (Header) serdes.jsonBytesToObject(headerJson, Header.class); - claim = (Claims) serdes.jsonBytesToObject(claimsJson, claimClass); + header = serdes.jsonBytesTo(headerJson, Header.class); + claim = serdes.jsonBytesTo(claimsJson, claimClass); } catch (JsonException e) { throw new JsonToJwtException(INVALID_JSON, e); } - JsonWebToken jwt = new JsonWebToken(header, claim, Optional.of(jwtAsText)); - - return jwt; + return new JsonWebToken(header, claim, Optional.of(jwtAsText)); } - protected JsonWebToken jws(String[] jwsParts, Class claimClass, String jwtAsText) throws JsonToJwtException { - JsonWebToken jwt = jwt(jwsParts, claimClass, jwtAsText); + protected JsonWebToken jws(String[] jwsParts, Class claimClass, String jwtAsText) throws JsonToJwtException { + JsonWebToken jwt = jwt(jwsParts, claimClass, jwtAsText); jwt.setSignature(Optional.of(jwsParts[JWS_LENGTH-1].getBytes())); return jwt; diff --git a/src/main/java/net/tokensmith/jwt/serialization/Serdes.java b/src/main/java/net/tokensmith/jwt/serialization/Serdes.java index d4c31cb..7c4b76f 100644 --- a/src/main/java/net/tokensmith/jwt/serialization/Serdes.java +++ b/src/main/java/net/tokensmith/jwt/serialization/Serdes.java @@ -28,8 +28,8 @@ public byte[] objectToByte(Object object) throws JsonException { } } - public Object jsonBytesToObject(byte[] json, Class c) throws JsonException { - Object object; + public T jsonBytesTo(byte[] json, Class c) throws JsonException { + T object; try { object = objectMapper.readValue(json, c); } catch (IOException e) { diff --git a/src/main/java/net/tokensmith/jwt/serialization/UnSecureJwtSerializer.java b/src/main/java/net/tokensmith/jwt/serialization/UnSecureJwtSerializer.java index d5f37fe..f168d99 100644 --- a/src/main/java/net/tokensmith/jwt/serialization/UnSecureJwtSerializer.java +++ b/src/main/java/net/tokensmith/jwt/serialization/UnSecureJwtSerializer.java @@ -21,9 +21,9 @@ public String compactJwtToString(Claims claims) { return compactJwt(claims).toString(); } - public ByteArrayOutputStream compactJwt(Claims claims) { + public ByteArrayOutputStream compactJwt(T claims) { - JsonWebToken jsonWebToken = unSecureJwtFactory.makeJwt(claims); + JsonWebToken jsonWebToken = unSecureJwtFactory.makeJwt(claims); ByteArrayOutputStream encodedJwt = null; try { diff --git a/src/test/java/examples/AsymmetricSignedJsonWebToken.java b/src/test/java/examples/AsymmetricSignedJsonWebToken.java index d600aed..063ec33 100644 --- a/src/test/java/examples/AsymmetricSignedJsonWebToken.java +++ b/src/test/java/examples/AsymmetricSignedJsonWebToken.java @@ -4,13 +4,14 @@ import net.tokensmith.jwt.builder.compact.SecureCompactBuilder; import net.tokensmith.jwt.builder.exception.CompactException; import net.tokensmith.jwt.config.JwtAppFactory; -import net.tokensmith.jwt.entity.jwk.KeyType; import net.tokensmith.jwt.entity.jwk.RSAKeyPair; import net.tokensmith.jwt.entity.jwk.RSAPublicKey; import net.tokensmith.jwt.entity.jwk.Use; import net.tokensmith.jwt.entity.jwt.JsonWebToken; import net.tokensmith.jwt.entity.jwt.header.Algorithm; import net.tokensmith.jwt.exception.SignatureException; +import net.tokensmith.jwt.jwk.generator.KeyGenerator; +import net.tokensmith.jwt.jwk.generator.exception.KeyGenerateException; import net.tokensmith.jwt.serialization.JwtSerde; import net.tokensmith.jwt.serialization.exception.JsonToJwtException; import net.tokensmith.jwt.jws.verifier.VerifySignature; @@ -24,23 +25,23 @@ */ public class AsymmetricSignedJsonWebToken { - public String toCompactJwt() { + public ByteArrayOutputStream toCompactJwt() throws KeyGenerateException { SecureCompactBuilder compactBuilder = new SecureCompactBuilder(); - RSAKeyPair keyPair = new RSAKeyPair( + JwtAppFactory jwtAppFactory = new JwtAppFactory(); + KeyGenerator keyGenerator = jwtAppFactory.keyGenerator(); + + RSAKeyPair keyPair; + try { + keyPair= keyGenerator.rsaKeyPair( + KeyGenerator.RSA_1024, Optional.of("test-key-id"), - KeyType.RSA, - Use.SIGNATURE, - new BigInteger("20446702916744654562596343388758805860065209639960173505037453331270270518732245089773723012043203236097095623402044690115755377345254696448759605707788965848889501746836211206270643833663949992536246985362693736387185145424787922241585721992924045675229348655595626434390043002821512765630397723028023792577935108185822753692574221566930937805031155820097146819964920270008811327036286786392793593121762425048860211859763441770446703722015857250621107855398693133264081150697423188751482418465308470313958250757758547155699749157985955379381294962058862159085915015369381046959790476428631998204940879604226680285601"), - new BigInteger("65537"), - new BigInteger("2358310989939619510179986262349936882924652023566213765118606431955566700506538911356936879137503597382515919515633242482643314423192704128296593672966061810149316320617894021822784026407461403384065351821972350784300967610143459484324068427674639688405917977442472804943075439192026107319532117557545079086537982987982522396626690057355718157403493216553255260857777965627529169195827622139772389760130571754834678679842181142252489617665030109445573978012707793010592737640499220015083392425914877847840457278246402760955883376999951199827706285383471150643561410605789710883438795588594095047409018233862167884701"), - new BigInteger("157377055902447438395586165028960291914931973278777532798470200156035267537359239071829408411909323208574959800537247728959718236884809685233284537349207654661530801859889389455120932077199406250387226339056140578989122526711937239401762061949364440402067108084155200696015505170135950332209194782224750221639"), - new BigInteger("129921752567406358990993347540064445018230073402482260994179328573323861908379211274626956543471664997237185298964648133324343327052852264060322088122401124781249085873464824282666514908127141915943024862618996371026577302203267804867959037802770797169483022132210859867700312376409633383772189122488119155159"), - new BigInteger("4922760648183732070600601771661330216909692924935440167185924139339187000497222028735680413269055839870281941362914961691371628021024152077883230870590287807744299308982303864732867094286567630701646611762288298013758658158894538059014178662376933683632720014228880806671525788467258162275185762295508460173"), - new BigInteger("95501022448116849078110281587424883261489167280943290677534750975651978631525094586933777934986404467352856624385049043666431411835209194330560695076194390729082708437497817187133629692908081460223069101908960299950170666285307890683263785145958472051553704139602453015343925544671829327400421727981791235189"), - new BigInteger("23545019917990284444784037831882732213707743418529123971725460465297450415859883707284136179135646366158633580054594447195052813412945775933274620822213099556720089770059982091144435545976515508108465724188242241967967709555336331874325396876783846248039429242763646988988076187339075374375350105207330456437") - ); + Use.SIGNATURE + ); + } catch (KeyGenerateException e) { + throw e; + } Claim claim = new Claim(); claim.setUriIsRoot(true); @@ -55,7 +56,7 @@ public String toCompactJwt() { e.printStackTrace(); } - return encodedJwt.toString(); + return encodedJwt; } public Boolean verifySignature() throws Exception { @@ -63,7 +64,6 @@ public Boolean verifySignature() throws Exception { RSAPublicKey publicKey = new RSAPublicKey( Optional.of("test-key-id"), - KeyType.RSA, Use.SIGNATURE, new BigInteger("20446702916744654562596343388758805860065209639960173505037453331270270518732245089773723012043203236097095623402044690115755377345254696448759605707788965848889501746836211206270643833663949992536246985362693736387185145424787922241585721992924045675229348655595626434390043002821512765630397723028023792577935108185822753692574221566930937805031155820097146819964920270008811327036286786392793593121762425048860211859763441770446703722015857250621107855398693133264081150697423188751482418465308470313958250757758547155699749157985955379381294962058862159085915015369381046959790476428631998204940879604226680285601"), new BigInteger("65537") @@ -71,7 +71,7 @@ public Boolean verifySignature() throws Exception { JwtAppFactory appFactory = new JwtAppFactory(); JwtSerde jwtSerde = appFactory.jwtSerde(); - JsonWebToken jsonWebToken; + JsonWebToken jsonWebToken; try { jsonWebToken = jwtSerde.stringToJwt(jwt, Claim.class); } catch (JsonToJwtException e) { diff --git a/src/test/java/examples/SymmetricSignedJsonWebToken.java b/src/test/java/examples/SymmetricSignedJsonWebToken.java index 07987cf..1430be8 100644 --- a/src/test/java/examples/SymmetricSignedJsonWebToken.java +++ b/src/test/java/examples/SymmetricSignedJsonWebToken.java @@ -9,6 +9,8 @@ import net.tokensmith.jwt.entity.jwt.JsonWebToken; import net.tokensmith.jwt.entity.jwt.header.Algorithm; import net.tokensmith.jwt.exception.SignatureException; +import net.tokensmith.jwt.jwk.generator.KeyGenerator; +import net.tokensmith.jwt.jwk.generator.exception.KeyGenerateException; import net.tokensmith.jwt.serialization.JwtSerde; import net.tokensmith.jwt.serialization.exception.JsonToJwtException; import net.tokensmith.jwt.jws.verifier.VerifySignature; @@ -21,15 +23,20 @@ */ public class SymmetricSignedJsonWebToken { - public String tocCompactJwt() { + public ByteArrayOutputStream toCompactJwt() throws KeyGenerateException { SecureCompactBuilder compactBuilder = new SecureCompactBuilder(); - SymmetricKey key = new SymmetricKey( - Optional.of("test-key-id"), - "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow", - Use.SIGNATURE - ); + JwtAppFactory jwtAppFactory = new JwtAppFactory(); + KeyGenerator keyGenerator = jwtAppFactory.keyGenerator(); + + SymmetricKey key; + + try { + key = keyGenerator.symmetricKey(Optional.of("test-key-id"), Use.SIGNATURE); + } catch (KeyGenerateException e) { + throw e; + } Claim claim = new Claim(); claim.setUriIsRoot(true); @@ -44,7 +51,7 @@ public String tocCompactJwt() { e.printStackTrace(); } - return encodedJwt.toString(); + return encodedJwt; } public Boolean verifySignature() throws Exception { @@ -54,7 +61,7 @@ public Boolean verifySignature() throws Exception { String jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZX0.TeZ3DKSE-gplbaoA8CK_RMojt8CfA1MTYaM_ZuOeGNw"; JwtSerde jwtSerde = appFactory.jwtSerde(); - JsonWebToken jsonWebToken = null; + JsonWebToken jsonWebToken; try { jsonWebToken = jwtSerde.stringToJwt(jwt, Claim.class); } catch (JsonToJwtException e) { diff --git a/src/test/java/examples/UnsecuredJsonWebTokenSerializer.java b/src/test/java/examples/UnsecuredJsonWebTokenSerializer.java index 96540d3..db24d9b 100644 --- a/src/test/java/examples/UnsecuredJsonWebTokenSerializer.java +++ b/src/test/java/examples/UnsecuredJsonWebTokenSerializer.java @@ -8,7 +8,7 @@ public class UnsecuredJsonWebTokenSerializer { - public String toEncodedJwt() { + public ByteArrayOutputStream toEncodedJwt() { UnsecureCompactBuilder compactBuilder = new UnsecureCompactBuilder(); @@ -17,6 +17,6 @@ public String toEncodedJwt() { ByteArrayOutputStream encodedJwt = compactBuilder.claims(claim).build(); - return encodedJwt.toString(); + return encodedJwt; } } diff --git a/src/test/java/helper/entity/Factory.java b/src/test/java/helper/entity/Factory.java index f2d0a61..1d164b7 100644 --- a/src/test/java/helper/entity/Factory.java +++ b/src/test/java/helper/entity/Factory.java @@ -1,5 +1,6 @@ package helper.entity; +import net.tokensmith.jwt.config.JwtAppFactory; import net.tokensmith.jwt.entity.jwk.*; import net.tokensmith.jwt.entity.jwt.JsonWebToken; import net.tokensmith.jwt.entity.jwt.header.Algorithm; @@ -14,6 +15,7 @@ * Created by tommackenzie on 11/12/15. */ public class Factory { + private static JwtAppFactory APP_FACTORY = new JwtAppFactory(); public static BigInteger toBigInt(String value) { byte[] decodedBytes = Base64.getUrlDecoder().decode(value); @@ -25,7 +27,6 @@ public static BigInteger toBigInt(String value) { public static RSAKeyPair makeRSAKeyPair() { return new RSAKeyPair( Optional.empty(), - KeyType.RSA, Use.SIGNATURE, toBigInt("ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ"), toBigInt("AQAB"), @@ -41,23 +42,31 @@ public static RSAKeyPair makeRSAKeyPair() { public static RSAPublicKey makeRSAPublicKey() { return new RSAPublicKey( Optional.empty(), - KeyType.RSA, Use.SIGNATURE, toBigInt("ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ"), toBigInt("AQAB") ); } - public static SymmetricKey makeSymmetricKey() { + public static SymmetricKey makeSymmetricKey() throws Exception{ SymmetricKey key = new SymmetricKey( - Optional.empty(), - "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow", - Use.SIGNATURE + Optional.empty(), + "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow", + Use.SIGNATURE ); return key; } + public static SymmetricKey makeBadSymmetricKey() { + + return new SymmetricKey( + Optional.empty(), + "%%%%^&&*(#*$(#*$#@(*$E*E(", + Use.SIGNATURE + ); + } + public static SymmetricKey makeSymmetricKeyForJWE() { SymmetricKey key = new SymmetricKey( Optional.empty(), @@ -79,7 +88,7 @@ public static Claim makeClaim() { return claim; } - public static JsonWebToken makeToken(Algorithm algorithm, Optional tokenType) { + public static JsonWebToken makeToken(Algorithm algorithm, Optional tokenType) { // header Header header = new Header(); @@ -89,7 +98,7 @@ public static JsonWebToken makeToken(Algorithm algorithm, Optional to // claim of the token. Claim claim = makeClaim(); - return new JsonWebToken(header, claim); + return new JsonWebToken<>(header, claim); } public static byte[] aad() { @@ -147,7 +156,6 @@ public static RSAKeyPair makeRSAKeyPairForJWE() { return new RSAKeyPair( Optional.empty(), - KeyType.RSA, Use.ENCRYPTION, toBigInt(n.toString()), toBigInt(e.toString()), @@ -174,7 +182,6 @@ public static RSAPublicKey makeRSAPublicKeyForJWE() { return new RSAPublicKey( Optional.empty(), - KeyType.RSA, Use.ENCRYPTION, toBigInt(n.toString()), toBigInt(e.toString()) diff --git a/src/test/java/net/tokensmith/jwt/builder/compact/SecureCompactBuilderTest.java b/src/test/java/net/tokensmith/jwt/builder/compact/SecureCompactBuilderTest.java index 9cea4b1..5b677a7 100644 --- a/src/test/java/net/tokensmith/jwt/builder/compact/SecureCompactBuilderTest.java +++ b/src/test/java/net/tokensmith/jwt/builder/compact/SecureCompactBuilderTest.java @@ -2,6 +2,7 @@ import helper.entity.Claim; import helper.entity.Factory; +import net.tokensmith.jwt.config.JwtAppFactory; import net.tokensmith.jwt.entity.jwk.RSAKeyPair; import net.tokensmith.jwt.entity.jwk.SymmetricKey; import net.tokensmith.jwt.entity.jwt.header.Algorithm; diff --git a/src/test/java/net/tokensmith/jwt/entity/jwk/RSAKeyPairTest.java b/src/test/java/net/tokensmith/jwt/entity/jwk/RSAKeyPairTest.java new file mode 100644 index 0000000..3d575d5 --- /dev/null +++ b/src/test/java/net/tokensmith/jwt/entity/jwk/RSAKeyPairTest.java @@ -0,0 +1,63 @@ +package net.tokensmith.jwt.entity.jwk; + +import org.junit.Test; + +import java.math.BigInteger; +import java.util.Optional; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.*; + +public class RSAKeyPairTest { + + @Test + public void buildShouldBeOk() { + RSAKeyPair actual = new RSAKeyPair.Builder() + .keyId(Optional.of("1234")) + .n(BigInteger.valueOf(1)) + .e(BigInteger.valueOf(2)) + .d(BigInteger.valueOf(3)) + .q(BigInteger.valueOf(4)) + .dp(BigInteger.valueOf(5)) + .dq(BigInteger.valueOf(6)) + .qi(BigInteger.valueOf(7)) + .build(); + + assertTrue(actual.getKeyId().isPresent()); + assertThat(actual.getKeyId().get(), is("1234")); + assertThat(actual.getKeyType(), is(KeyType.RSA)); + assertThat(actual.getN(), is(BigInteger.valueOf(1))); + assertThat(actual.getE(), is(BigInteger.valueOf(2))); + assertThat(actual.getD(), is(BigInteger.valueOf(3))); + assertThat(actual.getQ(), is(BigInteger.valueOf(4))); + assertThat(actual.getDp(), is(BigInteger.valueOf(5))); + assertThat(actual.getDq(), is(BigInteger.valueOf(6))); + assertThat(actual.getQi(), is(BigInteger.valueOf(7))); + + } + + @Test + public void buildMissingKeyIdShouldBeOk() { + RSAKeyPair actual = new RSAKeyPair.Builder() + .n(BigInteger.valueOf(1)) + .e(BigInteger.valueOf(2)) + .d(BigInteger.valueOf(3)) + .q(BigInteger.valueOf(4)) + .dp(BigInteger.valueOf(5)) + .dq(BigInteger.valueOf(6)) + .qi(BigInteger.valueOf(7)) + .build(); + + assertFalse(actual.getKeyId().isPresent()); + assertThat(actual.getKeyType(), is(KeyType.RSA)); + assertThat(actual.getKeyType(), is(KeyType.RSA)); + assertThat(actual.getN(), is(BigInteger.valueOf(1))); + assertThat(actual.getE(), is(BigInteger.valueOf(2))); + assertThat(actual.getD(), is(BigInteger.valueOf(3))); + assertThat(actual.getQ(), is(BigInteger.valueOf(4))); + assertThat(actual.getDp(), is(BigInteger.valueOf(5))); + assertThat(actual.getDq(), is(BigInteger.valueOf(6))); + assertThat(actual.getQi(), is(BigInteger.valueOf(7))); + } + +} \ No newline at end of file diff --git a/src/test/java/net/tokensmith/jwt/entity/jwk/RSAPublicKeyTest.java b/src/test/java/net/tokensmith/jwt/entity/jwk/RSAPublicKeyTest.java new file mode 100644 index 0000000..efa8553 --- /dev/null +++ b/src/test/java/net/tokensmith/jwt/entity/jwk/RSAPublicKeyTest.java @@ -0,0 +1,40 @@ +package net.tokensmith.jwt.entity.jwk; + +import org.junit.Test; + +import java.math.BigInteger; +import java.util.Optional; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.*; + +public class RSAPublicKeyTest { + + @Test + public void buildShouldBeOk() { + RSAPublicKey actual = new RSAPublicKey.Builder() + .keyId(Optional.of("1234")) + .n(BigInteger.valueOf(5678)) + .e(BigInteger.valueOf(91011)) + .build(); + + assertTrue(actual.getKeyId().isPresent()); + assertThat(actual.getKeyId().get(), is("1234")); + assertThat(actual.getKeyType(), is(KeyType.RSA)); + assertThat(actual.getN(), is(BigInteger.valueOf(5678))); + assertThat(actual.getE(), is(BigInteger.valueOf(91011))); + } + + @Test + public void buildMissingKeyIdShouldBeOk() { + RSAPublicKey actual = new RSAPublicKey.Builder() + .n(BigInteger.valueOf(5678)) + .e(BigInteger.valueOf(91011)) + .build(); + + assertFalse(actual.getKeyId().isPresent()); + assertThat(actual.getKeyType(), is(KeyType.RSA)); + assertThat(actual.getN(), is(BigInteger.valueOf(5678))); + assertThat(actual.getE(), is(BigInteger.valueOf(91011))); + } +} \ No newline at end of file diff --git a/src/test/java/net/tokensmith/jwt/entity/jwk/SymmetricKeyTest.java b/src/test/java/net/tokensmith/jwt/entity/jwk/SymmetricKeyTest.java new file mode 100644 index 0000000..5c80344 --- /dev/null +++ b/src/test/java/net/tokensmith/jwt/entity/jwk/SymmetricKeyTest.java @@ -0,0 +1,39 @@ +package net.tokensmith.jwt.entity.jwk; + +import org.junit.Test; + +import java.math.BigInteger; +import java.util.Optional; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.*; + +public class SymmetricKeyTest { + + @Test + public void buildShouldBeOk() { + SymmetricKey actual = new SymmetricKey.Builder() + .keyId(Optional.of("1234")) + .key("my-super-secret-key") + .build(); + + assertTrue(actual.getKeyId().isPresent()); + assertThat(actual.getKeyId().get(), is("1234")); + assertThat(actual.getKeyType(), is(KeyType.OCT)); + assertThat(actual.getKey(), is("my-super-secret-key")); + + } + + @Test + public void buildMissingKeyIdShouldBeOk() { + SymmetricKey actual = new SymmetricKey.Builder() + .key("my-super-secret-key") + .build(); + + assertFalse(actual.getKeyId().isPresent()); + assertThat(actual.getKeyType(), is(KeyType.OCT)); + assertThat(actual.getKey(), is("my-super-secret-key")); + + } + +} \ No newline at end of file diff --git a/src/test/java/net/tokensmith/jwt/factory/SecureJwtFactoryTest.java b/src/test/java/net/tokensmith/jwt/factory/SecureJwtFactoryTest.java index b87816b..41d862c 100644 --- a/src/test/java/net/tokensmith/jwt/factory/SecureJwtFactoryTest.java +++ b/src/test/java/net/tokensmith/jwt/factory/SecureJwtFactoryTest.java @@ -36,7 +36,7 @@ public void setUp(){ @Test - public void constructShouldAssignIVars() throws InvalidAlgorithmException, InvalidJsonWebKeyException { + public void constructShouldAssignIVars() throws Exception { SymmetricKey key = Factory.makeSymmetricKey(); key.setKeyId(Optional.of("test-key-id")); SecureJwtFactory subject = appFactory.secureJwtFactory(Algorithm.HS256, key); @@ -65,12 +65,12 @@ public void buildWithSymmetricKeyShouldHaveValidHeaderClaimsSignature() throws E // claim of the token. Claim claim = Factory.makeClaim(); - JsonWebToken actual = subject.makeJwt(claim); + JsonWebToken actual = subject.makeJwt(claim); assertThat(actual, is(notNullValue())); // inspect claims - Claim actualClaim = (Claim) actual.getClaims(); + Claim actualClaim = actual.getClaims(); assertThat(actualClaim.isUriIsRoot(), is(true)); assertThat(actualClaim.getIssuer().isPresent(), is(true)); assertThat(actualClaim.getIssuer().get(), is("joe")); @@ -116,12 +116,12 @@ public void buildWithRSAKeyPairShouldHaveValidHeaderClaimsSignature() throws Exc // claim of the token. Claim claim = Factory.makeClaim(); - JsonWebToken actual = subject.makeJwt(claim); + JsonWebToken actual = subject.makeJwt(claim); assertThat(actual, is(notNullValue())); // inspect claims - Claim actualClaim = (Claim) actual.getClaims(); + Claim actualClaim = actual.getClaims(); assertThat(actualClaim.isUriIsRoot(), is(true)); assertThat(actualClaim.getIssuer().isPresent(), is(true)); assertThat(actualClaim.getIssuer().get(), is("joe")); @@ -159,7 +159,7 @@ public void buildWithRSAKeyPairAndKeyId() throws JwtToJsonException, InvalidAlgo // claim of the token. Claim claim = Factory.makeClaim(); - JsonWebToken actual = subject.makeJwt(claim); + JsonWebToken actual = subject.makeJwt(claim); assertThat(actual, is(notNullValue())); assertThat(actual.getHeader().getKeyId(), is(keyId)); @@ -177,7 +177,7 @@ public void buildTwiceWithRSAKeyPairShouldSignsCorrectly() throws JwtToJsonExcep Claim claim = Factory.makeClaim(); // first JsonWebToken. - JsonWebToken actual = subject.makeJwt(claim); + JsonWebToken actual = subject.makeJwt(claim); assertThat(actual, is(notNullValue())); assertThat(actual.getSignature().isPresent(), is(true)); @@ -193,7 +193,7 @@ public void buildTwiceWithRSAKeyPairShouldSignsCorrectly() throws JwtToJsonExcep } @Test - public void buildTwiceWithSymmetricKeyShouldSignsCorrectly() throws JwtToJsonException, InvalidAlgorithmException, InvalidJsonWebKeyException { + public void buildTwiceWithSymmetricKeyShouldSignsCorrectly() throws Exception { // prepare subject of the test. SymmetricKey key = Factory.makeSymmetricKey(); @@ -203,7 +203,7 @@ public void buildTwiceWithSymmetricKeyShouldSignsCorrectly() throws JwtToJsonExc Claim claim = Factory.makeClaim(); // first JsonWebToken. - JsonWebToken actual = subject.makeJwt(claim); + JsonWebToken actual = subject.makeJwt(claim); assertThat(actual, is(notNullValue())); assertThat(actual.getSignature().isPresent(), is(true)); diff --git a/src/test/java/net/tokensmith/jwt/factory/UnSecureJwtFactoryTest.java b/src/test/java/net/tokensmith/jwt/factory/UnSecureJwtFactoryTest.java index a4e61e4..aa37bc7 100644 --- a/src/test/java/net/tokensmith/jwt/factory/UnSecureJwtFactoryTest.java +++ b/src/test/java/net/tokensmith/jwt/factory/UnSecureJwtFactoryTest.java @@ -40,12 +40,12 @@ public void makeUnsecuredTokenShouldHaveValidHeaderClaimsSignature() throws Exce claim.setIssuer(issuer); claim.setExpirationTime(expirationTime); - JsonWebToken actual = subject.makeJwt(claim); + JsonWebToken actual = subject.makeJwt(claim); assertThat(actual, is(notNullValue())); // inspect claims - Claim actualClaim = (Claim) actual.getClaims(); + Claim actualClaim = actual.getClaims(); assertThat(actualClaim.isUriIsRoot(), is(true)); assertThat(actualClaim.getIssuer().isPresent(), is(true)); assertThat(actualClaim.getIssuer().get(), is("joe")); diff --git a/src/test/java/net/tokensmith/jwt/jwe/factory/CipherRSAFactoryTest.java b/src/test/java/net/tokensmith/jwt/jwe/factory/CipherRSAFactoryTest.java index 2a69b18..b1fdc4e 100644 --- a/src/test/java/net/tokensmith/jwt/jwe/factory/CipherRSAFactoryTest.java +++ b/src/test/java/net/tokensmith/jwt/jwe/factory/CipherRSAFactoryTest.java @@ -7,8 +7,8 @@ import org.junit.Test; import net.tokensmith.jwt.config.JwtAppFactory; import net.tokensmith.jwt.jwe.Transformation; -import net.tokensmith.jwt.jwk.PrivateKeyFactory; -import net.tokensmith.jwt.jwk.PublicKeyFactory; +import net.tokensmith.jwt.jwk.PrivateKeyTranslator; +import net.tokensmith.jwt.jwk.PublicKeyTranslator; import javax.crypto.Cipher; @@ -20,15 +20,15 @@ import static org.junit.Assert.*; public class CipherRSAFactoryTest { - private PublicKeyFactory publicKeyFactory; - private PrivateKeyFactory privateKeyFactory; + private PublicKeyTranslator publicKeyTranslator; + private PrivateKeyTranslator privateKeyTranslator; private CipherRSAFactory subject; @Before public void setUp() { JwtAppFactory jwtAppFactory = new JwtAppFactory(); - publicKeyFactory = jwtAppFactory.publicKeyFactory(); - privateKeyFactory = jwtAppFactory.privateKeyFactory(); + publicKeyTranslator = jwtAppFactory.publicKeyFactory(); + privateKeyTranslator = jwtAppFactory.privateKeyFactory(); subject = new CipherRSAFactory(); } @@ -36,7 +36,7 @@ public void setUp() { public void forEncryptWhenPublicKey() throws Exception { RSAPublicKey rsaPublicKey = Factory.makeRSAPublicKey(); - java.security.interfaces.RSAPublicKey jdkPublicKey = publicKeyFactory.makePublicKey(rsaPublicKey); + java.security.interfaces.RSAPublicKey jdkPublicKey = publicKeyTranslator.to(rsaPublicKey); Cipher actual = subject.forEncrypt(Transformation.RSA_OAEP, jdkPublicKey); @@ -48,7 +48,7 @@ public void forEncryptWhenPublicKey() throws Exception { @Test public void forDecryptWhenPrivateKey() throws Exception { RSAKeyPair jwk = Factory.makeRSAKeyPair(); - RSAPrivateCrtKey jdkPrivateKey = privateKeyFactory.makePrivateKey(jwk); + RSAPrivateCrtKey jdkPrivateKey = privateKeyTranslator.to(jwk); Cipher actual = subject.forDecrypt(Transformation.RSA_OAEP, jdkPrivateKey); diff --git a/src/test/java/net/tokensmith/jwt/jwe/factory/CipherSymmetricFactoryTest.java b/src/test/java/net/tokensmith/jwt/jwe/factory/CipherSymmetricFactoryTest.java index 620fe1c..0fe2b48 100644 --- a/src/test/java/net/tokensmith/jwt/jwe/factory/CipherSymmetricFactoryTest.java +++ b/src/test/java/net/tokensmith/jwt/jwe/factory/CipherSymmetricFactoryTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import net.tokensmith.jwt.jwe.Transformation; import net.tokensmith.jwt.jwk.KeyAlgorithm; -import net.tokensmith.jwt.jwk.SecretKeyFactory; +import net.tokensmith.jwt.jwk.generator.jdk.SecretKeyGenerator; import javax.crypto.Cipher; import javax.crypto.SecretKey; @@ -26,8 +26,8 @@ public void setUp() { @Test public void forEncryptWhenSecretKey() throws Exception { - SecretKeyFactory secretKeyFactory = new SecretKeyFactory(); - SecretKey secretKey = secretKeyFactory.makeKey(KeyAlgorithm.AES); + SecretKeyGenerator secretKeyGenerator = new SecretKeyGenerator(); + SecretKey secretKey = secretKeyGenerator.makeKey(KeyAlgorithm.AES); byte[] aad = Factory.aad(); Cipher actual = subject.forEncrypt(Transformation.AES_GCM_NO_PADDING, secretKey, aad); @@ -39,8 +39,8 @@ public void forEncryptWhenSecretKey() throws Exception { @Test public void forDecryptWhenSecretKey() throws Exception { - SecretKeyFactory secretKeyFactory = new SecretKeyFactory(); - SecretKey secretKey = secretKeyFactory.makeKey(KeyAlgorithm.AES); + SecretKeyGenerator secretKeyGenerator = new SecretKeyGenerator(); + SecretKey secretKey = secretKeyGenerator.makeKey(KeyAlgorithm.AES); byte[] aad = Factory.aad(); byte[] initVector = subject.makeInitVector(); diff --git a/src/test/java/net/tokensmith/jwt/jwe/factory/SecretKeyFactoryTest.java b/src/test/java/net/tokensmith/jwt/jwe/factory/SecretKeyGeneratorTest.java similarity index 78% rename from src/test/java/net/tokensmith/jwt/jwe/factory/SecretKeyFactoryTest.java rename to src/test/java/net/tokensmith/jwt/jwe/factory/SecretKeyGeneratorTest.java index d760570..aa6a652 100644 --- a/src/test/java/net/tokensmith/jwt/jwe/factory/SecretKeyFactoryTest.java +++ b/src/test/java/net/tokensmith/jwt/jwe/factory/SecretKeyGeneratorTest.java @@ -3,7 +3,7 @@ import org.junit.Before; import org.junit.Test; import net.tokensmith.jwt.jwk.KeyAlgorithm; -import net.tokensmith.jwt.jwk.SecretKeyFactory; +import net.tokensmith.jwt.jwk.generator.jdk.SecretKeyGenerator; import javax.crypto.SecretKey; @@ -11,12 +11,12 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.*; -public class SecretKeyFactoryTest { - private SecretKeyFactory subject; +public class SecretKeyGeneratorTest { + private SecretKeyGenerator subject; @Before public void setUp() { - subject = new SecretKeyFactory(); + subject = new SecretKeyGenerator(); } @Test public void makeKeyForAESAnd256ShouldBeOk() throws Exception { diff --git a/src/test/java/net/tokensmith/jwt/jwe/serialization/direct/JweDirectSerializerTest.java b/src/test/java/net/tokensmith/jwt/jwe/serialization/direct/JweDirectSerializerTest.java index b2eee42..6720cc2 100644 --- a/src/test/java/net/tokensmith/jwt/jwe/serialization/direct/JweDirectSerializerTest.java +++ b/src/test/java/net/tokensmith/jwt/jwe/serialization/direct/JweDirectSerializerTest.java @@ -20,7 +20,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.*; -import static org.mockito.Matchers.notNull; + public class JweDirectSerializerTest { private static JwtAppFactory jwtAppFactory = new JwtAppFactory(); diff --git a/src/test/java/net/tokensmith/jwt/jwk/PrivateKeyFactoryTest.java b/src/test/java/net/tokensmith/jwt/jwk/PrivateKeyTranslatorTest.java similarity index 96% rename from src/test/java/net/tokensmith/jwt/jwk/PrivateKeyFactoryTest.java rename to src/test/java/net/tokensmith/jwt/jwk/PrivateKeyTranslatorTest.java index 3a749ce..3fd5852 100644 --- a/src/test/java/net/tokensmith/jwt/jwk/PrivateKeyFactoryTest.java +++ b/src/test/java/net/tokensmith/jwt/jwk/PrivateKeyTranslatorTest.java @@ -14,8 +14,8 @@ import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; -public class PrivateKeyFactoryTest { - private PrivateKeyFactory subject; +public class PrivateKeyTranslatorTest { + private PrivateKeyTranslator subject; @Before public void setUp() { @@ -26,7 +26,7 @@ public void setUp() { @Test public void makePrivateKeyShouldMakeRSAPrivateCrtKey() throws Exception { RSAKeyPair jwk = Factory.makeRSAKeyPair(); - RSAPrivateCrtKey privateKey = subject.makePrivateKey(jwk); + RSAPrivateCrtKey privateKey = subject.to(jwk); // expected values BigInteger modulus = new BigInteger("20446702916744654562596343388758805860065209639960173505037453331270270518732245089773723012043203236097095623402044690115755377345254696448759605707788965848889501746836211206270643833663949992536246985362693736387185145424787922241585721992924045675229348655595626434390043002821512765630397723028023792577935108185822753692574221566930937805031155820097146819964920270008811327036286786392793593121762425048860211859763441770446703722015857250621107855398693133264081150697423188751482418465308470313958250757758547155699749157985955379381294962058862159085915015369381046959790476428631998204940879604226680285601"); @@ -57,7 +57,7 @@ public void makePrivateKeyWhenKeyIsNot512ShouldThrowPrivateKeyException() throws PrivateKeyException actual = null; try { - subject.makePrivateKey(rsaKeyPair); + subject.to(rsaKeyPair); } catch (PrivateKeyException e) { actual = e; } diff --git a/src/test/java/net/tokensmith/jwt/jwk/PublicKeyFactoryTest.java b/src/test/java/net/tokensmith/jwt/jwk/PublicKeyTranslatorTest.java similarity index 91% rename from src/test/java/net/tokensmith/jwt/jwk/PublicKeyFactoryTest.java rename to src/test/java/net/tokensmith/jwt/jwk/PublicKeyTranslatorTest.java index be9531f..bc5a1aa 100644 --- a/src/test/java/net/tokensmith/jwt/jwk/PublicKeyFactoryTest.java +++ b/src/test/java/net/tokensmith/jwt/jwk/PublicKeyTranslatorTest.java @@ -13,9 +13,9 @@ import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; -public class PublicKeyFactoryTest { +public class PublicKeyTranslatorTest { private JwtAppFactory appFactory; - private PublicKeyFactory subject; + private PublicKeyTranslator subject; @Before public void setUp() { @@ -32,7 +32,7 @@ public void makePublicKeyShouldBeRsaPublicKey() throws PublicKeyException { BigInteger modulus = new BigInteger("20446702916744654562596343388758805860065209639960173505037453331270270518732245089773723012043203236097095623402044690115755377345254696448759605707788965848889501746836211206270643833663949992536246985362693736387185145424787922241585721992924045675229348655595626434390043002821512765630397723028023792577935108185822753692574221566930937805031155820097146819964920270008811327036286786392793593121762425048860211859763441770446703722015857250621107855398693133264081150697423188751482418465308470313958250757758547155699749157985955379381294962058862159085915015369381046959790476428631998204940879604226680285601"); BigInteger publicExponent = new BigInteger("65537"); - java.security.interfaces.RSAPublicKey actual = subject.makePublicKey(publicKey); + java.security.interfaces.RSAPublicKey actual = subject.to(publicKey); assertThat(actual, is(notNullValue())); assertThat(actual.getAlgorithm(), is("RSA")); @@ -48,7 +48,7 @@ public void makePublicKeyWhenKeyIsNot512ShouldThrowPublicKeyException() throws P PublicKeyException actual = null; try { - subject.makePublicKey(publicKey); + subject.to(publicKey); } catch (PublicKeyException e) { actual = e; } diff --git a/src/test/java/net/tokensmith/jwt/jwk/generator/KeyGeneratorTest.java b/src/test/java/net/tokensmith/jwt/jwk/generator/KeyGeneratorTest.java new file mode 100644 index 0000000..2d827ff --- /dev/null +++ b/src/test/java/net/tokensmith/jwt/jwk/generator/KeyGeneratorTest.java @@ -0,0 +1,109 @@ +package net.tokensmith.jwt.jwk.generator; + +import net.tokensmith.jwt.config.JwtAppFactory; +import net.tokensmith.jwt.entity.jwk.RSAKeyPair; +import net.tokensmith.jwt.entity.jwk.SymmetricKey; +import net.tokensmith.jwt.entity.jwk.Use; +import org.junit.Test; + +import java.util.Optional; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.*; + +public class KeyGeneratorTest { + private static final JwtAppFactory jwtAppFactory = new JwtAppFactory(); + + @Test + public void symmetricKeyShouldBeOk() throws Exception { + KeyGenerator subject = jwtAppFactory.keyGenerator(); + + SymmetricKey actual = subject.symmetricKey(Optional.of("123"), Use.SIGNATURE); + + assertTrue(actual.getKeyId().isPresent()); + assertThat(actual.getKeyId().get(), is("123")); + assertThat(actual.getUse(), is(Use.SIGNATURE)); + assertThat(actual.getKey(), is(notNullValue())); + + // key should be able to be base64 decoded. + try { + jwtAppFactory.urlDecoder().decode(actual.getKey()); + } catch (IllegalArgumentException e) { + fail("key is not base 64 encoded. " + e.getMessage()); + } + + } + + @Test + public void rsaKeyPair1024ShouldBeOk() throws Exception { + KeyGenerator subject = jwtAppFactory.keyGenerator(); + + RSAKeyPair actual = subject.rsaKeyPair(KeyGenerator.RSA_1024, Optional.of("123"), Use.SIGNATURE); + + assertTrue(actual.getKeyId().isPresent()); + assertThat(actual.getKeyId().get(), is("123")); + assertThat(actual.getUse(), is(Use.SIGNATURE)); + assertThat(actual.getN(), is(notNullValue())); + assertThat(actual.getE(), is(notNullValue())); + assertThat(actual.getD(), is(notNullValue())); + assertThat(actual.getP(), is(notNullValue())); + assertThat(actual.getQ(), is(notNullValue())); + assertThat(actual.getDp(), is(notNullValue())); + assertThat(actual.getDq(), is(notNullValue())); + assertThat(actual.getQi(), is(notNullValue())); + } + + @Test + public void rsaKeyPair2048ShouldBeOk() throws Exception { + KeyGenerator subject = jwtAppFactory.keyGenerator(); + + RSAKeyPair actual = subject.rsaKeyPair(KeyGenerator.RSA_2048, Optional.of("123"), Use.SIGNATURE); + + assertTrue(actual.getKeyId().isPresent()); + assertThat(actual.getKeyId().get(), is("123")); + assertThat(actual.getUse(), is(Use.SIGNATURE)); + assertThat(actual.getN(), is(notNullValue())); + assertThat(actual.getE(), is(notNullValue())); + assertThat(actual.getD(), is(notNullValue())); + assertThat(actual.getP(), is(notNullValue())); + assertThat(actual.getQ(), is(notNullValue())); + assertThat(actual.getDp(), is(notNullValue())); + assertThat(actual.getDq(), is(notNullValue())); + assertThat(actual.getQi(), is(notNullValue())); + } + + @Test + public void rsaKeyPair4096ShouldBeOk() throws Exception { + KeyGenerator subject = jwtAppFactory.keyGenerator(); + + RSAKeyPair actual = subject.rsaKeyPair(KeyGenerator.RSA_4096, Optional.of("123"), Use.SIGNATURE); + + assertTrue(actual.getKeyId().isPresent()); + assertThat(actual.getKeyId().get(), is("123")); + assertThat(actual.getUse(), is(Use.SIGNATURE)); + assertThat(actual.getN(), is(notNullValue())); + assertThat(actual.getE(), is(notNullValue())); + assertThat(actual.getD(), is(notNullValue())); + assertThat(actual.getP(), is(notNullValue())); + assertThat(actual.getQ(), is(notNullValue())); + assertThat(actual.getDp(), is(notNullValue())); + assertThat(actual.getDq(), is(notNullValue())); + assertThat(actual.getQi(), is(notNullValue())); + } + + @Test + public void rsa1024IsOk() throws Exception { + assertThat(KeyGenerator.RSA_1024, is(1024)); + } + + @Test + public void rsa2048IsOk() throws Exception { + assertThat(KeyGenerator.RSA_2048, is(2048)); + } + + @Test + public void rsa4096IsOk() throws Exception { + assertThat(KeyGenerator.RSA_4096, is(4096)); + } +} \ No newline at end of file diff --git a/src/test/java/net/tokensmith/jwt/jws/signer/MacSignerTest.java b/src/test/java/net/tokensmith/jwt/jws/signer/MacSignerTest.java index bc31beb..11e6d2d 100644 --- a/src/test/java/net/tokensmith/jwt/jws/signer/MacSignerTest.java +++ b/src/test/java/net/tokensmith/jwt/jws/signer/MacSignerTest.java @@ -27,7 +27,7 @@ public class MacSignerTest { Signer subject; @Before - public void setUp() throws InvalidAlgorithmException, InvalidJsonWebKeyException { + public void setUp() throws Exception { SymmetricKey key = Factory.makeSymmetricKey(); JwtAppFactory appFactory = new JwtAppFactory(); @@ -57,7 +57,7 @@ public void shouldSignJwtCorrectly() throws JwtToJsonException { claim.setIssuer(issuer); claim.setExpirationTime(expirationTime); - JsonWebToken jwt = new JsonWebToken(header, claim); + JsonWebToken jwt = new JsonWebToken<>(header, claim); byte[] actual = subject.run(jwt); assertThat(actual, is("lliDzOlRAdGUCfCHCPx_uisb6ZfZ1LRQa0OJLeYTTpY".getBytes())); diff --git a/src/test/java/net/tokensmith/jwt/jws/signer/RSASignerTest.java b/src/test/java/net/tokensmith/jwt/jws/signer/RSASignerTest.java index 208c772..2a5a181 100644 --- a/src/test/java/net/tokensmith/jwt/jws/signer/RSASignerTest.java +++ b/src/test/java/net/tokensmith/jwt/jws/signer/RSASignerTest.java @@ -1,5 +1,6 @@ package net.tokensmith.jwt.jws.signer; +import helper.entity.Claim; import helper.entity.Factory; import net.tokensmith.jwt.entity.jwk.RSAKeyPair; import net.tokensmith.jwt.entity.jwt.JsonWebToken; @@ -75,7 +76,7 @@ public void signTokenWithRS256ShouldSignCorrectly() throws InvalidAlgorithmExcep RSAKeyPair jwk = Factory.makeRSAKeyPair(); Signer subject = appFactory.signerFactory().makeSigner(Algorithm.RS256, jwk); - JsonWebToken jwt = Factory.makeToken(Algorithm.RS256, Optional.empty()); + JsonWebToken jwt = Factory.makeToken(Algorithm.RS256, Optional.empty()); byte[] actual = subject.run(jwt); diff --git a/src/test/java/net/tokensmith/jwt/jws/signer/factory/MacFactoryTest.java b/src/test/java/net/tokensmith/jwt/jws/signer/factory/MacFactoryTest.java index 103ecc3..40c3ea6 100644 --- a/src/test/java/net/tokensmith/jwt/jws/signer/factory/MacFactoryTest.java +++ b/src/test/java/net/tokensmith/jwt/jws/signer/factory/MacFactoryTest.java @@ -29,7 +29,7 @@ public void setUp() { } @Test - public void makeKeyShouldBeHS256WithSecretKey() { + public void makeKeyShouldBeHS256WithSecretKey() throws Exception { SymmetricKey key = Factory.makeSymmetricKey(); java.security.Key actual = subject.makeKey(SignAlgorithm.HS256, key); @@ -41,7 +41,7 @@ public void makeKeyShouldBeHS256WithSecretKey() { } @Test - public void makeMacShouldBeHS256Alg() throws InvalidAlgorithmException, SecurityKeyException { + public void makeMacShouldBeHS256Alg() throws Exception { SymmetricKey key = Factory.makeSymmetricKey(); Mac actual = subject.makeMac(SignAlgorithm.HS256, key); diff --git a/src/test/java/net/tokensmith/jwt/jws/signer/factory/SignerFactoryImplTest.java b/src/test/java/net/tokensmith/jwt/jws/signer/factory/SignerFactoryImplTest.java index 1f5597c..5746134 100644 --- a/src/test/java/net/tokensmith/jwt/jws/signer/factory/SignerFactoryImplTest.java +++ b/src/test/java/net/tokensmith/jwt/jws/signer/factory/SignerFactoryImplTest.java @@ -29,7 +29,7 @@ public void setUp() throws Exception { } @Test - public void shouldCreateMacSigner() throws InvalidAlgorithmException, InvalidJsonWebKeyException { + public void shouldCreateMacSigner() throws Exception { SymmetricKey key = Factory.makeSymmetricKey(); Signer actual = subject.makeSigner(Algorithm.HS256, key); diff --git a/src/test/java/net/tokensmith/jwt/jws/verifier/VerifyMacSignatureTest.java b/src/test/java/net/tokensmith/jwt/jws/verifier/VerifyMacSignatureTest.java index d3793ae..c220226 100644 --- a/src/test/java/net/tokensmith/jwt/jws/verifier/VerifyMacSignatureTest.java +++ b/src/test/java/net/tokensmith/jwt/jws/verifier/VerifyMacSignatureTest.java @@ -33,7 +33,7 @@ public void verifySecureJwtWithJwtShouldBeTrue() throws Exception { "eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ." + "lliDzOlRAdGUCfCHCPx_uisb6ZfZ1LRQa0OJLeYTTpY"; - JsonWebToken jwt = null; + JsonWebToken jwt = null; try { jwt = jwtSerde.stringToJwt(jwtAsText, Claim.class); } catch (JsonToJwtException e) { @@ -54,7 +54,7 @@ public void verifyUnsecureJwtWithJwtShouldBeTrue() throws Exception { String jwtAsText = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9." + "eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ."; - JsonWebToken jwt = null; + JsonWebToken jwt = null; try { jwt = jwtSerde.stringToJwt(jwtAsText, Claim.class); } catch (JsonToJwtException e) { diff --git a/src/test/java/net/tokensmith/jwt/jws/verifier/VerifyRsaSignatureTest.java b/src/test/java/net/tokensmith/jwt/jws/verifier/VerifyRsaSignatureTest.java index f923235..5961351 100644 --- a/src/test/java/net/tokensmith/jwt/jws/verifier/VerifyRsaSignatureTest.java +++ b/src/test/java/net/tokensmith/jwt/jws/verifier/VerifyRsaSignatureTest.java @@ -28,7 +28,7 @@ public void setUp() { public void testRunShouldBeTrue() throws Exception { String jwtAsText = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw"; JwtSerde serializer = appFactory.jwtSerde(); - JsonWebToken jwt = serializer.stringToJwt(jwtAsText, Claim.class); + JsonWebToken jwt = serializer.stringToJwt(jwtAsText, Claim.class); RSAPublicKey publicKey = Factory.makeRSAPublicKey(); VerifySignature subject = appFactory.verifySignature(Algorithm.RS256, publicKey); diff --git a/src/test/java/net/tokensmith/jwt/jws/verifier/factory/VerifySignatureFactoryImplTest.java b/src/test/java/net/tokensmith/jwt/jws/verifier/factory/VerifySignatureFactoryImplTest.java deleted file mode 100644 index 286bda8..0000000 --- a/src/test/java/net/tokensmith/jwt/jws/verifier/factory/VerifySignatureFactoryImplTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.tokensmith.jwt.jws.verifier.factory; - -import helper.entity.Factory; -import net.tokensmith.jwt.entity.jwk.RSAPublicKey; -import net.tokensmith.jwt.entity.jwk.SymmetricKey; -import net.tokensmith.jwt.entity.jwt.header.Algorithm; -import org.junit.Before; -import org.junit.Test; -import net.tokensmith.jwt.config.JwtAppFactory; -import net.tokensmith.jwt.jws.verifier.VerifyMacSignature; -import net.tokensmith.jwt.jws.verifier.VerifyRsaSignature; -import net.tokensmith.jwt.jws.verifier.VerifySignature; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.*; - -/** - * Created by tommackenzie on 11/15/15. - */ -public class VerifySignatureFactoryImplTest { - private JwtAppFactory appFactory; - - @Before - public void setUp() { - this.appFactory = new JwtAppFactory(); - } - - @Test - public void testMakeVerifySignatureShouldBeVerifyMacSignature() throws Exception { - VerifySignatureFactory subject = appFactory.verifySignatureFactory(); - SymmetricKey key = Factory.makeSymmetricKey(); - - VerifySignature verifySignature = subject.makeVerifySignature(Algorithm.HS256, key); - - assertThat(verifySignature, instanceOf(VerifyMacSignature.class)); - } - - @Test - public void testMakeVerifySignatureShouldBeVerifyRSASignature() throws Exception { - VerifySignatureFactory subject = appFactory.verifySignatureFactory(); - RSAPublicKey key = Factory.makeRSAPublicKey(); - - VerifySignature verifySignature = subject.makeVerifySignature(Algorithm.RS256, key); - - assertThat(verifySignature, instanceOf(VerifyRsaSignature.class)); - } -} \ No newline at end of file diff --git a/src/test/java/net/tokensmith/jwt/jws/verifier/factory/VerifySignatureFactoryTest.java b/src/test/java/net/tokensmith/jwt/jws/verifier/factory/VerifySignatureFactoryTest.java new file mode 100644 index 0000000..aa82a57 --- /dev/null +++ b/src/test/java/net/tokensmith/jwt/jws/verifier/factory/VerifySignatureFactoryTest.java @@ -0,0 +1,124 @@ +package net.tokensmith.jwt.jws.verifier.factory; + +import helper.entity.Factory; +import net.tokensmith.jwt.entity.jwk.KeyType; +import net.tokensmith.jwt.entity.jwk.RSAPublicKey; +import net.tokensmith.jwt.entity.jwk.SymmetricKey; +import net.tokensmith.jwt.entity.jwt.header.Algorithm; +import net.tokensmith.jwt.exception.SignatureException; +import net.tokensmith.jwt.jws.signer.factory.exception.InvalidAlgorithmException; +import net.tokensmith.jwt.jws.signer.factory.exception.InvalidJsonWebKeyException; +import net.tokensmith.jwt.jws.signer.factory.rsa.exception.PublicKeyException; +import org.junit.Before; +import org.junit.Test; +import net.tokensmith.jwt.config.JwtAppFactory; +import net.tokensmith.jwt.jws.verifier.VerifyMacSignature; +import net.tokensmith.jwt.jws.verifier.VerifyRsaSignature; +import net.tokensmith.jwt.jws.verifier.VerifySignature; + +import java.math.BigInteger; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.*; + +/** + * Created by tommackenzie on 11/15/15. + */ +public class VerifySignatureFactoryTest { + private JwtAppFactory appFactory; + + @Before + public void setUp() { + this.appFactory = new JwtAppFactory(); + } + + @Test + public void testMakeVerifySignatureShouldBeVerifyMacSignature() throws Exception { + VerifySignatureFactory subject = appFactory.verifySignatureFactory(); + SymmetricKey key = Factory.makeSymmetricKey(); + + VerifySignature verifySignature = subject.makeVerifySignature(Algorithm.HS256, key); + + assertThat(verifySignature, instanceOf(VerifyMacSignature.class)); + } + + @Test + public void testMakeVerifySignatureShouldBeVerifyRSASignature() throws Exception { + VerifySignatureFactory subject = appFactory.verifySignatureFactory(); + RSAPublicKey key = Factory.makeRSAPublicKey(); + + VerifySignature verifySignature = subject.makeVerifySignature(Algorithm.RS256, key); + + assertThat(verifySignature, instanceOf(VerifyRsaSignature.class)); + } + + @Test + public void testMakeVerifySignatureWhenHS256AndGivenRSAKeyShouldThrowSignatureException() throws Exception { + VerifySignatureFactory subject = appFactory.verifySignatureFactory(); + RSAPublicKey key = Factory.makeRSAPublicKey(); + + SignatureException actual = null; + try { + subject.makeVerifySignature(Algorithm.HS256, key); + } catch (SignatureException e) { + actual = e; + } + + assertThat(actual, is(notNullValue())); + assertThat(actual.getCause(), is(instanceOf(InvalidAlgorithmException.class))); + } + + @Test + public void testMakeVerifySignatureWhenHS256AndBadKeyShouldThrowSignatureException() throws Exception { + VerifySignatureFactory subject = appFactory.verifySignatureFactory(); + SymmetricKey key = Factory.makeBadSymmetricKey(); + + SignatureException actual = null; + try { + subject.makeVerifySignature(Algorithm.HS256, key); + } catch (SignatureException e) { + actual = e; + } + + assertThat(actual, is(notNullValue())); + assertThat(actual.getCause(), is(instanceOf(InvalidJsonWebKeyException.class))); + } + + @Test + public void testMakeVerifySignatureWhenRsaAndGivenSymmetricKeyShouldThrowSignatureException() throws Exception { + VerifySignatureFactory subject = appFactory.verifySignatureFactory(); + SymmetricKey key = Factory.makeSymmetricKey(); + + SignatureException actual = null; + try { + subject.makeVerifySignature(Algorithm.RS256, key); + } catch (SignatureException e) { + actual = e; + } + + assertThat(actual, is(notNullValue())); + assertThat(actual.getCause(), is(instanceOf(InvalidAlgorithmException.class))); + } + + @Test + public void testMakeVerifySignatureWhenRSAAndBadKeyShouldThrowSignatureException() throws Exception { + VerifySignatureFactory subject = appFactory.verifySignatureFactory(); + RSAPublicKey key = new RSAPublicKey.Builder() + .n(BigInteger.valueOf(1)) + .e(BigInteger.valueOf(1)) + .build(); + + SignatureException actual = null; + try { + subject.makeVerifySignature(Algorithm.RS256, key); + } catch (SignatureException e) { + actual = e; + } + + assertThat(actual, is(notNullValue())); + assertThat(actual.getCause(), is(instanceOf(InvalidJsonWebKeyException.class))); + } + +} \ No newline at end of file diff --git a/src/test/java/net/tokensmith/jwt/serialization/JwtSerdeTest.java b/src/test/java/net/tokensmith/jwt/serialization/JwtSerdeTest.java index 51f4456..a3ab977 100644 --- a/src/test/java/net/tokensmith/jwt/serialization/JwtSerdeTest.java +++ b/src/test/java/net/tokensmith/jwt/serialization/JwtSerdeTest.java @@ -37,7 +37,7 @@ public void UnsecuredJwtToStringShouldBeValidJWT() throws Exception { Claim claim = Factory.makeClaim(); - JsonWebToken tokenToMarshal = unsecureTokenBuilder.makeJwt(claim); + JsonWebToken tokenToMarshal = unsecureTokenBuilder.makeJwt(claim); ByteArrayOutputStream actual = subject.compactJwt(tokenToMarshal); assertThat(actual.toString(), is(expectedJwt)); } @@ -57,7 +57,7 @@ public void SecuredJwtToStringShouldBeValid() throws Exception { Claim claim = Factory.makeClaim(); - JsonWebToken tokenToMarshal = secureJwtFactory.makeJwt(claim); + JsonWebToken tokenToMarshal = secureJwtFactory.makeJwt(claim); ByteArrayOutputStream actual = subject.compactJwt(tokenToMarshal); assertThat(actual.toString(), is(expectedJwt)); @@ -79,7 +79,7 @@ public void SecuredJwtWithKeyIdToStringShouldBeValid() throws Exception { Claim claim = Factory.makeClaim(); - JsonWebToken tokenToMarshal = secureJwtFactory.makeJwt(claim); + JsonWebToken tokenToMarshal = secureJwtFactory.makeJwt(claim); ByteArrayOutputStream actual = subject.compactJwt(tokenToMarshal); assertThat(actual.toString(), is(expectedJwt)); @@ -93,7 +93,7 @@ public void stringToJwtShouldBeUnsecuredJwt() throws Exception { String jwtAsText = "eyJhbGciOiJub25lIn0=." + "eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ==."; - JsonWebToken actual = subject.stringToJwt(jwtAsText, Claim.class); + JsonWebToken actual = subject.stringToJwt(jwtAsText, Claim.class); assertThat(actual, is(notNullValue())); // header @@ -104,7 +104,7 @@ public void stringToJwtShouldBeUnsecuredJwt() throws Exception { // claim assertThat(actual.getClaims(), is(notNullValue())); assertThat(actual.getClaims(), instanceOf(Claim.class)); - assertThat(((Claim) actual.getClaims()).isUriIsRoot(), is(true)); + assertThat((actual.getClaims()).isUriIsRoot(), is(true)); assertThat(actual.getClaims().getIssuer().isPresent(), is(true)); assertThat(actual.getClaims().getIssuer().get(), is("joe")); assertThat(actual.getClaims().getExpirationTime().isPresent(), is(true)); @@ -129,7 +129,7 @@ public void stringToJwtShouldBeSecuredJwt() throws Exception { "eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ." + signature; - JsonWebToken actual = subject.stringToJwt(jwtAsText, Claim.class); + JsonWebToken actual = subject.stringToJwt(jwtAsText, Claim.class); assertThat(actual, is(notNullValue())); // header @@ -142,7 +142,7 @@ public void stringToJwtShouldBeSecuredJwt() throws Exception { // claim assertThat(actual.getClaims(), is(notNullValue())); assertThat(actual.getClaims(), instanceOf(Claim.class)); - assertThat(((Claim) actual.getClaims()).isUriIsRoot(), is(true)); + assertThat((actual.getClaims()).isUriIsRoot(), is(true)); assertThat(actual.getClaims().getIssuer().isPresent(), is(true)); assertThat(actual.getClaims().getIssuer().get(), is("joe")); assertThat(actual.getClaims().getExpirationTime().isPresent(), is(true)); @@ -171,7 +171,7 @@ public void stringToJwtShouldBeSecuredJwtWithKeyId() throws Exception { "eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ." + signature; - JsonWebToken actual = subject.stringToJwt(jwtAsText, Claim.class); + JsonWebToken actual = subject.stringToJwt(jwtAsText, Claim.class); assertThat(actual, is(notNullValue())); // header @@ -185,7 +185,7 @@ public void stringToJwtShouldBeSecuredJwtWithKeyId() throws Exception { // claim assertThat(actual.getClaims(), is(notNullValue())); assertThat(actual.getClaims(), instanceOf(Claim.class)); - assertThat(((Claim) actual.getClaims()).isUriIsRoot(), is(true)); + assertThat((actual.getClaims()).isUriIsRoot(), is(true)); assertThat(actual.getClaims().getIssuer().isPresent(), is(true)); assertThat(actual.getClaims().getIssuer().get(), is("joe")); assertThat(actual.getClaims().getExpirationTime().isPresent(), is(true)); diff --git a/src/test/java/net/tokensmith/jwt/serialization/SerdesTest.java b/src/test/java/net/tokensmith/jwt/serialization/SerdesTest.java index d550ff5..6a0af20 100644 --- a/src/test/java/net/tokensmith/jwt/serialization/SerdesTest.java +++ b/src/test/java/net/tokensmith/jwt/serialization/SerdesTest.java @@ -60,7 +60,7 @@ public void claimToJsonExpectExcludesNullAndOptionalEmpty() throws JsonException public void jsonToUnsecuredHeader() throws JsonException { Serdes subject = appFactory.serdes(); byte[] json = "{\"alg\":\"none\"}".getBytes(); - Header actual = (Header) subject.jsonBytesToObject(json, Header.class); + Header actual = subject.jsonBytesTo(json, Header.class); assertThat(actual.getAlgorithm(), is(Algorithm.NONE)); } @@ -68,7 +68,7 @@ public void jsonToUnsecuredHeader() throws JsonException { public void jsonToClaim() throws JsonException { Serdes subject = appFactory.serdes(); byte[] json = "{\"iss\":\"joe\",\"exp\":1300819380,\"http://example.com/is_root\":true}".getBytes(); - Claim actual = (Claim) subject.jsonBytesToObject(json, Claim.class); + Claim actual = subject.jsonBytesTo(json, Claim.class); assertThat(actual, is(notNullValue())); assertThat(actual.isUriIsRoot(), is(true)); @@ -84,10 +84,10 @@ public void jsonToClaim() throws JsonException { } @Test(expected=JsonException.class) - public void jsonBytesToObjectShouldThrowJsonException() throws JsonException { + public void jsonBytesToShouldThrowJsonException() throws JsonException { Serdes subject = appFactory.serdes(); byte[] invalidJson = "{\"iss\":\"joe\"".getBytes(); - subject.jsonBytesToObject(invalidJson, Claim.class); + subject.jsonBytesTo(invalidJson, Claim.class); } } \ No newline at end of file