Java Code Examples for java.security.interfaces.ECKey

The following examples show how to use java.security.interfaces.ECKey. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: openjsse   Source File: X509Authentication.java    License: GNU General Public License v2.0 6 votes vote down vote up
ECParameterSpec getECParameterSpec() {
    if (popPrivateKey == null ||
            !"EC".equals(popPrivateKey.getAlgorithm())) {
        return null;
    }

    if (popPrivateKey instanceof ECKey) {
        return ((ECKey)popPrivateKey).getParams();
    } else if (popCerts != null && popCerts.length != 0) {
        // The private key not extractable, get the parameters from
        // the X.509 certificate.
        PublicKey publicKey = popCerts[0].getPublicKey();
        if (publicKey instanceof ECKey) {
            return ((ECKey)publicKey).getParams();
        }
    }

    return null;
}
 
Example 2
Source Project: Bytecoder   Source File: X509Authentication.java    License: Apache License 2.0 6 votes vote down vote up
ECParameterSpec getECParameterSpec() {
    if (popPrivateKey == null ||
            !"EC".equals(popPrivateKey.getAlgorithm())) {
        return null;
    }

    if (popPrivateKey instanceof ECKey) {
        return ((ECKey)popPrivateKey).getParams();
    } else if (popCerts != null && popCerts.length != 0) {
        // The private key not extractable, get the parameters from
        // the X.509 certificate.
        PublicKey publicKey = popCerts[0].getPublicKey();
        if (publicKey instanceof ECKey) {
            return ((ECKey)publicKey).getParams();
        }
    }

    return null;
}
 
Example 3
Source Project: MaxKey   Source File: KeyPairUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
	}

	_logger.warn("Don't know how to get key size from key " + pubKey);
	return UNKNOWN_KEY_SIZE;
}
 
Example 4
Source Project: crypto   Source File: KeyAgreementCryptography.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 初始化密钥协商算法的乙方密钥对
 *
 * @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;
}
 
Example 5
Source Project: swim   Source File: JsonWebSignature.java    License: Apache License 2.0 5 votes vote down vote up
public static JsonWebSignature sign(PrivateKey privateKey, Value unprotectedHeader,
                                    Value protectedHeader, Data payloadData) {
  if (privateKey instanceof ECKey) {
    return signECDSA(privateKey, unprotectedHeader, protectedHeader, payloadData);
  } else if (privateKey instanceof RSAKey) {
    return signRSA(privateKey, unprotectedHeader, protectedHeader, payloadData);
  } else {
    throw new IllegalArgumentException("unsupported signing key type");
  }
}
 
Example 6
Source Project: swim   Source File: JsonWebSignature.java    License: Apache License 2.0 5 votes vote down vote up
static int ecKeyLength(Key key) {
  final int bitLength = ((ECKey) key).getParams().getOrder().bitLength();
  if (bitLength <= 256) {
    return 32;
  } else if (bitLength <= 384) {
    return 48;
  } else if (bitLength <= 521) {
    return 66;
  } else {
    throw new IllegalArgumentException("unsupported key size");
  }
}
 
Example 7
Source Project: swim   Source File: JsonWebKey.java    License: Apache License 2.0 5 votes vote down vote up
public ECKey ecKey() {
  if (this.value.containsKey("d")) {
    return ecPrivateKey();
  } else {
    return ecPublicKey();
  }
}
 
Example 8
Source Project: browserup-proxy   Source File: EncryptionUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the type of digital signature used with the specified signing key.
 *
 * @param signingKey private key that will be used to sign a certificate (or something else)
 * @return a string representing the digital signature type (ECDSA, RSA, etc.)
 */
public static String getDigitalSignatureType(Key signingKey) {
    if (signingKey instanceof ECKey) {
        return "ECDSA";
    } else if (signingKey instanceof RSAKey) {
        return "RSA";
    } else if (signingKey instanceof DSAKey) {
        return "DSA";
    } else {
        throw new IllegalArgumentException("Cannot determine digital signature encryption type for unknown key type: " + signingKey.getClass().getCanonicalName());
    }

}
 
Example 9
Source Project: CapturePacket   Source File: EncryptionUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the type of digital signature used with the specified signing key.
 *
 * @param signingKey private key that will be used to sign a certificate (or something else)
 * @return a string representing the digital signature type (ECDSA, RSA, etc.)
 */
public static String getDigitalSignatureType(Key signingKey) {
    if (signingKey instanceof ECKey) {
        return "ECDSA";
    } else if (signingKey instanceof RSAKey) {
        return "RSA";
    } else if (signingKey instanceof DSAKey) {
        return "DSA";
    } else {
        throw new IllegalArgumentException("Cannot determine digital signature encryption type for unknown key type: " + signingKey.getClass().getCanonicalName());
    }

}
 
Example 10
Source Project: Launcher   Source File: SecurityHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static Cipher newECCipher(int mode, ECKey key) {
    Cipher cipher = newBCCipher(EC_CIPHER_ALGO);
    try {
        cipher.init(mode, (Key) key);
    } catch (InvalidKeyException e) {
        throw new InternalError(e);
    }
    return cipher;
}
 
Example 11
Source Project: lams   Source File: EllipticCurveSigner.java    License: GNU General Public License v2.0 5 votes vote down vote up
public EllipticCurveSigner(SignatureAlgorithm alg, Key key) {
    super(alg, key);
    if (!(key instanceof PrivateKey && key instanceof ECKey)) {
        String msg = "Elliptic Curve signatures must be computed using an EC PrivateKey.  The specified key of " +
                     "type " + key.getClass().getName() + " is not an EC PrivateKey.";
        throw new IllegalArgumentException(msg);
    }
}
 
Example 12
Source Project: Bytecoder   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private String fullDisplayAlgName(Key key) {
    String result = key.getAlgorithm();
    if (key instanceof ECKey) {
        ECParameterSpec paramSpec = ((ECKey) key).getParams();
        if (paramSpec instanceof NamedCurve) {
            result += " (" + paramSpec.toString().split(" ")[0] + ")";
        }
    }
    return result;
}
 
Example 13
Source Project: Bytecoder   Source File: ConstraintsParameters.java    License: Apache License 2.0 5 votes vote down vote up
public static String[] getNamedCurveFromKey(Key key) {
    if (key instanceof ECKey) {
        NamedCurve nc = CurveDB.lookup(((ECKey)key).getParams());
        return (nc == null ? EMPTYLIST : CurveDB.getNamesByOID(nc.getObjectId()));
    } else if (key instanceof XECKey) {
        String[] s = {
                ((NamedParameterSpec)((XECKey)key).getParams()).getName()
        };
        return s;
    } else {
        return EMPTYLIST;
    }
}
 
Example 14
Source Project: walle   Source File: V2SchemeSigner.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 15
Source Project: java-jwt   Source File: JWTTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldAcceptECDSA256Algorithm() throws Exception {
    String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g";
    ECKey key = (ECKey) PemUtils.readPublicKeyFromFile(PUBLIC_KEY_FILE_EC_256, "EC");
    DecodedJWT jwt = JWT.require(Algorithm.ECDSA256(key))
            .build()
            .verify(token);

    assertThat(jwt, is(notNullValue()));
}
 
Example 16
Source Project: java-jwt   Source File: ConcurrentVerifyTest.java    License: MIT License 5 votes vote down vote up
@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);
    JWTVerifier verifier = JWTVerifier.init(algorithm).withIssuer("auth0").build();

    concurrentVerify(verifier, token);
}
 
Example 17
Source Project: fusionauth-jwt   Source File: KeyUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return the length of the key in bits.
 *
 * @param key the key
 * @return the length in bites of the provided key.
 */
public static int getKeyLength(Key key) {
  if (key instanceof ECKey) {
    int bytes;
    if (key instanceof ECPublicKey) {
      ECPublicKey ecPublicKey = (ECPublicKey) key;
      bytes = ecPublicKey.getW().getAffineX().toByteArray().length;
    } else {
      ECPrivateKey ecPrivateKey = (ECPrivateKey) key;
      bytes = ecPrivateKey.getS().toByteArray().length;
    }

    if (bytes >= 63 && bytes <= 66) {
      return 521;
    }

    // If bytes is not a multiple of 8, add one byte
    if (bytes % 8 != 0) {
      bytes = bytes + 1;
    }

    return ((bytes / 8) * 8) * 8;
  } else if (key instanceof RSAKey) {
    return ((RSAKey) key).getModulus().bitLength();
  }

  throw new IllegalArgumentException();
}
 
Example 18
Source Project: hono   Source File: JwtHelper.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets the path to a PKCS8 PEM file containing the RSA private key to use for signing tokens asserting the
 * registration status of devices.
 *
 * @param keyPath The absolute path to the file.
 * @throws NullPointerException if the path is {@code null}.
 * @throws IllegalArgumentException if the key cannot be read from the file.
 */
protected final void setPrivateKey(final String keyPath) {
    Objects.requireNonNull(keyPath);
    key = KeyLoader.fromFiles(vertx, keyPath, null).getPrivateKey();
    if (key == null) {
        throw new IllegalArgumentException("cannot load private key: " + keyPath);
    } else if (key instanceof ECKey) {
        algorithm = SignatureAlgorithm.ES256;
    } else if (key instanceof RSAKey) {
        algorithm = SignatureAlgorithm.RS256;
    } else {
        throw new IllegalArgumentException("unsupported private key type: " + key.getClass());
    }
}
 
Example 19
Source Project: java-jwt   Source File: ECDSAAlgorithmTest.java    License: MIT License 5 votes vote down vote up
@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 jwt = asJWT(algorithmSign, ES512Header, auth0IssPayload);

    assertSignaturePresent(jwt);
    algorithmVerify.verify(JWT.decode(jwt));
}
 
Example 20
Source Project: Dream-Catcher   Source File: EncryptionUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the type of digital signature used with the specified signing key.
 *
 * @param signingKey private key that will be used to sign a certificate (or something else)
 * @return a string representing the digital signature type (ECDSA, RSA, etc.)
 */
public static String getDigitalSignatureType(Key signingKey) {
    if (signingKey instanceof ECKey) {
        return "ECDSA";
    } else if (signingKey instanceof RSAKey) {
        return "RSA";
    } else if (signingKey instanceof DSAKey) {
        return "DSA";
    } else {
        throw new IllegalArgumentException("Cannot determine digital signature encryption type for unknown key type: " + signingKey.getClass().getCanonicalName());
    }

}
 
Example 21
Source Project: Jose4j   Source File: EcdsaUsingShaAlgorithm.java    License: Apache License 2.0 5 votes vote down vote up
private void validateKeySpec(ECKey ecKey) throws InvalidKeyException
{
    ECParameterSpec spec = ecKey.getParams();
    EllipticCurve curve = spec.getCurve();

    String name = EllipticCurves.getName(curve);

    if (!getCurveName().equals(name))
    {
        throw new InvalidKeyException(getAlgorithmIdentifier() + "/" + getJavaAlgorithm() + " expects a key using " +
                getCurveName() + " but was " + name);
    }
}
 
Example 22
Source Project: ECTester   Source File: ECUtil.java    License: MIT License 5 votes vote down vote up
public static ECKey loadKey(short params, String named, String file, AlgorithmParameterSpec spec) throws IOException {
    if (params == EC_Consts.PARAMETERS_KEYPAIR) {
        throw new IllegalArgumentException();
    }
    EC_Params param = loadParams(params, named, file);
    if (param != null) {
        if (params == EC_Consts.PARAMETER_W) {
            return new RawECPublicKey(toPoint(param), (ECParameterSpec) spec);
        } else if (params == EC_Consts.PARAMETER_S) {
            return new RawECPrivateKey(toScalar(param), (ECParameterSpec) spec);
        }
    }
    return null;
}
 
Example 23
Source Project: AndroidHttpCapture   Source File: EncryptionUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the type of digital signature used with the specified signing key.
 *
 * @param signingKey private key that will be used to sign a certificate (or something else)
 * @return a string representing the digital signature type (ECDSA, RSA, etc.)
 */
public static String getDigitalSignatureType(Key signingKey) {
    if (signingKey instanceof ECKey) {
        return "ECDSA";
    } else if (signingKey instanceof RSAKey) {
        return "RSA";
    } else if (signingKey instanceof DSAKey) {
        return "DSA";
    } else {
        throw new IllegalArgumentException("Cannot determine digital signature encryption type for unknown key type: " + signingKey.getClass().getCanonicalName());
    }

}
 
Example 24
Source Project: java-jwt   Source File: JWTTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldCreateAnEmptyECDSA256SignedToken() throws Exception {
    String signed = JWT.create().sign(Algorithm.ECDSA256((ECKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_EC_256, "EC")));
    assertThat(signed, is(notNullValue()));

    String[] parts = signed.split("\\.");
    String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8);
    assertThat(headerJson, JsonMatcher.hasEntry("alg", "ES256"));
    assertThat(headerJson, JsonMatcher.hasEntry("typ", "JWT"));
    assertThat(parts[1], is("e30"));

    JWTVerifier verified = JWT.require(Algorithm.ECDSA256((ECKey) PemUtils.readPublicKeyFromFile(PUBLIC_KEY_FILE_EC_256, "EC")))
            .build();
    assertThat(verified, is(notNullValue()));
}
 
Example 25
Source Project: java-jwt   Source File: ECDSABouncyCastleProviderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldPassECDSA256VerificationWithJOSESignature() throws Exception {
    String jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g";
    ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC");
    Algorithm algorithm = Algorithm.ECDSA256(key);
    algorithm.verify(JWT.decode(jwt));
}
 
Example 26
Source Project: java-jwt   Source File: ECDSABouncyCastleProviderTests.java    License: MIT License 5 votes vote down vote up
@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 jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.MEYCIQDiJWTf5jS/hFPj/0hpCWn7x1n/h+xPMjKWCs9MMusS9AIhAMcFPJVLe2A9uvb8hl8sRO2IpGoKDRpDmyH14ixNPAHW";
    ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC");
    Algorithm algorithm = Algorithm.ECDSA256(key);
    algorithm.verify(JWT.decode(jwt));
}
 
Example 27
Source Project: java-jwt   Source File: ECDSABouncyCastleProviderTests.java    License: MIT License 5 votes vote down vote up
@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 jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.W9qfN1b80B9hnMo49WL8THrOsf1vEjOhapeFemPMGySzxTcgfyudS5esgeBTO908X5SLdAr5jMwPUPBs9b6nNg";
    Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC"));
    algorithm.verify(JWT.decode(jwt));
}
 
Example 28
Source Project: java-jwt   Source File: ECDSABouncyCastleProviderTests.java    License: MIT License 5 votes vote down vote up
@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 jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.W9qfN1b80B9hnMo49WL8THrOsf1vEjOhapeFemPMGySzxTcgfyudS5esgeBTO908X5SLdAr5jMwPUPBs9b6nNg";
    Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC"));
    algorithm.verify(JWT.decode(jwt));
}
 
Example 29
Source Project: java-jwt   Source File: ECDSABouncyCastleProviderTests.java    License: MIT License 5 votes vote down vote up
@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 jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature;
    Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC"));
    algorithm.verify(JWT.decode(jwt));
}
 
Example 30
Source Project: java-jwt   Source File: ECDSABouncyCastleProviderTests.java    License: MIT License 5 votes vote down vote up
@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 jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature;
    Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC"));
    algorithm.verify(JWT.decode(jwt));
}