Java 类java.security.interfaces.ECPrivateKey 实例源码

项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@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);
}
项目:RISE-V2G    文件:SecurityUtils.java   
/**
 * Reads the private key from an encrypted PKCS#8 file and returns it as an ECPrivateKey instance.
 * 
 * @param A PKCS#8 (.key) file containing the private key with value "s"
 * @return The private key as an ECPrivateKey instance
 */
public static ECPrivateKey getPrivateKey(String keyFilePath) {
    Path fileLocation = Paths.get(keyFilePath);
    byte[] pkcs8ByteArray;

    try {
        pkcs8ByteArray = Files.readAllBytes(fileLocation);

        // The DER encoded private key is password-based encrypted and provided in PKCS#8. So we need to decrypt it first
        PBEKeySpec pbeKeySpec = new PBEKeySpec(GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString().toCharArray());
        EncryptedPrivateKeyInfo encryptedPrivKeyInfo = new EncryptedPrivateKeyInfo(pkcs8ByteArray);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedPrivKeyInfo.getAlgName());
        Key secret = secretKeyFactory.generateSecret(pbeKeySpec);
        PKCS8EncodedKeySpec pkcs8PrivKeySpec = encryptedPrivKeyInfo.getKeySpec(secret);

        ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(pkcs8PrivKeySpec);

        return privateKey;
    } catch (IOException | InvalidKeySpecException | NoSuchAlgorithmException | InvalidKeyException e) {
        getLogger().error(e.getClass().getSimpleName() + " occurred while trying to access private key at " +
                  "location '" + keyFilePath + "'");
        return null;
    } 
}
项目:RISE-V2G    文件:SecurityUtils.java   
/**
    * Encrypts the private key of the contract certificate which is to be sent to the EVCC. First, the
    * shared secret based on the ECDH parameters is calculated, then the symmetric session key with which
    * the private key of the contract certificate is to be encrypted.
    * 
    * @param certificateECPublicKey The public key of either the OEM provisioning certificate (in case of 
    *                                CertificateInstallation) or the to be updated contract certificate
    *                                (in case of CertificateUpdate)
    * @param ecKeyPair The EC keypair
    * @param contractCertPrivateKey The private key of the contract certificate
    * @return The encrypted private key of the to be installed contract certificate
    */
public static ContractSignatureEncryptedPrivateKeyType encryptContractCertPrivateKey(
        ECPublicKey certificateECPublicKey, 
        KeyPair ecKeyPair,
        ECPrivateKey contractCertPrivateKey) {
    // Generate the shared secret by using the public key of either OEMProvCert or ContractCert
    byte[] sharedSecret = generateSharedSecret((ECPrivateKey) ecKeyPair.getPrivate(), certificateECPublicKey);

    if (sharedSecret == null) {
        getLogger().error("Shared secret could not be generated");
        return null;
    }

    // The session key is generated using the computed shared secret
    SecretKey sessionKey = generateSessionKey(sharedSecret);

    // Finally, the private key of the contract certificate is encrypted using the session key
    ContractSignatureEncryptedPrivateKeyType encryptedContractCertPrivateKey = 
            getContractSignatureEncryptedPrivateKey(sessionKey, contractCertPrivateKey);

    return encryptedContractCertPrivateKey;
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@Test
public void shouldSignAndVerifyWithECDSA512() throws Exception {
    ECDSAAlgorithm algorithm512 = (ECDSAAlgorithm) Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC"));
    String content512 = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9";

    for (int i = 0; i < 10; i++) {
        byte[] signature = algorithm512.sign(content512.getBytes());
        String signature512 = Base64.encodeBase64URLSafeString((signature));

        String token  = content512 + "." + signature512;
        JWT jwt = JWT.require(algorithm512).withIssuer("auth0").build();
        DecodedJWT decoded = jwt.decode(token);
        algorithm512.verify(decoded, EncodeType.Base64);
    }
}
项目:wolfcrypt-jni    文件:EccTest.java   
@Test
public void getEccCurveNameFromSpec()
    throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {

    /* generate key pair */
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
    ECGenParameterSpec genSpec = new ECGenParameterSpec("secp256r1");
    kpg.initialize(genSpec);

    KeyPair pair = kpg.genKeyPair();
    ECPrivateKey priv = (ECPrivateKey)pair.getPrivate();

    ECParameterSpec spec = priv.getParams();

    String curveName = Ecc.getCurveName(spec);

    assertEquals(curveName, "SECP256R1");
}
项目:javaOIDCMsg    文件:JWTCreatorTest.java   
@Test
public void shouldNotOverwriteKeyIdIfAddedFromECDSAAlgorithms() throws Exception {
    ECPrivateKey privateKey = (ECPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_EC_256, "EC");
    ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class);
    when(provider.getPrivateKeyId()).thenReturn("my-key-id");
    when(provider.getPrivateKey()).thenReturn(privateKey);

    String signed = JWTCreator.init()
            .withKeyId("real-key-id")
            .sign(Algorithm.ECDSA256(provider));

    assertThat(signed, is(notNullValue()));
    String[] parts = signed.split("\\.");
    String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8);
    assertThat(headerJson, JsonMatcher.hasEntry("kid", "my-key-id"));
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@Test
public void shouldThrowOnVerifyWhenTheSignatureIsNotPrepared() 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(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 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);
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@Test
public void shouldDoECDSA256SigningWithProvidedPrivateKey() throws Exception {
    ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class);
    PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC");
    PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC");
    when(provider.getPrivateKey()).thenReturn((ECPrivateKey) privateKey);
    when(provider.getPublicKeyById(null)).thenReturn((ECPublicKey) publicKey);
    Algorithm algorithm = Algorithm.ECDSA256(provider);
    String jwtContent = String.format("%s.%s", ES256Header, 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);
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@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 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);
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@Test
public void shouldThrowOnSignWhenSignatureAlgorithmDoesNotExists() 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(NoSuchAlgorithmException.class));

    CryptoHelper crypto = mock(CryptoHelper.class);
    when(crypto.createSignatureFor(anyString(), any(PrivateKey.class), any(byte[].class)))
            .thenThrow(NoSuchAlgorithmException.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));
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@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));
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@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);
    }
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@Test
public void shouldDecodeECDSA512JOSE() throws Exception {
    ECDSAAlgorithm algorithm512 = (ECDSAAlgorithm) Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC"));

    //Without padding
    byte[] joseSignature = createJOSESignature(66, false, false);
    byte[] derSignature = algorithm512.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 66, false, false);

    //With R padding
    joseSignature = createJOSESignature(66, true, false);
    derSignature = algorithm512.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 66, true, false);

    //With S padding
    joseSignature = createJOSESignature(66, false, true);
    derSignature = algorithm512.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 66, false, true);

    //With both paddings
    joseSignature = createJOSESignature(66, true, true);
    derSignature = algorithm512.JOSEToDER(joseSignature);
    assertValidDERSignature(derSignature, 66, true, true);
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@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);
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@Test
public void shouldThrowOnVerifyWhenTheSignatureIsNotPrepared() 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(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 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);
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@Test
public void shouldDoECDSA256SigningWithProvidedPrivateKey() throws Exception {
    ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class);
    PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC");
    PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC");
    when(provider.getPrivateKey()).thenReturn((ECPrivateKey) privateKey);
    when(provider.getPublicKeyById(null)).thenReturn((ECPublicKey) publicKey);
    Algorithm algorithm = Algorithm.ECDSA256(provider);
    String jwtContent = String.format("%s.%s", ES256Header, 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);
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@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));
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@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));
}
项目:mDL-ILP    文件:ECCUtils.java   
/**
 * Extract the raw bytes of the private ECC key in standard smart card format.
 * @param privateKey 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[] decodeECCPrivateKeyPKCS8(PrivateKey privateKey, EllipticCurveParameters curveReference)
{
    byte[] privateKeyBytes = {};

    if (privateKey instanceof ECPrivateKey)
    {
        final byte[] s = getStandardSizeInteger(((ECPrivateKey)privateKey).getS().toByteArray(), curveReference);
        privateKeyBytes = s;
    }

    return privateKeyBytes;
}
项目:mDL-ILP    文件:ECCUtils.java   
/**
 * Extract the raw bytes of the private ECC key in standard smart card format.
 * @param privateKey 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[] decodeECCPrivateKeyPKCS8(PrivateKey privateKey, EllipticCurveParameters curveReference)
{
    byte[] privateKeyBytes = {};

    if (privateKey instanceof ECPrivateKey)
    {
        final byte[] s = getStandardSizeInteger(((ECPrivateKey)privateKey).getS().toByteArray(), curveReference);
        privateKeyBytes = s;
    }

    return privateKeyBytes;
}
项目:shibboleth-idp-oidc-extension    文件:SignRegistrationResponse.java   
/**
 * Returns correct implementation of signer based on algorithm type.
 * 
 * @param jwsAlgorithm
 *            JWS algorithm
 * @return signer for algorithm and private key
 * @throws JOSEException
 *             if algorithm cannot be supported
 */
private JWSSigner getSigner(Algorithm jwsAlgorithm) throws JOSEException {
    if (JWSAlgorithm.Family.EC.contains(jwsAlgorithm)) {
        return new ECDSASigner((ECPrivateKey) credential.getPrivateKey());
    }
    if (JWSAlgorithm.Family.RSA.contains(jwsAlgorithm)) {
        return new RSASSASigner(credential.getPrivateKey());
    }
    if (JWSAlgorithm.Family.HMAC_SHA.contains(jwsAlgorithm)) {
        return new MACSigner(credential.getSecretKey());
    }
    throw new JOSEException("Unsupported algorithm " + jwsAlgorithm.getName());
}
项目:shibboleth-idp-oidc-extension    文件:AbstractSignJWTAction.java   
/**
 * Returns correct implementation of signer based on algorithm type.
 * 
 * @param jwsAlgorithm
 *            JWS algorithm
 * @return signer for algorithm and private key
 * @throws JOSEException
 *             if algorithm cannot be supported
 */
private JWSSigner getSigner(Algorithm jwsAlgorithm) throws JOSEException {
    if (JWSAlgorithm.Family.EC.contains(jwsAlgorithm)) {
        return new ECDSASigner((ECPrivateKey) credential.getPrivateKey());
    }
    if (JWSAlgorithm.Family.RSA.contains(jwsAlgorithm)) {
        return new RSASSASigner(credential.getPrivateKey());
    }
    if (JWSAlgorithm.Family.HMAC_SHA.contains(jwsAlgorithm)) {
        return new MACSigner(credential.getSecretKey());
    }
    throw new JOSEException("Unsupported algorithm " + jwsAlgorithm.getName());
}
项目:ipack    文件:JCEECPrivateKey.java   
public JCEECPrivateKey(
    ECPrivateKey    key)
{
    this.d = key.getS();
    this.algorithm = key.getAlgorithm();
    this.ecSpec = key.getParams();
}
项目:ipack    文件:BCDSTU4145PrivateKey.java   
public BCDSTU4145PrivateKey(
    ECPrivateKey key)
{
    this.d = key.getS();
    this.algorithm = key.getAlgorithm();
    this.ecSpec = key.getParams();
}
项目:ipack    文件:KeyFactorySpi.java   
protected Key engineTranslateKey(
    Key    key)
    throws InvalidKeyException
{
    if (key instanceof ECPublicKey)
    {
        return new BCECPublicKey((ECPublicKey)key, configuration);
    }
    else if (key instanceof ECPrivateKey)
    {
        return new BCECPrivateKey((ECPrivateKey)key, configuration);
    }

    throw new InvalidKeyException("key type unknown");
}
项目:ipack    文件:BCECGOST3410PrivateKey.java   
public BCECGOST3410PrivateKey(
    ECPrivateKey key)
{
    this.d = key.getS();
    this.algorithm = key.getAlgorithm();
    this.ecSpec = key.getParams();
}
项目:JungleTree    文件:JwtTokenFactory.java   
public String generateClientSaltToken(PublicKey serverPublicKey, PrivateKey serverPrivateKey, byte[] clientSalt) {
    JWSObject token = new JWSObject(createServerTokenHeader((ECPublicKey) serverPublicKey), new Payload(createClientSaltJson(clientSalt)));
    try {
        token.sign(new ECDSASigner((ECPrivateKey) serverPrivateKey));
    } catch (JOSEException ex) {
        log.error("Failed to sign server token!", ex);
        throw new RuntimeException(ex);
    }
    return token.serialize();
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@Test
public void shouldThrowOnDERSignatureConversionIfRNumberDoesNotHaveExpectedLength() throws Exception {
    ECDSAAlgorithm algorithm256 = (ECDSAAlgorithm) Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC"));
    byte[] derSignature = createDERSignature(32, false, false);
    derSignature[3] = (byte) 34;
    exception.expect(SignatureException.class);
    exception.expectMessage("Invalid DER signature format.");

    algorithm256.DERToJOSE(derSignature);
}
项目:RISE-V2G    文件:MessageHandler.java   
public synchronized V2GMessage getV2GMessage(
        byte[] sessionID, 
        HashMap<String, byte[]> xmlSignatureRefElements,
        ECPrivateKey signaturePrivateKey,
        JAXBElement<? extends BodyBaseType> v2gMessageInstance) {
    return getV2GMessage(sessionID, null, xmlSignatureRefElements, signaturePrivateKey, v2gMessageInstance);
}