Search in sources :

Example 81 with NoSuchProviderException

use of java.security.NoSuchProviderException in project oxAuth by GluuFederation.

the class SupportRequestFile method requestFileMethod.

@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "sectorIdentifierUri", "requestFileBasePath", "requestFileBaseUrl" })
// This tests requires a place to publish a request object via HTTPS
@Test
public void requestFileMethod(final String userId, final String userSecret, final String redirectUri, final String redirectUris, final String sectorIdentifierUri, final String requestFileBasePath, final String requestFileBaseUrl) throws Exception {
    showTitle("OC5:FeatureTest-Support Request File");
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN);
    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();
    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());
    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();
    // 2. Writing a request object in a file
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();
    String state = UUID.randomUUID().toString();
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(state);
    try {
        OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
        JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest, SignatureAlgorithm.HS256, clientSecret, cryptoProvider);
        jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull()));
        jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false)));
        jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
        jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull()));
        jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false)));
        jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createNull()));
        jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, ClaimValue.createValueList(new String[] { "2" })));
        jwtAuthorizationRequest.getIdTokenMember().setMaxAge(86400);
        String authJwt = jwtAuthorizationRequest.getEncodedJwt();
        String hash = Base64Util.base64urlencode(JwtUtil.getMessageDigestSHA256(authJwt));
        String fileName = UUID.randomUUID().toString() + ".txt";
        String filePath = requestFileBasePath + File.separator + fileName;
        String fileUrl = requestFileBaseUrl + "/" + fileName + "#" + hash;
        FileWriter fw = new FileWriter(filePath);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(authJwt);
        bw.close();
        fw.close();
        authorizationRequest.setRequestUri(fileUrl);
        System.out.println("Request JWT: " + authJwt);
        System.out.println("Request File Path: " + filePath);
        System.out.println("Request File URL: " + fileUrl);
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    // 3. Request authorization
    AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setRequest(authorizationRequest);
    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(authorizationEndpoint, authorizationRequest, userId, userSecret);
    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getAccessToken());
    assertNotNull(authorizationResponse.getState());
}
Also used : JwtAuthorizationRequest(org.xdi.oxauth.client.model.authorize.JwtAuthorizationRequest) FileWriter(java.io.FileWriter) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ResponseType(org.xdi.oxauth.model.common.ResponseType) BufferedWriter(java.io.BufferedWriter) OxAuthCryptoProvider(org.xdi.oxauth.model.crypto.OxAuthCryptoProvider) JwtAuthorizationRequest(org.xdi.oxauth.client.model.authorize.JwtAuthorizationRequest) NoSuchProviderException(java.security.NoSuchProviderException) Claim(org.xdi.oxauth.client.model.authorize.Claim) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(org.xdi.oxauth.BaseTest)

Example 82 with NoSuchProviderException

use of java.security.NoSuchProviderException in project jdk8u_jdk by JetBrains.

the class XMLSignatureFactory method getInstance.

/**
     * Returns an <code>XMLSignatureFactory</code> that supports the
     * requested XML processing mechanism and representation type (ex: "DOM"),
     * as supplied by the specified provider. The specified provider must be
     * registered in the security provider list.
     *
     * <p>Note that the list of registered providers may be retrieved via
     * the {@link Security#getProviders() Security.getProviders()} method.
     *
     * @param mechanismType the type of the XML processing mechanism and
     *    representation. See the <a
     *    href="../../../../../technotes/guides/security/xmldsig/overview.html#Service Provider">
     *    Service Providers</a> section of the API overview for a list of
     *    standard mechanism types.
     * @param provider the string name of the provider
     * @return a new <code>XMLSignatureFactory</code>
     * @throws NoSuchProviderException if the specified provider is not
     *    registered in the security provider list
     * @throws NullPointerException if <code>provider</code> or
     *    <code>mechanismType</code> is <code>null</code>
     * @throws NoSuchMechanismException if an <code>XMLSignatureFactory</code>
     *    implementation for the specified mechanism is not
     *    available from the specified provider
     * @see Provider
     */
public static XMLSignatureFactory getInstance(String mechanismType, String provider) throws NoSuchProviderException {
    if (mechanismType == null) {
        throw new NullPointerException("mechanismType cannot be null");
    } else if (provider == null) {
        throw new NullPointerException("provider cannot be null");
    } else if (provider.length() == 0) {
        throw new NoSuchProviderException();
    }
    Instance instance;
    try {
        instance = GetInstance.getInstance("XMLSignatureFactory", null, mechanismType, provider);
    } catch (NoSuchAlgorithmException nsae) {
        throw new NoSuchMechanismException(nsae);
    }
    XMLSignatureFactory factory = (XMLSignatureFactory) instance.impl;
    factory.mechanismType = mechanismType;
    factory.provider = instance.provider;
    return factory;
}
Also used : Instance(sun.security.jca.GetInstance.Instance) NoSuchMechanismException(javax.xml.crypto.NoSuchMechanismException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 83 with NoSuchProviderException

use of java.security.NoSuchProviderException in project jdk8u_jdk by JetBrains.

the class CICO method runTest.

public void runTest(String algo, String mo, String pad, int whichRead) throws Exception {
    Cipher ci1 = null;
    Cipher ci2 = null;
    byte[] iv = null;
    AlgorithmParameterSpec aps = null;
    SecretKey key = null;
    try {
        // Do initialization
        Random rdm = new Random();
        rdm.nextBytes(plainText);
        KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
        if (!kg.getAlgorithm().equals(algo)) {
            throw new RuntimeException("Unexpected algorithm <" + kg.getAlgorithm() + ">, expected value is <" + algo + ">");
        }
        kg.init(KEY_LENGTH);
        key = kg.generateKey();
        ci1 = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
        if (mo.equalsIgnoreCase("ECB")) {
            ci1.init(Cipher.ENCRYPT_MODE, key);
        } else {
            ci1.init(Cipher.ENCRYPT_MODE, key, aps);
        }
        if (!mo.equalsIgnoreCase("ECB")) {
            iv = ci1.getIV();
            aps = new IvParameterSpec(iv);
        } else {
            aps = null;
        }
        ci2 = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
        if (mo.equalsIgnoreCase("ECB")) {
            ci2.init(Cipher.DECRYPT_MODE, key);
        } else {
            ci2.init(Cipher.DECRYPT_MODE, key, aps);
        }
        ByteArrayInputStream baInput = new ByteArrayInputStream(plainText);
        ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
        try (CipherInputStream ciInput = new CipherInputStream(baInput, ci1);
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput, ci2)) {
            // mark and reset methods
            if (ciInput.markSupported()) {
                throw new RuntimeException("CipherInputStream unexpectedly supports the mark and reset methods");
            }
            // of buffering : byte[] and int
            switch(whichRead) {
                case 0:
                    int buffer0 = ciInput.read();
                    while (buffer0 != -1) {
                        ciOutput.write(buffer0);
                        buffer0 = ciInput.read();
                    }
                    break;
                case 1:
                    byte[] buffer1 = new byte[20];
                    int len1 = ciInput.read(buffer1);
                    while (len1 != -1) {
                        ciOutput.write(buffer1, 0, len1);
                        len1 = ciInput.read(buffer1);
                    }
                    break;
                case NREADS - 1:
                    byte[] buffer2 = new byte[ci1.getOutputSize(plainText.length)];
                    int offset2 = 0;
                    int len2 = 0;
                    while (len2 != -1) {
                        len2 = ciInput.read(buffer2, offset2, buffer2.length - offset2);
                        offset2 += len2;
                    }
                    ciOutput.write(buffer2, 0, buffer2.length);
                    break;
            }
        }
        // Get the output
        byte[] recoveredText = new byte[baOutput.size()];
        recoveredText = baOutput.toByteArray();
        if (!java.util.Arrays.equals(plainText, recoveredText)) {
            throw new RuntimeException("Original text is not equal with recovered text, with " + algo + "/" + mo + "/" + pad + "/" + whichRead);
        }
    // Compare input and output
    } catch (NoSuchAlgorithmException e) {
        //OFB20 is for negative testing
        if (!mo.equalsIgnoreCase("OFB20")) {
            System.out.println("Unexpected NoSuchAlgorithmException with " + algo + "/" + mo + "/" + pad + "/" + whichRead);
            throw new RuntimeException("Test failed!");
        }
    } catch (IOException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
        System.out.println("Unexpected Exception with " + algo + "/" + mo + "/" + pad + "/" + whichRead);
        System.out.println("Test failed!");
        throw e;
    }
}
Also used : CipherOutputStream(javax.crypto.CipherOutputStream) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CipherInputStream(javax.crypto.CipherInputStream) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) SecretKey(javax.crypto.SecretKey) Random(java.util.Random) ByteArrayInputStream(java.io.ByteArrayInputStream) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) NoSuchProviderException(java.security.NoSuchProviderException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) KeyGenerator(javax.crypto.KeyGenerator)

Example 84 with NoSuchProviderException

use of java.security.NoSuchProviderException in project jdk8u_jdk by JetBrains.

the class CTR method runTest.

public void runTest(String algo, String mo, String pad) throws Exception {
    Cipher ci = null;
    byte[] iv = null;
    AlgorithmParameterSpec aps = null;
    SecretKey key = null;
    try {
        Random rdm = new Random();
        byte[] plainText;
        ci = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
        KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
        kg.init(KEY_LENGTH);
        key = kg.generateKey();
        for (int i = 0; i < 15; i++) {
            plainText = new byte[1600 + i + 1];
            rdm.nextBytes(plainText);
            if (!mo.equalsIgnoreCase("GCM")) {
                ci.init(Cipher.ENCRYPT_MODE, key, aps);
            } else {
                ci.init(Cipher.ENCRYPT_MODE, key);
            }
            byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
            int offset = ci.update(plainText, 0, plainText.length, cipherText, 0);
            ci.doFinal(cipherText, offset);
            if (!mo.equalsIgnoreCase("ECB")) {
                iv = ci.getIV();
                aps = new IvParameterSpec(iv);
            } else {
                aps = null;
            }
            if (!mo.equalsIgnoreCase("GCM")) {
                ci.init(Cipher.DECRYPT_MODE, key, aps);
            } else {
                ci.init(Cipher.DECRYPT_MODE, key, ci.getParameters());
            }
            byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)];
            int len = ci.doFinal(cipherText, 0, cipherText.length, recoveredText);
            byte[] tmp = new byte[len];
            for (int j = 0; j < len; j++) {
                tmp[j] = recoveredText[j];
            }
            Arrays.toString(plainText);
            if (!java.util.Arrays.equals(plainText, tmp)) {
                System.out.println("Original: ");
                dumpBytes(plainText);
                System.out.println("Recovered: ");
                dumpBytes(tmp);
                throw new RuntimeException("Original text is not equal with recovered text, with mode:" + mo);
            }
        }
    } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | ShortBufferException | IllegalBlockSizeException | BadPaddingException e) {
        System.out.println("Test failed!");
        throw e;
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) SecretKey(javax.crypto.SecretKey) Random(java.util.Random) ShortBufferException(javax.crypto.ShortBufferException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) NoSuchProviderException(java.security.NoSuchProviderException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) KeyGenerator(javax.crypto.KeyGenerator)

Example 85 with NoSuchProviderException

use of java.security.NoSuchProviderException in project midpoint by Evolveum.

the class ProtectorImpl method decryptBytes.

@Override
protected <T> byte[] decryptBytes(ProtectedData<T> protectedData) throws SchemaException, EncryptionException {
    EncryptedDataType encryptedDataType = protectedData.getEncryptedDataType();
    EncryptionMethodType encryptionMethodType = encryptedDataType.getEncryptionMethod();
    if (encryptionMethodType == null) {
        throw new SchemaException("No encryptionMethod element in protected data");
    }
    String algorithmUri = encryptionMethodType.getAlgorithm();
    if (StringUtils.isBlank(algorithmUri)) {
        throw new SchemaException("No algorithm URI in encryptionMethod element in protected data");
    }
    KeyInfoType keyInfo = encryptedDataType.getKeyInfo();
    if (keyInfo == null) {
        throw new SchemaException("No keyInfo element in protected data");
    }
    String keyName = keyInfo.getKeyName();
    if (StringUtils.isBlank(keyName)) {
        throw new SchemaException("No keyName defined in keyInfo element in protected data");
    }
    SecretKey key = getSecretKeyByDigest(keyName);
    CipherDataType cipherData = encryptedDataType.getCipherData();
    if (cipherData == null) {
        throw new SchemaException("No cipherData element in protected data");
    }
    byte[] encryptedBytes = cipherData.getCipherValue();
    if (encryptedBytes == null || encryptedBytes.length == 0) {
        throw new SchemaException("No cipherValue in cipherData element in protected data");
    }
    byte[] decryptedData;
    try {
        decryptedData = decryptBytes(encryptedBytes, algorithmUri, key);
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | NoSuchProviderException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
        throw new EncryptionException(e.getMessage(), e);
    }
    return decryptedData;
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) EncryptedDataType(com.evolveum.prism.xml.ns._public.types_3.EncryptedDataType) EncryptionMethodType(com.evolveum.prism.xml.ns._public.types_3.EncryptionMethodType) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) KeyInfoType(com.evolveum.prism.xml.ns._public.types_3.KeyInfoType) SecretKey(javax.crypto.SecretKey) CipherDataType(com.evolveum.prism.xml.ns._public.types_3.CipherDataType) NoSuchProviderException(java.security.NoSuchProviderException)

Aggregations

NoSuchProviderException (java.security.NoSuchProviderException)93 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)67 InvalidKeyException (java.security.InvalidKeyException)30 IOException (java.io.IOException)28 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)18 CertificateException (java.security.cert.CertificateException)18 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)14 Cipher (javax.crypto.Cipher)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 BadPaddingException (javax.crypto.BadPaddingException)12 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)12 KeyStoreException (java.security.KeyStoreException)11 SignatureException (java.security.SignatureException)10 X509Certificate (java.security.cert.X509Certificate)10 SecretKey (javax.crypto.SecretKey)10 CertificateFactory (java.security.cert.CertificateFactory)9 CertificateEncodingException (java.security.cert.CertificateEncodingException)8 IvParameterSpec (javax.crypto.spec.IvParameterSpec)8 KeyStore (java.security.KeyStore)7 Provider (java.security.Provider)7