java.security.interfaces.ECPrivateKey Java Examples

The following examples show how to use java.security.interfaces.ECPrivateKey. 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 File: ECDSABouncyCastleProviderTests.java    From java-jwt with MIT License 6 votes vote down vote up
@Test
public void shouldThrowOnVerifyWhenThePublicKeyIsInvalid() throws Exception {
    exception.expect(SignatureVerificationException.class);
    exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: some-alg");
    exception.expectCause(isA(InvalidKeyException.class));

    CryptoHelper crypto = mock(CryptoHelper.class);
    when(crypto.verifySignatureFor(anyString(), any(PublicKey.class), any(String.class), any(String.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 jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g";
    algorithm.verify(JWT.decode(jwt));
}
 
Example #2
Source File: BaseTestSupport.java    From termd with Apache License 2.0 6 votes vote down vote up
public static <T extends Key> void assertKeyEquals(String message, T expected, T actual) {
    if (expected == actual) {
        return;
    }

    assertEquals(message + "[algorithm]", expected.getAlgorithm(), actual.getAlgorithm());

    if (expected instanceof RSAPublicKey) {
        assertRSAPublicKeyEquals(message, RSAPublicKey.class.cast(expected), RSAPublicKey.class.cast(actual));
    } else if (expected instanceof DSAPublicKey) {
        assertDSAPublicKeyEquals(message, DSAPublicKey.class.cast(expected), DSAPublicKey.class.cast(actual));
    } else if (expected instanceof ECPublicKey) {
        assertECPublicKeyEquals(message, ECPublicKey.class.cast(expected), ECPublicKey.class.cast(actual));
    } else if (expected instanceof RSAPrivateKey) {
        assertRSAPrivateKeyEquals(message, RSAPrivateKey.class.cast(expected), RSAPrivateKey.class.cast(actual));
    } else if (expected instanceof ECPrivateKey) {
        assertECPrivateKeyEquals(message, ECPrivateKey.class.cast(expected), ECPrivateKey.class.cast(actual));
    }
    assertArrayEquals(message + "[encdoded-data]", expected.getEncoded(), actual.getEncoded());
}
 
Example #3
Source File: EcdhHelper.java    From cxf with Apache License 2.0 6 votes vote down vote up
public byte[] getDerivedKey(JweHeaders headers) {
    KeyPair pair = CryptoUtils.generateECKeyPair(ecurve);
    ECPublicKey publicKey = (ECPublicKey)pair.getPublic();
    ECPrivateKey privateKey = (ECPrivateKey)pair.getPrivate();
    KeyAlgorithm keyAlgo = headers.getKeyEncryptionAlgorithm();
    ContentAlgorithm contentAlgo = ContentAlgorithm.valueOf(ctAlgo);
    String algorithm = (KeyAlgorithm.isDirect(keyAlgo)) ? contentAlgo.getJwaName() : keyAlgo.getJwaName();
    int keySizeBits = (KeyAlgorithm.isDirect(keyAlgo)) ? contentAlgo.getKeySizeBits() : keyAlgo.getKeySizeBits();

    if (apuBytes != null) {
        headers.setHeader("apu", Base64UrlUtility.encode(apuBytes));
    }
    if (apvBytes != null) {
        headers.setHeader("apv", Base64UrlUtility.encode(apvBytes));
    }
    headers.setJsonWebKey("epk", JwkUtils.fromECPublicKey(publicKey, ecurve));

    return JweUtils.getECDHKey(privateKey, peerPublicKey, apuBytes, apvBytes,
                               algorithm, keySizeBits);
}
 
Example #4
Source File: ECKeyTest.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
@Test
public void testToJsonWebKey() throws Exception {
	ECGenParameterSpec gps = new ECGenParameterSpec(EcKey.P521);
	EC_KEY_GENERATOR.initialize(gps);
	KeyPair keyPair = EC_KEY_GENERATOR.generateKeyPair();
	
	ECPublicKey apub = (ECPublicKey) keyPair.getPublic();
	ECPoint point = apub.getW();
	ECPrivateKey apriv = (ECPrivateKey) keyPair.getPrivate();
	
	JsonWebKey jwk = new JsonWebKey()
			.withKid("kid")
			.withCrv(JsonWebKeyCurveName.P_521)
			.withX(point.getAffineX().toByteArray())
			.withY(point.getAffineY().toByteArray())
			.withD(apriv.getS().toByteArray())
			.withKty(JsonWebKeyType.EC);
	
	EcKey newKey = new EcKey("kid", keyPair);
	
	JsonWebKey newJwk = newKey.toJsonWebKey();
	//set missing parameters
	newJwk.withKid("kid");
	
	assertEquals(jwk, newJwk);	
}
 
Example #5
Source File: ECDSABouncyCastleProviderTests.java    From java-jwt with MIT License 6 votes vote down vote up
@Test
public void shouldThrowOnVerifyWhenTheSignatureIsNotPrepared() throws Exception {
    exception.expect(SignatureVerificationException.class);
    exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: some-alg");
    exception.expectCause(isA(SignatureException.class));

    CryptoHelper crypto = mock(CryptoHelper.class);
    when(crypto.verifySignatureFor(anyString(), any(PublicKey.class), any(String.class), any(String.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);
    String jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g";
    algorithm.verify(JWT.decode(jwt));
}
 
Example #6
Source File: ECDH.java    From thunder with GNU Affero General Public License v3.0 6 votes vote down vote up
public static ECDHKeySet getSharedSecret (ECKey keyServer, ECKey keyClient) {
    try {

        ECPrivateKeySpec specPrivate = new ECPrivateKeySpec(keyServer.getPrivKey(), ecParameters);
        ECPublicKeySpec specPublic = new ECPublicKeySpec(new ECPoint(keyClient.getPubKeyPoint().getXCoord().toBigInteger(), keyClient.getPubKeyPoint()
                .getYCoord().toBigInteger()), ecParameters);

        ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(specPrivate);
        ECPublicKey publicKey = (ECPublicKey) kf.generatePublic(specPublic);

        JCEECPrivateKey ecPrivKey = new JCEECPrivateKey(privateKey);
        JCEECPublicKey ecPubKey = new JCEECPublicKey(publicKey);

        KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH");
        aKeyAgree.init(ecPrivKey);
        aKeyAgree.doPhase(ecPubKey, true);

        return new ECDHKeySet(aKeyAgree.generateSecret(), keyServer.getPubKey(), keyClient.getPubKey());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: JwtSignatureImpl.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
static String keyAlgorithm(Map<String, Object> headers, Key signingKey) {
    String alg = (String) headers.get("alg");
    if (signingKey instanceof RSAPrivateKey) {
        if (alg == null) {
            return SignatureAlgorithm.RS256.name();
        } else if (alg.startsWith("RS")) {
            return alg;
        }
    } else if (signingKey instanceof ECPrivateKey) {
        if (alg == null) {
            return SignatureAlgorithm.ES256.name();
        } else if (alg.startsWith("ES")) {
            return alg;
        }
    } else if (signingKey instanceof SecretKey) {
        if (alg == null) {
            return SignatureAlgorithm.HS256.name();
        } else if (alg.startsWith("HS")) {
            return alg;
        }
    }
    throw ImplMessages.msg.unsupportedSignatureAlgorithm(signingKey.getAlgorithm());
}
 
Example #8
Source File: ECDSAAlgorithmTest.java    From java-jwt with MIT License 6 votes vote down vote up
@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);
}
 
Example #9
Source File: ECDSAAlgorithmTest.java    From java-jwt with MIT License 6 votes vote down vote up
@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), 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(ES256HeaderBytes, new byte[0]);
}
 
Example #10
Source File: TestKeycardCommandSet.java    From status-keycard with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a LOAD KEY APDU. The given private key and chain code are formatted as a raw binary seed and the P1 of
 * the command is set to LOAD_KEY_P1_SEED (0x03). This works on cards which support public key derivation.
 * The loaded keyset is extended and support further key derivation.
 *
 * @param aPrivate a private key
 * @param chainCode the chain code
 * @return the raw card response
 * @throws IOException communication error
 */
public APDUResponse loadKey(PrivateKey aPrivate, byte[] chainCode) throws IOException {
  byte[] privateKey = ((ECPrivateKey) aPrivate).getS().toByteArray();

  int privLen = privateKey.length;
  int privOff = 0;

  if(privateKey[0] == 0x00) {
    privOff++;
    privLen--;
  }

  byte[] data = new byte[chainCode.length + privLen];
  System.arraycopy(privateKey, privOff, data, 0, privLen);
  System.arraycopy(chainCode, 0, data, privLen, chainCode.length);

  return loadKey(data, LOAD_KEY_P1_SEED);
}
 
Example #11
Source File: ECDSAAlgorithmTest.java    From java-jwt with MIT License 6 votes vote down vote up
@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 jwt = "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);
    algorithm.verify(JWT.decode(jwt));
}
 
Example #12
Source File: EcKeyTest.java    From wycheproof with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodedPrivateKey() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
  keyGen.initialize(EcUtil.getNistP256Params());
  KeyPair keyPair = keyGen.generateKeyPair();
  ECPrivateKey priv = (ECPrivateKey) keyPair.getPrivate();
  byte[] encoded = priv.getEncoded();
  System.out.println("Encoded ECPrivateKey:" + TestUtil.bytesToHex(encoded));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded);
  KeyFactory kf = KeyFactory.getInstance("EC");
  ECPrivateKey decoded = (ECPrivateKey) kf.generatePrivate(spec);
  assertEquals(priv.getS(), decoded.getS());
  assertEquals(priv.getParams().getCofactor(), decoded.getParams().getCofactor());
  assertEquals(priv.getParams().getCurve(), decoded.getParams().getCurve());
  assertEquals(priv.getParams().getGenerator(), decoded.getParams().getGenerator());
  assertEquals(priv.getParams().getOrder(), decoded.getParams().getOrder());
}
 
Example #13
Source File: MessageHandler.java    From RISE-V2G with MIT License 5 votes vote down vote up
private synchronized MessageHeaderType getHeader(
		byte[] sessionID,
		NotificationType notification,
		JAXBElement<? extends BodyBaseType> v2gMessageInstance,
		HashMap<String, byte[]> xmlSignatureRefElements,
		ECPrivateKey signaturePrivateKey) {
	MessageHeaderType header =  new MessageHeaderType();
	header.setSessionID(sessionID);
	header.setNotification(notification);
	
	if (xmlSignatureRefElements != null && xmlSignatureRefElements.size() != 0) {
		SignedInfoType signedInfo = SecurityUtils.getSignedInfo(xmlSignatureRefElements);
		
		byte[] signature = SecurityUtils.signSignedInfoElement(
								getExiCodec().getExiEncodedSignedInfo(getJaxbElement(signedInfo)), 
								signaturePrivateKey
						   );
		
		SignatureValueType signatureValue = new SignatureValueType();
		signatureValue.setValue(signature);
		
		SignatureType xmlSignature = new SignatureType();
		xmlSignature.setSignatureValue(signatureValue);
		xmlSignature.setSignedInfo(signedInfo);
		
		header.setSignature(xmlSignature);
	}
	
	return header;
}
 
Example #14
Source File: ECDSABouncyCastleProviderTests.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldDoECDSA512SigningWithBothKeys() throws Exception {
    Algorithm algorithm = Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC"));
    String jwt = asJWT(algorithm, ES512Header, auth0IssPayload);

    assertSignaturePresent(jwt);
    algorithm.verify(JWT.decode(jwt));
}
 
Example #15
Source File: ECDSABouncyCastleProviderTests.java    From java-jwt with MIT License 5 votes vote down vote up
@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 header384 = "eyJhbGciOiJFUzM4NCJ9";
    String body = "eyJpc3MiOiJhdXRoMCJ9";

    for (int i = 0; i < 10; i++) {
        String jwt = asJWT(algorithm384, header384, body);
        algorithm384.verify(JWT.decode(jwt));
    }
}
 
Example #16
Source File: AndroidKeyStore.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Return the type of a given PrivateKey object. This is an integer
 * that maps to one of the values defined by org.chromium.net.PrivateKeyType,
 * which is itself auto-generated from net/android/private_key_type_list.h
 * @param privateKey The PrivateKey handle
 * @return key type, or PrivateKeyType.INVALID if unknown.
 */
@CalledByNative
public static int getPrivateKeyType(PrivateKey privateKey) {
    if (privateKey instanceof RSAPrivateKey)
        return PrivateKeyType.RSA;
    if (privateKey instanceof DSAPrivateKey)
        return PrivateKeyType.DSA;
    if (privateKey instanceof ECPrivateKey)
        return PrivateKeyType.ECDSA;
    else
        return PrivateKeyType.INVALID;
}
 
Example #17
Source File: JwsUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static JwsSignatureProvider getPrivateKeySignatureProvider(PrivateKey key, SignatureAlgorithm algo) {
    if (algo == null) {
        LOG.warning("No signature algorithm was defined");
        throw new JwsException(JwsException.Error.ALGORITHM_NOT_SET);
    }
    if (key instanceof ECPrivateKey) {
        return new EcDsaJwsSignatureProvider((ECPrivateKey)key, algo);
    } else if (key instanceof RSAPrivateKey) {
        return new PrivateKeyJwsSignatureProvider(key, algo);
    }

    return null;
}
 
Example #18
Source File: EciesTest.java    From wycheproof with Apache License 2.0 5 votes vote down vote up
/**
 * BouncyCastle has a key generation algorithm "ECIES". This test checks that the result are
 * ECKeys in both cases.
 */
@Test
public void testKeyGeneration() throws Exception {
  ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
  KeyPairGenerator kf = KeyPairGenerator.getInstance("ECIES");
  kf.initialize(ecSpec);
  KeyPair keyPair = kf.generateKeyPair();
  ECPrivateKey unusedPriv = (ECPrivateKey) keyPair.getPrivate();
  ECPublicKey unusedPub = (ECPublicKey) keyPair.getPublic();
}
 
Example #19
Source File: ECDSATest.java    From java_security with MIT License 5 votes vote down vote up
/**
 * 
 * @author timliu
 * 说明: 用java的jdk里面相关方法实现ECDSA的签名及签名验证,要jdk7.x以上,ECDSA:椭圆曲线数字签名算法
 */
public static void jdkECDSA()
{
	try {
		// 1.初始化密钥
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
		keyPairGenerator.initialize(256);
		KeyPair keyPair = keyPairGenerator.generateKeyPair();
		ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic();
		ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate();
		
		// 2.进行签名
		PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());
		KeyFactory keyFactory = KeyFactory.getInstance("EC");
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
		Signature signature = Signature.getInstance("SHA1withECDSA");
		signature.initSign(privateKey);
		signature.update(src.getBytes());
		byte[] result = signature.sign();
		System.out.println("jdk ecdsa sign:" + Hex.encodeHexString(result) );
		
		// 3.验证签名
		X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
		keyFactory = KeyFactory.getInstance("EC");
		PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
		signature = Signature.getInstance("SHA1withECDSA");
		signature.initVerify(publicKey);
		signature.update(src.getBytes());
		boolean bool = signature.verify(result);
		System.out.println("jdk ecdsa verify:" + bool);
	} catch (Exception e) {
		System.out.println(e.toString());
	}
	
}
 
Example #20
Source File: CryptoUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static ECPrivateKey getECPrivateKey(String curve, byte[] privateKey) {
    try {
        ECParameterSpec params = getECParameterSpec(curve, true);
        ECPrivateKeySpec keySpec = new ECPrivateKeySpec(
                                       toBigInteger(privateKey), params);
        KeyFactory kf = KeyFactory.getInstance("EC");
        return (ECPrivateKey) kf.generatePrivate(keySpec);

    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example #21
Source File: NativeKeyAgreementSpi.java    From ECTester with MIT License 5 votes vote down vote up
@Override
protected void engineInit(Key key, SecureRandom random) throws InvalidKeyException {
    if (!(key instanceof ECPrivateKey)) {
        throw new InvalidKeyException
                ("Key must be instance of ECPrivateKey");
    }
    privateKey = (ECPrivateKey) key;
    this.params = privateKey.getParams();
}
 
Example #22
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static KeyDecryptionProvider getPrivateKeyDecryptionProvider(PrivateKey key, KeyAlgorithm algo) {
    if (key instanceof RSAPrivateKey) {
        return new RSAKeyDecryptionAlgorithm((RSAPrivateKey)key, algo);
    } else if (key instanceof ECPrivateKey) {
        if (AlgorithmUtils.isEcdhEsWrap(algo.getJwaName())) {
            return new EcdhAesWrapKeyDecryptionAlgorithm((ECPrivateKey)key, algo);
        } else {
            return new EcdhDirectKeyDecryptionAlgorithm((ECPrivateKey)key);
        }
    }

    return null;
}
 
Example #23
Source File: ECDSABouncyCastleProviderTests.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldDoECDSA256SigningWithBothKeys() throws Exception {
    Algorithm algorithm = Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC"));
    String jwt = asJWT(algorithm, ES256Header, auth0IssPayload);

    assertSignaturePresent(jwt);
    algorithm.verify(JWT.decode(jwt));
}
 
Example #24
Source File: MessageHandler.java    From RISE-V2G with MIT License 5 votes vote down vote up
public synchronized V2GMessage getV2GMessage(
		byte[] sessionID, 
		HashMap<String, byte[]> xmlSignatureRefElements,
		ECPrivateKey signaturePrivateKey,
		JAXBElement<? extends BodyBaseType> v2gMessageInstance) {
	return getV2GMessage(sessionID, null, xmlSignatureRefElements, signaturePrivateKey, v2gMessageInstance);
}
 
Example #25
Source File: ECDSAAlgorithmTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldBeEqualSignatureMethodDecodeResults() throws Exception {
    // signatures are not deterministic in value, so instead of directly comparing the signatures,
    // check that both sign(..) methods can be used to create a jwt which can be
    // verified
    Algorithm algorithm = Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC"));

    String header = "eyJhbGciOiJFUzI1NiJ9";
    String payload = "eyJpc3MiOiJhdXRoMCJ9";

    byte[] headerBytes = header.getBytes(StandardCharsets.UTF_8);
    byte[] payloadBytes = payload.getBytes(StandardCharsets.UTF_8);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    bout.write(headerBytes);
    bout.write('.');
    bout.write(payloadBytes);

    String jwtSignature1 = Base64.encodeBase64URLSafeString(algorithm.sign(bout.toByteArray()));
    String jwt1 = String.format("%s.%s.%s", header, payload, jwtSignature1);

    algorithm.verify(JWT.decode(jwt1));

    String jwtSignature2 = Base64.encodeBase64URLSafeString(algorithm.sign(headerBytes, payloadBytes));
    String jwt2 = String.format("%s.%s.%s", header, payload, jwtSignature2);

    algorithm.verify(JWT.decode(jwt2));
}
 
Example #26
Source File: BCECPrivateKey.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public BCECPrivateKey(
    ECPrivateKey key,
    ProviderConfiguration configuration)
{
    this.d = key.getS();
    this.algorithm = key.getAlgorithm();
    this.ecSpec = key.getParams();
    this.configuration = configuration;
}
 
Example #27
Source File: NativeSignatureSpi.java    From ECTester with MIT License 5 votes vote down vote up
@Override
protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
    if (!(privateKey instanceof ECPrivateKey)) {
        throw new InvalidKeyException
                ("Key must be an instance of ECPrivateKey");
    }
    signKey = (ECPrivateKey) privateKey;
    params = signKey.getParams();
    buffer.reset();
}
 
Example #28
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 5 votes vote down vote up
public static ECPrivateKey parseEcKey(byte[] blob) throws GeneralSecurityException,
        IOException, InvalidCipherTextException {
    ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(
            blob));
    org.bouncycastle.asn1.sec.ECPrivateKey pk = org.bouncycastle.asn1.sec.ECPrivateKey
            .getInstance(ain.readObject());
    ain.close();

    return toJcaPrivateKey(pk);
}
 
Example #29
Source File: JWSServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidSignature_EC() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JOSEException {
    //Generate EC key
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
    ECGenParameterSpec gps = new ECGenParameterSpec (Curve.P_521.getStdName());
    kpg.initialize(gps);
    KeyPair ecKey = kpg.generateKeyPair();

    ECPublicKey ecPublicKey  = (ECPublicKey)ecKey.getPublic();
    ECKey key = new ECKey();
    key.setKty("EC");
    key.setKid(KID);
    key.setCrv(Curve.P_521.getName());
    key.setX(Base64.getUrlEncoder().encodeToString(ecPublicKey.getW().getAffineX().toByteArray()));
    key.setY(Base64.getUrlEncoder().encodeToString(ecPublicKey.getW().getAffineY().toByteArray()));

    //Sign JWT with Elliptic Curve algorithm
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.ES512).keyID(KID).build(),
            new JWTClaimsSet.Builder()
                    .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
                    .build()
    );
    signedJWT.sign(new ECDSASigner((ECPrivateKey) ecKey.getPrivate()));

    assertTrue("Should be ok",jwsService.isValidSignature(signedJWT, key));
}
 
Example #30
Source File: ECDSABouncyCastleProviderTests.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowECDSA512VerificationWithDERSignatureWithBothKeys() 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 jwt = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9.MIGIAkIB4Ik8MixIeHBFIZkJjquymLzN6Q7DQr2pgw2uJ0/UW726GsDVCsb4RTFeUTTrK+aHZHtHPRoTuTEHCuerwvxo4EICQgGALKocz3lL8qfH1444LNBLaOSNJp3RNkB5YHDEhQEsox21PMA9kau2TcxkOW9jGX6b9N9FhlGo0/mmWFhVCR1YNg==";
    Algorithm algorithm = Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC"));
    algorithm.verify(JWT.decode(jwt));
}