/** * Generate a new keypair using the given Java Security Provider. * * All private key operations will use the provider. */ public ECKey(Provider provider, SecureRandom secureRandom) { this.provider = provider; KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom); KeyPair keyPair = keyPairGen.generateKeyPair(); this.privKey = keyPair.getPrivate(); PublicKey pubKey = keyPair.getPublic(); if (pubKey instanceof BCECPublicKey) { pub = ((BCECPublicKey) pubKey).getQ(); } else if (pubKey instanceof ECPublicKey) { pub = extractPublicKey((ECPublicKey) pubKey); } else { throw new AssertionError("Expected Provider " + provider.getName() + " to produce a subtype of ECPublicKey, found " + pubKey.getClass()); } }
/** * Generate a new keypair using the given Java Security Provider. * * All private key operations will use the provider. */ public ECKey(Provider provider, SecureRandom secureRandom) { this.provider = provider; final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom); final KeyPair keyPair = keyPairGen.generateKeyPair(); this.privKey = keyPair.getPrivate(); final PublicKey pubKey = keyPair.getPublic(); if (pubKey instanceof BCECPublicKey) { pub = ((BCECPublicKey) pubKey).getQ(); } else if (pubKey instanceof ECPublicKey) { pub = extractPublicKey((ECPublicKey) pubKey); } else { throw new AssertionError( "Expected Provider " + provider.getName() + " to produce a subtype of ECPublicKey, found " + pubKey.getClass()); } }
@Test public void shouldDecodeECDSA384JOSE() throws Exception { ECDSAAlgorithm algorithm384 = (ECDSAAlgorithm) Algorithm.ECDSA384((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC")); //Without padding byte[] joseSignature = createJOSESignature(48, false, false); byte[] derSignature = algorithm384.JOSEToDER(joseSignature); assertValidDERSignature(derSignature, 48, false, false); //With R padding joseSignature = createJOSESignature(48, true, false); derSignature = algorithm384.JOSEToDER(joseSignature); assertValidDERSignature(derSignature, 48, true, false); //With S padding joseSignature = createJOSESignature(48, false, true); derSignature = algorithm384.JOSEToDER(joseSignature); assertValidDERSignature(derSignature, 48, false, true); //With both paddings joseSignature = createJOSESignature(48, true, true); derSignature = algorithm384.JOSEToDER(joseSignature); assertValidDERSignature(derSignature, 48, true, true); }
/** * Extract the raw bytes of the public ECC key in standard smart card format. * @param publicKey the key to extract the bytes of. * @param curveReference the reference to the standard curve of the key. * @return the extract bytes of the key. */ public static byte[] decodeECCPublicKeyX509(PublicKey publicKey, EllipticCurveParameters curveReference) { byte[] publicKeyBytes = {}; if (publicKey instanceof ECPublicKey) { final ECPoint w = ((ECPublicKey)publicKey).getW(); final byte[] x = getStandardSizeInteger(w.getAffineX().toByteArray(), curveReference); final byte[] y = getStandardSizeInteger(w.getAffineY().toByteArray(), curveReference); publicKeyBytes = Bytes.concatenate(Bytes.bytes("04"), x, y); // Uncompressed format. } return publicKeyBytes; }
@Test public void shouldThrowOnSignWhenThePrivateKeyIsInvalid() throws Exception { exception.expect(SignatureGenerationException.class); exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: some-algorithm"); exception.expectCause(isA(InvalidKeyException.class)); CryptoHelper crypto = mock(CryptoHelper.class); when(crypto.createSignatureFor(anyString(), any(PrivateKey.class), any(byte[].class))) .thenThrow(InvalidKeyException.class); ECPublicKey publicKey = mock(ECPublicKey.class); ECPrivateKey privateKey = mock(ECPrivateKey.class); ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey); Algorithm algorithm = new ECDSAAlgorithm(crypto, "some-alg", "some-algorithm", 32, provider); algorithm.sign(ES256Header.getBytes(StandardCharsets.UTF_8)); }
/** * @param pair KeyPair to convert to an OpenSSH public key * @return OpenSSH-encoded pubkey */ public static byte[] extractOpenSSHPublic(KeyPair pair) { try { PublicKey pubKey = pair.getPublic(); if (pubKey instanceof RSAPublicKey) { return RSASHA1Verify.encodeSSHRSAPublicKey((RSAPublicKey) pubKey); } else if (pubKey instanceof DSAPublicKey) { return DSASHA1Verify.encodeSSHDSAPublicKey((DSAPublicKey) pubKey); } else if (pubKey instanceof ECPublicKey) { return ECDSASHA2Verify.encodeSSHECDSAPublicKey((ECPublicKey) pubKey); } else if (pubKey instanceof EdDSAPublicKey) { return Ed25519Verify.encodeSSHEd25519PublicKey((EdDSAPublicKey) pubKey); } else { return null; } } catch (IOException e) { return null; } }
@Test public void shouldDoECDSA512SigningWithProvidedPrivateKey() throws Exception { ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC"); PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"); when(provider.getPrivateKey()).thenReturn((ECPrivateKey) privateKey); when(provider.getPublicKeyById(null)).thenReturn((ECPublicKey) publicKey); Algorithm algorithm = Algorithm.ECDSA512(provider); String jwtContent = String.format("%s.%s", ES512Header, auth0IssPayload); byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithm.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
private void serverKeyExchange(ECDH_ServerKeyExchange mesg) throws IOException { if (debug != null && Debug.isOn("handshake")) { mesg.print(System.out); } ECPublicKey key = mesg.getPublicKey(); ecdh = new ECDHCrypt(key.getParams(), sslContext.getSecureRandom()); ephemeralServerKey = key; // check constraints of EC PublicKey if (!algorithmConstraints.permits( EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), ephemeralServerKey)) { throw new SSLHandshakeException("ECDH ServerKeyExchange " + "does not comply to algorithm constraints"); } }
public static boolean verifyECSignature(String encodededData, String encodedSignedData, String encodedPublicKey) throws CryptoException { try { KeyFactory keyFactory = KeyFactory.getInstance("EC"); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decode(encodedPublicKey, Base64.DEFAULT)); ECPublicKey publicKey = (ECPublicKey) keyFactory.generatePublic(publicKeySpec); Signature verificationFunction = Signature.getInstance(REST_AUTH_SIGNATURE_ALGORITHM); verificationFunction.initVerify(publicKey); verificationFunction.update(Base64.decode(encodededData, Base64.DEFAULT)); if (verificationFunction.verify(Base64.decode(encodedSignedData, Base64.DEFAULT))) { return true; } } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | SignatureException e) { throw new CryptoException("Unable to verify signature: " + e.getMessage()); } return false; }
private JWSHeader createServerTokenHeader(ECPublicKey serverPublicKey) { if (!serverPublicKey.getFormat().equals("X.509")) { throw new RuntimeException(String.format( "Server public key is not in X.509 format! Got %s instead", serverPublicKey.getFormat() )); } return new JWSHeader( JWSAlgorithm.ES384, null, null, null, null, null, URI.create(getServerPublicKeyBase64((ECPublicKey) serverKeyPair.getPublic())), null, null, null, null, null, null ); }
public static AlgorithmIdentifier getSigAlgId(PublicKey pubKey, HashAlgoType hashAlgo, SignatureAlgoControl algoControl) throws NoSuchAlgorithmException { ParamUtil.requireNonNull("hashAlgo", hashAlgo); if (pubKey instanceof RSAPublicKey) { boolean rsaMgf1 = (algoControl == null) ? false : algoControl.isRsaMgf1(); return getRSASigAlgId(hashAlgo, rsaMgf1); } else if (pubKey instanceof ECPublicKey) { boolean dsaPlain = (algoControl == null) ? false : algoControl.isDsaPlain(); boolean gm = (algoControl == null) ? false : algoControl.isGm(); return getECSigAlgId(hashAlgo, dsaPlain, gm); } else if (pubKey instanceof DSAPublicKey) { return getDSASigAlgId(hashAlgo); } else { throw new NoSuchAlgorithmException("Unknown public key '" + pubKey.getClass().getName()); } }
public P11PrivateKey(P11CryptService p11CryptService, P11EntityIdentifier identityId) throws P11TokenException { this.p11CryptService = ParamUtil.requireNonNull("identityId", p11CryptService); this.identityId = ParamUtil.requireNonNull("entityId", identityId); this.publicKey = p11CryptService.getIdentity(identityId).publicKey(); if (this.publicKey instanceof RSAPublicKey) { algorithm = "RSA"; keysize = ((RSAPublicKey) publicKey).getModulus().bitLength(); } else if (this.publicKey instanceof DSAPublicKey) { algorithm = "DSA"; keysize = ((DSAPublicKey) publicKey).getParams().getP().bitLength(); } else if (this.publicKey instanceof ECPublicKey) { algorithm = "EC"; keysize = ((ECPublicKey) publicKey).getParams().getCurve().getField().getFieldSize(); } else { throw new P11TokenException("unknown public key: " + publicKey); } }
/** * Returns the ECPublicKey instance from its encoded raw bytes. * The first byte has the fixed value 0x04 indicating the uncompressed form. * Therefore, the byte array must be of form: [0x04, x coord of point (32 bytes), y coord of point (32 bytes)] * * @param publicKeyBytes The byte array representing the encoded raw bytes of the public key * @return The ECPublicKey instance */ public static ECPublicKey getPublicKey(byte[] publicKeyBytes) { // First we separate x and y of coordinates into separate variables byte[] x = new byte[32]; byte[] y = new byte[32]; System.arraycopy(publicKeyBytes, 1, x, 0, 32); System.arraycopy(publicKeyBytes, 33, y, 0, 32); try { KeyFactory kf = KeyFactory.getInstance("EC"); AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC"); parameters.init(new ECGenParameterSpec("secp256r1")); ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class); ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)), ecParameterSpec); ECPublicKey ecPublicKey = (ECPublicKey) kf.generatePublic(ecPublicKeySpec); return ecPublicKey; } catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException e) { getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get public key from raw bytes", e); return null; } }
/** * Returns the public key part of an elliptic curve Diffie-Hellman keypair * * @param ecdhKeyPair The elliptic curve Diffie-Hellman keypair * @return The respective public key */ public static DiffieHellmanPublickeyType getDHPublicKey(KeyPair ecdhKeyPair) { DiffieHellmanPublickeyType dhPublicKey = new DiffieHellmanPublickeyType(); /* * Experience from the test symposium in San Diego (April 2016): * The Id element of the signature is not restricted in size by the standard itself. But on embedded * systems, the memory is very limited which is why we should not use long IDs for the signature reference * element. A good size would be 3 characters max (like the example in the ISO 15118-2 annex J) */ dhPublicKey.setId("id1"); byte[] uncompressedDHpublicKey = getUncompressedSubjectPublicKey((ECPublicKey) ecdhKeyPair.getPublic()); getLogger().debug("Created DHpublickey: " + ByteUtils.toHexString(uncompressedDHpublicKey)); dhPublicKey.setValue(uncompressedDHpublicKey); return dhPublicKey; }
@Test public void shouldThrowOnSignWhenTheSignatureIsNotPrepared() throws Exception { exception.expect(SignatureGenerationException.class); exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: some-algorithm"); exception.expectCause(isA(SignatureException.class)); CryptoHelper crypto = mock(CryptoHelper.class); when(crypto.createSignatureFor(anyString(), any(PrivateKey.class), any(byte[].class))) .thenThrow(SignatureException.class); ECPublicKey publicKey = mock(ECPublicKey.class); ECPrivateKey privateKey = mock(ECPrivateKey.class); ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey); Algorithm algorithm = new ECDSAAlgorithm(crypto, "some-alg", "some-algorithm", 32, provider); algorithm.sign(ES256Header.getBytes(StandardCharsets.UTF_8)); }
/** * Java puts some encoding information into the ECPublicKey.getEncoded(). * This method returns the raw ECPoint (the x and y coordinate of the public key) in uncompressed form * (with the 0x04 as first octet), aka the Subject Public Key according to RFC 5480 * * @param ecPublicKey The ECPublicKey provided by Java * @return The uncompressed Subject Public Key (with the first octet set to 0x04) */ public static byte[] getUncompressedSubjectPublicKey(ECPublicKey ecPublicKey) { byte[] uncompressedPubKey = new byte[65]; uncompressedPubKey[0] = 0x04; byte[] affineX = ecPublicKey.getW().getAffineX().toByteArray(); byte[] affineY = ecPublicKey.getW().getAffineY().toByteArray(); // If the length is 33 bytes, then the first byte is a 0x00 which is to be omitted if (affineX.length == 33) System.arraycopy(affineX, 1, uncompressedPubKey, 1, 32); else System.arraycopy(affineX, 0, uncompressedPubKey, 1, 32); if (affineY.length == 33) System.arraycopy(affineY, 1, uncompressedPubKey, 33, 32); else System.arraycopy(affineY, 0, uncompressedPubKey, 33, 32); return uncompressedPubKey; }
/** * Check key encryption parameters for consistency and required values. * * @param kekParams the key encryption parameters to check * @param allowEmpty if false, a null parameter is treated as an error * * @throws EncryptionException thrown if any parameters are missing or have invalid values */ protected void checkParams(KeyEncryptionParameters kekParams, boolean allowEmpty) throws EncryptionException { if (kekParams == null) { if (allowEmpty) { return; } else { log.error("Key encryption parameters are required"); throw new EncryptionException("Key encryption parameters are required"); } } Key key = SecurityHelper.extractEncryptionKey(kekParams.getEncryptionCredential()); if (key == null) { log.error("Key encryption credential and contained key are required"); throw new EncryptionException("Key encryption credential and contained key are required"); } else if (key instanceof DSAPublicKey) { log.error("Attempt made to use DSA key for encrypted key transport"); throw new EncryptionException("DSA keys may not be used for encrypted key transport"); } else if (key instanceof ECPublicKey) { log.error("Attempt made to use EC key for encrypted key transport"); throw new EncryptionException("EC keys may not be used for encrypted key transport"); } else if (DatatypeHelper.isEmpty(kekParams.getAlgorithm())) { log.error("Key encryption algorithm URI is required"); throw new EncryptionException("Key encryption algorithm URI is required"); } }
protected Key engineDoPhase(Key key, boolean lastPhase) throws InvalidKeyException, IllegalStateException { if (privateKey == null) { throw new IllegalStateException("Not initialized"); } if (publicValue != null) { throw new IllegalStateException("Phase already executed"); } if (lastPhase == false) { throw new IllegalStateException ("Only two party agreement supported, lastPhase must be true"); } if (key instanceof ECPublicKey == false) { throw new InvalidKeyException ("Key must be a PublicKey with algorithm EC"); } ECPublicKey ecKey = (ECPublicKey)key; int keyLenBits = ecKey.getParams().getCurve().getField().getFieldSize(); secretLen = (keyLenBits + 7) >> 3; publicValue = P11ECKeyFactory.getEncodedPublicValue(ecKey); return null; }
@Test public void shouldDecodeECDSA512DER() throws Exception { ECDSAAlgorithm algorithm512 = (ECDSAAlgorithm) Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC")); //Without padding byte[] derSignature = createDERSignature(66, false, false); byte[] joseSignature = algorithm512.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 66, false, false); //With R padding derSignature = createDERSignature(66, true, false); joseSignature = algorithm512.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 66, true, false); //With S padding derSignature = createDERSignature(66, false, true); joseSignature = algorithm512.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 66, false, true); //With both paddings derSignature = createDERSignature(66, true, true); joseSignature = algorithm512.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 66, true, true); }
@Test public void shouldDecodeECDSA256JOSE() throws Exception { ECDSAAlgorithm algorithm256 = (ECDSAAlgorithm) Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC")); //Without padding byte[] joseSignature = createJOSESignature(32, false, false); byte[] derSignature = algorithm256.JOSEToDER(joseSignature); assertValidDERSignature(derSignature, 32, false, false); //With R padding joseSignature = createJOSESignature(32, true, false); derSignature = algorithm256.JOSEToDER(joseSignature); assertValidDERSignature(derSignature, 32, true, false); //With S padding joseSignature = createJOSESignature(32, false, true); derSignature = algorithm256.JOSEToDER(joseSignature); assertValidDERSignature(derSignature, 32, false, true); //With both paddings joseSignature = createJOSESignature(32, true, true); derSignature = algorithm256.JOSEToDER(joseSignature); assertValidDERSignature(derSignature, 32, true, true); }
@Test public void shouldFailJOSEToDERConversionOnInvalidJOSESignatureLength() 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[256]; new SecureRandom().nextBytes(bytes); String signature = Base64.encodeBase64URLSafeString(bytes); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature; ECPublicKey publicKey = (ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"); ECPrivateKey privateKey = mock(ECPrivateKey.class); ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey); Algorithm algorithm = new ECDSAAlgorithm("ES256", "SHA256withECDSA", 128, provider); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldThrowOnVerifyWhenThePublicKeyIsInvalid() throws Exception { exception.expect(AlgorithmMismatchException.class); exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header."); CryptoHelper crypto = mock(CryptoHelper.class); when(crypto.verifySignatureFor(anyString(), any(PublicKey.class), any(byte[].class), any(byte[].class))) .thenThrow(InvalidKeyException.class); ECPublicKey publicKey = mock(ECPublicKey.class); ECPrivateKey privateKey = mock(ECPrivateKey.class); ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey); Algorithm algorithm = new ECDSAAlgorithm(crypto, "some-alg", "some-algorithm", 32, provider); String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g"; JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldDoECDSA384SigningWithProvidedPrivateKey() throws Exception { ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC"); PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"); when(provider.getPrivateKey()).thenReturn((ECPrivateKey) privateKey); when(provider.getPublicKeyById(null)).thenReturn((ECPublicKey) publicKey); Algorithm algorithm = Algorithm.ECDSA384(provider); String jwtContent = String.format("%s.%s", ES384Header, auth0IssPayload); byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = algorithm.sign(contentBytes); String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes); String token = String.format("%s.%s", jwtContent, jwtSignature); assertThat(signatureBytes, is(notNullValue())); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
@Test public void shouldDecodeECDSA384DER() throws Exception { ECDSAAlgorithm algorithm384 = (ECDSAAlgorithm) Algorithm.ECDSA384((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC")); //Without padding byte[] derSignature = createDERSignature(48, false, false); byte[] joseSignature = algorithm384.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 48, false, false); //With R padding derSignature = createDERSignature(48, true, false); joseSignature = algorithm384.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 48, true, false); //With S padding derSignature = createDERSignature(48, false, true); joseSignature = algorithm384.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 48, false, true); //With both paddings derSignature = createDERSignature(48, true, true); joseSignature = algorithm384.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 48, true, true); }
@Test public void shouldDecodeECDSA256DER() throws Exception { ECDSAAlgorithm algorithm256 = (ECDSAAlgorithm) Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC")); //Without padding byte[] derSignature = createDERSignature(32, false, false); byte[] joseSignature = algorithm256.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 32, false, false); //With R padding derSignature = createDERSignature(32, true, false); joseSignature = algorithm256.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 32, true, false); //With S padding derSignature = createDERSignature(32, false, true); joseSignature = algorithm256.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 32, false, true); //With both paddings derSignature = createDERSignature(32, true, true); joseSignature = algorithm256.DERToJOSE(derSignature); assertValidJOSESignature(joseSignature, 32, true, true); }
@Test public void shouldSignAndVerifyWithECDSA384() throws Exception { ECDSAAlgorithm algorithm384 = (ECDSAAlgorithm) Algorithm.ECDSA384((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC")); String content384 = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9"; for (int i = 0; i < 10; i++) { byte[] signature = algorithm384.sign(content384.getBytes()); String signature384 = Base64.encodeBase64URLSafeString((signature)); String token = content384 + "." + signature384; JWT jwt = JWT.require(algorithm384).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm384.verify(decoded, EncodeType.Base64); } }
@Test public void recoverKeyPair_Ec() throws Exception { KeyPair kp = PubkeyUtils.recoverKeyPair(EC_KEY_PKCS8); ECPublicKey pubKey = (ECPublicKey) kp.getPublic(); assertEquals(EC_KEY_pub_x, pubKey.getW().getAffineX()); assertEquals(EC_KEY_pub_y, pubKey.getW().getAffineY()); }
private static ECPoint extractPublicKey(final ECPublicKey ecPublicKey) { final java.security.spec.ECPoint publicPointW = ecPublicKey.getW(); final BigInteger xCoord = publicPointW.getAffineX(); final BigInteger yCoord = publicPointW.getAffineY(); return CURVE.getCurve().createPoint(xCoord, yCoord); }
@Test public void shouldPassECDSA512VerificationWithJOSESignatureWithBothKeys() throws Exception { String token = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.AeCJPDIsSHhwRSGZCY6rspi8zekOw0K9qYMNridP1Fu9uhrA1QrG-EUxXlE06yvmh2R7Rz0aE7kxBwrnq8L8aOBCAYAsqhzPeUvyp8fXjjgs0Eto5I0mndE2QHlgcMSFASyjHbU8wD2Rq7ZNzGQ5b2MZfpv030WGUajT-aZYWFUJHVg2"; Algorithm algorithm = Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC")); JWT jwt = JWT.require(algorithm).withIssuer("auth0").build(); DecodedJWT decoded = jwt.decode(token); algorithm.verify(decoded, EncodeType.Base64); }
public BCDSTU4145PublicKey( ECPublicKey key) { this.algorithm = key.getAlgorithm(); this.ecSpec = key.getParams(); this.q = EC5Util.convertPoint(this.ecSpec, key.getW(), false); }
public BCECPublicKey( ECPublicKey key, ProviderConfiguration configuration) { this.algorithm = key.getAlgorithm(); this.ecSpec = key.getParams(); this.q = EC5Util.convertPoint(this.ecSpec, key.getW(), false); }