/** * Gets the APK Signature Scheme v2 signature algorithms to be used for signing an APK using the * provided key. * * @param minSdkVersion minimum API Level of the platform on which the APK may be installed (see * AndroidManifest.xml minSdkVersion attribute). * * @throws InvalidKeyException if the provided key is not suitable for signing APKs using * APK Signature Scheme v2 */ public static List<SignatureAlgorithm> getSuggestedSignatureAlgorithms( PublicKey signingKey, int minSdkVersion) throws InvalidKeyException { String keyAlgorithm = signingKey.getAlgorithm(); if ("RSA".equalsIgnoreCase(keyAlgorithm)) { // Use RSASSA-PKCS1-v1_5 signature scheme instead of RSASSA-PSS to guarantee // deterministic signatures which make life easier for OTA updates (fewer files // changed when deterministic signature schemes are used). // Pick a digest which is no weaker than the key. int modulusLengthBits = ((RSAKey) signingKey).getModulus().bitLength(); if (modulusLengthBits <= 3072) { // 3072-bit RSA is roughly 128-bit strong, meaning SHA-256 is a good fit. return Collections.singletonList(SignatureAlgorithm.RSA_PKCS1_V1_5_WITH_SHA256); } else { // Keys longer than 3072 bit need to be paired with a stronger digest to avoid the // digest being the weak link. SHA-512 is the next strongest supported digest. return Collections.singletonList(SignatureAlgorithm.RSA_PKCS1_V1_5_WITH_SHA512); } } else if ("DSA".equalsIgnoreCase(keyAlgorithm)) { // DSA is supported only with SHA-256. return Collections.singletonList(SignatureAlgorithm.DSA_WITH_SHA256); } else if ("EC".equalsIgnoreCase(keyAlgorithm)) { // Pick a digest which is no weaker than the key. int keySizeBits = ((ECKey) signingKey).getParams().getOrder().bitLength(); if (keySizeBits <= 256) { // 256-bit Elliptic Curve is roughly 128-bit strong, meaning SHA-256 is a good fit. return Collections.singletonList(SignatureAlgorithm.ECDSA_WITH_SHA256); } else { // Keys longer than 256 bit need to be paired with a stronger digest to avoid the // digest being the weak link. SHA-512 is the next strongest supported digest. return Collections.singletonList(SignatureAlgorithm.ECDSA_WITH_SHA512); } } else { throw new InvalidKeyException("Unsupported key algorithm: " + keyAlgorithm); } }
@Test public void shouldFailECDSA256VerificationOnInvalidJOSESignatureLength() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA"); exception.expectCause(isA(SignatureException.class)); exception.expectCause(hasMessage(is("Invalid JOSE signature format."))); byte[] bytes = new byte[63]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA384VerificationOnInvalidDERSignature() throws Exception { exception.expect(AlgorithmMismatchException.class); exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header."); byte[] bytes = new byte[96]; new SecureRandom().nextBytes(bytes); bytes[0] = 0x30; String signature = Base64.encodeBase64URLSafeString(bytes); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
/** * Wraps the provided private key for use in the TLS/SSL stack only. Sign/decrypt operations * using the key will be delegated to the {@code Signature}/{@code Cipher} implementation of the * provider which accepts the key. */ static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey, ECParameterSpec params) throws InvalidKeyException { if (params == null) { if (privateKey instanceof ECKey) { params = ((ECKey) privateKey).getParams(); } } if (params == null) { throw new InvalidKeyException("EC parameters not available: " + privateKey); } OpenSSLECGroupContext group; try { group = OpenSSLECGroupContext.getInstance(params); } catch (InvalidAlgorithmParameterException e) { throw new InvalidKeyException("Invalid EC parameters: " + params); } return new OpenSSLKey( NativeCrypto.getECPrivateKeyWrapper(privateKey, group.getNativeRef()), true); }
/** * Get the key size of a public key. * * @param pubKey The public key * @return The key size, {@link #UNKNOWN_KEY_SIZE} if not known */ public static int getKeyLength(PublicKey pubKey) { if (pubKey instanceof RSAKey) { return ((RSAKey) pubKey).getModulus().bitLength(); } else if (pubKey instanceof DSAKey) { return ((DSAKey) pubKey).getParams().getP().bitLength(); } else if (pubKey instanceof DHKey) { return ((DHKey) pubKey).getParams().getP().bitLength(); } else if (pubKey instanceof ECKey) { // TODO: how to get key size from these? return UNKNOWN_KEY_SIZE; } LOG.warning("Don't know how to get key size from key " + pubKey); return UNKNOWN_KEY_SIZE; }
/** * 初始化密钥协商算法的乙方密钥对 * * @param publicKey 甲方公钥的二进制形式 * @return 乙方密钥对 */ public Map<String, Key> initKey(byte[] publicKey) { PublicKey pubKey = this.toPublicKey(publicKey); KeyPairGenerator keyPairGenerator = getKeyPairGenerator(); AlgorithmParameterSpec algorithmParameterSpec = null; if (pubKey instanceof DHKey) { algorithmParameterSpec = ((DHKey) pubKey).getParams(); } else if (pubKey instanceof ECKey) { algorithmParameterSpec = ((ECKey) pubKey).getParams(); } else { throw new CryptographyException(ExceptionInfo.NO_SUCH_ALGORITHM_EXCEPTION_INFO + getConfiguration().getKeyAlgorithm()); } try { keyPairGenerator.initialize(algorithmParameterSpec); } catch (InvalidAlgorithmParameterException e) { throw new CryptographyException(ExceptionInfo.NO_SUCH_ALGORITHM_EXCEPTION_INFO + getConfiguration().getKeyAlgorithm(), e); } KeyPair keyPair = keyPairGenerator.generateKeyPair(); Map<String, Key> keyMap = new HashMap<String, Key>(); keyMap.put(PRIVATE_KEY, keyPair.getPrivate()); keyMap.put(PUBLIC_KEY, keyPair.getPublic()); return keyMap; }
/** * Determines the name of the domain parameters that were used for generating the key. * * @param key An EC key * @return The name of the domain parameters that were used for the EC key, * or an empty string if curve is unknown. */ public static String getNamedCurve(Key key) { if (!(key instanceof ECKey)) { throw new InvalidParameterException("Not a EC private key."); } ECKey ecKey = (ECKey) key; ECParameterSpec params = ecKey.getParams(); if (!(params instanceof ECNamedCurveSpec)) { return ""; } ECNamedCurveSpec ecPrivateKeySpec = (ECNamedCurveSpec) params; String namedCurve = ecPrivateKeySpec.getName(); return namedCurve; }
private EcData(ECKey key, ECPoint q, BigInteger x) { ECParameterSpec params = key.getParams(); EllipticCurve curve = params.getCurve(); curveModulus = ((ECFieldFp) curve.getField()).getP().toByteArray(); curveA = curve.getA().toByteArray(); curveB = curve.getB().toByteArray(); gX = params.getGenerator().getAffineX().toByteArray(); gY = params.getGenerator().getAffineY().toByteArray(); n = params.getOrder().toByteArray(); if (q == null) { qX = null; qY = null; } else { qX = q.getAffineX().toByteArray(); qY = q.getAffineY().toByteArray(); } this.x = x == null ? null : x.toByteArray(); }
/** * Returns the 'order' parameter of a given ECDSA private key as a * a byte buffer. * @param privateKey A PrivateKey instance. Must implement ECKey. * @return A byte buffer corresponding to the 'order' parameter. * This is a big-endian representation of a BigInteger. */ @CalledByNative private static byte[] getECKeyOrder(PrivateKey privateKey) { if (privateKey instanceof ECKey) { ECParameterSpec params = ((ECKey) privateKey).getParams(); return params.getOrder().toByteArray(); } Log.w(TAG, "Not an ECKey instance!"); return null; }
private static Algorithm getAlgorithm(String algo, String key, boolean IsKeyASignerKey) throws IllegalArgumentException, UnsupportedEncodingException { if (algo.equals(HS256.getAlgorithm())) { return Algorithm.HMAC256(key); } if (algo.equals(HS384.getAlgorithm())) { return Algorithm.HMAC384(key); } if (algo.equals(HS512.getAlgorithm())) { return Algorithm.HMAC512(key); } if (algo.equals(ES256.getAlgorithm())) { return Algorithm.ECDSA256((ECKey) getKeyInstance(key, "EC", IsKeyASignerKey)); } if (algo.equals(ES384.getAlgorithm())) { return Algorithm.ECDSA384((ECKey) getKeyInstance(key, "EC", IsKeyASignerKey)); } if (algo.equals(ES512.getAlgorithm())) { return Algorithm.ECDSA512((ECKey) getKeyInstance(key, "EC",IsKeyASignerKey)); } if (algo.equals(RS256.getAlgorithm())) { return Algorithm.RSA256((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey)); } if (algo.equals(RS384.getAlgorithm())) { return Algorithm.RSA384((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey)); } if (algo.equals(RS512.getAlgorithm())) { return Algorithm.RSA512((RSAKey) getKeyInstance(key, "RSA", IsKeyASignerKey)); } return Algorithm.none(); }
@Test public void shouldPassECDSA256VerificationWithJOSESignature() throws Exception { String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g"; ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"); Algorithm algorithm = Algorithm.ECDSA256(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldThrowOnECDSA256VerificationWithDERSignature() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA"); exception.expectCause(isA(SignatureException.class)); exception.expectCause(hasMessage(is("Invalid JOSE signature format."))); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.MEYCIQDiJWTf5jS/hFPj/0hpCWn7x1n/h+xPMjKWCs9MMusS9AIhAMcFPJVLe2A9uvb8hl8sRO2IpGoKDRpDmyH14ixNPAHW"; ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"); Algorithm algorithm = Algorithm.ECDSA256(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA256VerificationWithInvalidPublicKey() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA"); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.W9qfN1b80B9hnMo49WL8THrOsf1vEjOhapeFemPMGySzxTcgfyudS5esgeBTO908X5SLdAr5jMwPUPBs9b6nNg"; Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA256VerificationWhenUsingPrivateKey() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA"); exception.expectCause(isA(IllegalStateException.class)); exception.expectCause(hasMessage(is("The given Public Key is null."))); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.W9qfN1b80B9hnMo49WL8THrOsf1vEjOhapeFemPMGySzxTcgfyudS5esgeBTO908X5SLdAr5jMwPUPBs9b6nNg"; Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA256VerificationOnInvalidJOSESignature() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA"); byte[] bytes = new byte[64]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA256VerificationOnInvalidDERSignature() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA"); byte[] bytes = new byte[64]; bytes[0] = 0x30; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldPassECDSA384VerificationWithJOSESignature() throws Exception { String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9.50UU5VKNdF1wfykY8jQBKpvuHZoe6IZBJm5NvoB8bR-hnRg6ti-CHbmvoRtlLfnHfwITa_8cJMy6TenMC2g63GQHytc8rYoXqbwtS4R0Ko_AXbLFUmfxnGnMC6v4MS_z"; ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"); Algorithm algorithm = Algorithm.ECDSA384(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldThrowOnECDSA384VerificationWithDERSignature() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA384withECDSA"); exception.expectCause(isA(SignatureException.class)); exception.expectCause(hasMessage(is("Invalid JOSE signature format."))); String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9.MGUCMQDnRRTlUo10XXB/KRjyNAEqm+4dmh7ohkEmbk2+gHxtH6GdGDq2L4Idua+hG2Ut+ccCMH8CE2v/HCTMuk3pzAtoOtxkB8rXPK2KF6m8LUuEdCqPwF2yxVJn8ZxpzAur+DEv8w=="; ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"); Algorithm algorithm = Algorithm.ECDSA384(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA384VerificationWithInvalidPublicKey() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA384withECDSA"); String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9._k5h1KyO-NE0R2_HAw0-XEc0bGT5atv29SxHhOGC9JDqUHeUdptfCK_ljQ01nLVt2OQWT2SwGs-TuyHDFmhPmPGFZ9wboxvq_ieopmYqhQilNAu-WF-frioiRz9733fU"; Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA384VerificationWhenUsingPrivateKey() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA384withECDSA"); exception.expectCause(isA(IllegalStateException.class)); exception.expectCause(hasMessage(is("The given Public Key is null."))); String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9._k5h1KyO-NE0R2_HAw0-XEc0bGT5atv29SxHhOGC9JDqUHeUdptfCK_ljQ01nLVt2OQWT2SwGs-TuyHDFmhPmPGFZ9wboxvq_ieopmYqhQilNAu-WF-frioiRz9733fU"; Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA384VerificationOnInvalidJOSESignatureLength() throws Exception { exception.expect(AlgorithmMismatchException.class); exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header."); byte[] bytes = new byte[95]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA384VerificationOnInvalidJOSESignature() throws Exception { exception.expect(AlgorithmMismatchException.class); exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header."); byte[] bytes = new byte[96]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_384, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldPassECDSA512VerificationWithJOSESignature() throws Exception { String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AeCJPDIsSHhwRSGZCY6rspi8zekOw0K9qYMNridP1Fu9uhrA1QrG-EUxXlE06yvmh2R7Rz0aE7kxBwrnq8L8aOBCAYAsqhzPeUvyp8fXjjgs0Eto5I0mndE2QHlgcMSFASyjHbU8wD2Rq7ZNzGQ5b2MZfpv030WGUajT-aZYWFUJHVg2"; ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"); Algorithm algorithm = Algorithm.ECDSA512(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldThrowOnECDSA512VerificationWithDERSignature() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA512withECDSA"); exception.expectCause(isA(SignatureException.class)); exception.expectCause(hasMessage(is("Invalid JOSE signature format."))); String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.MIGIAkIB4Ik8MixIeHBFIZkJjquymLzN6Q7DQr2pgw2uJ0/UW726GsDVCsb4RTFeUTTrK+aHZHtHPRoTuTEHCuerwvxo4EICQgGALKocz3lL8qfH1444LNBLaOSNJp3RNkB5YHDEhQEsox21PMA9kau2TcxkOW9jGX6b9N9FhlGo0/mmWFhVCR1YNg=="; ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"); Algorithm algorithm = Algorithm.ECDSA512(key); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA512VerificationWithInvalidPublicKey() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA512withECDSA"); String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AZgdopFFsN0amCSs2kOucXdpylD31DEm5ChK1PG0_gq5Mf47MrvVph8zHSVuvcrXzcE1U3VxeCg89mYW1H33Y-8iAF0QFkdfTUQIWKNObH543WNMYYssv3OtOj0znPv8atDbaF8DMYAtcT1qdmaSJRhx-egRE9HGZkinPh9CfLLLt58X"; Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA512VerificationWhenUsingPrivateKey() throws Exception { exception.expect(SignatureVerificationException.class); exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA512withECDSA"); exception.expectCause(isA(IllegalStateException.class)); exception.expectCause(hasMessage(is("The given Public Key is null."))); String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AZgdopFFsN0amCSs2kOucXdpylD31DEm5ChK1PG0_gq5Mf47MrvVph8zHSVuvcrXzcE1U3VxeCg89mYW1H33Y-8iAF0QFkdfTUQIWKNObH543WNMYYssv3OtOj0znPv8atDbaF8DMYAtcT1qdmaSJRhx-egRE9HGZkinPh9CfLLLt58X"; Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA512VerificationOnInvalidJOSESignatureLength() throws Exception { exception.expect(AlgorithmMismatchException.class); exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header."); byte[] bytes = new byte[131]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA512VerificationOnInvalidJOSESignature() throws Exception { exception.expect(AlgorithmMismatchException.class); exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header."); byte[] bytes = new byte[132]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailECDSA512VerificationOnInvalidDERSignature() throws Exception { exception.expect(AlgorithmMismatchException.class); exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header."); byte[] bytes = new byte[132]; new SecureRandom().nextBytes(bytes); bytes[0] = 0x30; String signature = Base64.encodeBase64URLSafeString(bytes); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldDoECDSA256Signing() throws Exception { Algorithm algorithmSign = Algorithm.ECDSA256((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC")); Algorithm algorithmVerify = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC")); String jwtContent = String.format("%s.%s", ES256Header, auth0IssPayload); byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithmSign.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithmVerify.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailOnECDSA256SigningWhenUsingPublicKey() throws Exception { exception.expect(SignatureGenerationException.class); exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: SHA256withECDSA"); exception.expectCause(isA(IllegalStateException.class)); exception.expectCause(hasMessage(is("The given Private Key is null."))); Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC")); algorithm.sign(new byte[0]); }
@Test public void shouldDoECDSA384Signing() throws Exception { Algorithm algorithmSign = Algorithm.ECDSA384((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC")); Algorithm algorithmVerify = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC")); String jwtContent = String.format("%s.%s", ES384Header, auth0IssPayload); byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithmSign.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithmVerify.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailOnECDSA384SigningWhenUsingPublicKey() throws Exception { exception.expect(SignatureGenerationException.class); exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: SHA384withECDSA"); exception.expectCause(isA(IllegalStateException.class)); exception.expectCause(hasMessage(is("The given Private Key is null."))); Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC")); algorithm.sign(new byte[0]); }
@Test public void shouldDoECDSA512Signing() throws Exception { Algorithm algorithmSign = Algorithm.ECDSA512((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC")); Algorithm algorithmVerify = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC")); String jwtContent = String.format("%s.%s", ES512Header, auth0IssPayload); byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithmSign.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithmVerify.verify(decoded, EncodeType.Base64); }
@Test public void shouldFailOnECDSA512SigningWhenUsingPublicKey() throws Exception { exception.expect(SignatureGenerationException.class); exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: SHA512withECDSA"); exception.expectCause(isA(IllegalStateException.class)); exception.expectCause(hasMessage(is("The given Private Key is null."))); Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC")); algorithm.sign(new byte[0]); }