Example usage for java.security Security getProvider

List of usage examples for java.security Security getProvider

Introduction

In this page you can find the example usage for java.security Security getProvider.

Prototype

public static Provider getProvider(String name) 

Source Link

Document

Returns the provider installed with the specified name, if any.

Usage

From source file:org.cesecore.keys.token.BaseCryptoToken.java

private void setProvider(Provider prov) {
    if (prov != null) {
        String pName = prov.getName();
        if (pName.startsWith("LunaJCA")) {
            // Luna Java provider does not contain support for RSA/ECB/PKCS1Padding but this is
            // the same as the alias below on small amounts of data
            prov.put("Alg.Alias.Cipher.RSA/NONE/NoPadding", "RSA//NoPadding");
            prov.put("Alg.Alias.Cipher.1.2.840.113549.1.1.1", "RSA//NoPadding");
            prov.put("Alg.Alias.Cipher.RSA/ECB/PKCS1Padding", "RSA//PKCS1v1_5");
            prov.put("Alg.Alias.Cipher.1.2.840.113549.3.7", "DES3/CBC/PKCS5Padding");
        }//from w  ww.ja  va 2 s.c  o  m
        if (Security.getProvider(pName) == null) {
            Security.addProvider(prov);
        }
        if (Security.getProvider(pName) == null) {
            throw new ProviderException("Not possible to install provider: " + pName);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("No provider passed to setProvider()");
        }
    }
}

From source file:org.cesecore.keys.token.p11.Pkcs11SlotLabel.java

/**
 * Get the IAIK provider.// www.ja va  2 s.c  om
 * @param slot Slot list index or slot ID.
 * @param libFile P11 module so file.
 * @param isIndex true if first parameter is a slot list index, false if slot ID.
 * @return the provider
 */
private static Provider getIAIKP11Provider(final long slot, final File libFile,
        final Pkcs11SlotLabelType type) {
    // Properties for the IAIK PKCS#11 provider
    final Properties prop = new Properties();
    try {
        prop.setProperty("PKCS11_NATIVE_MODULE", libFile.getCanonicalPath());
    } catch (IOException e) {
        throw new RuntimeException("Could for unknown reason not construct canonical filename.", e);
    }
    // If using Slot Index it is denoted by brackets in iaik
    prop.setProperty("SLOT_ID",
            type.equals(Pkcs11SlotLabelType.SLOT_INDEX) ? ("[" + slot + "]") : Long.toString(slot));
    if (log.isDebugEnabled()) {
        log.debug(prop.toString());
    }
    Provider ret = null;
    try {
        @SuppressWarnings("unchecked")
        final Class<? extends Provider> implClass = (Class<? extends Provider>) Class
                .forName(IAIK_PKCS11_CLASS);
        log.info("Using IAIK PKCS11 provider: " + IAIK_PKCS11_CLASS);
        // iaik PKCS11 has Properties as constructor argument
        ret = implClass.getConstructor(Properties.class).newInstance(new Object[] { prop });
        // It's not enough just to add the p11 provider. Depending on algorithms we may have to install the IAIK JCE provider as well in order
        // to support algorithm delegation
        @SuppressWarnings("unchecked")
        final Class<? extends Provider> jceImplClass = (Class<? extends Provider>) Class
                .forName(IAIK_JCEPROVIDER_CLASS);
        Provider iaikProvider = jceImplClass.getConstructor().newInstance();
        if (Security.getProvider(iaikProvider.getName()) == null) {
            log.info("Adding IAIK JCE provider for Delegation: " + IAIK_JCEPROVIDER_CLASS);
            Security.addProvider(iaikProvider);
        }
    } catch (InvocationTargetException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (InstantiationException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (IllegalAccessException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (IllegalArgumentException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (NoSuchMethodException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (SecurityException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    } catch (ClassNotFoundException e) {
        // NOPMD: Ignore, reflection related errors are handled elsewhere
    }
    return ret;
}

From source file:org.cesecore.keys.util.KeyStoreTools.java

private void generateEC(final String name, final String keyEntryName)
        throws InvalidAlgorithmParameterException {
    if (log.isTraceEnabled()) {
        log.trace(">generate EC: curve name " + name + ", keyEntryName " + keyEntryName);
    }/*w  w w. j a  va  2s .com*/
    // Generate the EC Keypair
    KeyPairGenerator kpg;
    try {
        kpg = KeyPairGenerator.getInstance("EC", this.providerName);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Algorithm " + "EC" + "was not recognized.", e);
    } catch (NoSuchProviderException e) {
        throw new IllegalStateException("BouncyCastle was not found as a provider.", e);
    }
    try {
        Provider prov = Security.getProvider(this.providerName);
        if (StringUtils.contains(prov.getClass().getName(), "iaik")) {
            throw new InvalidAlgorithmParameterException("IAIK ECC key generation not implemented.");
            /*
            ECDSAPrivateKey privateKeyTemplate = new ECDSAPrivateKey();
            privateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
            privateKeyTemplate.getToken().setBooleanValue(Boolean.FALSE);
                    
            ECDSAPublicKey publicKeyTemplate = new ECDSAPublicKey();
            publicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE);
            publicKeyTemplate.getToken().setBooleanValue(Boolean.FALSE);
                    
            ObjectID eccCurveObjectID = new ObjectID(objectID);
            publicKeyTemplate.getEcdsaParams().setByteArrayValue(DerCoder.encode(eccCurveObjectID));
                    
            PKCS11KeyPairGenerationSpec keyPairGenerationSpec =
               new PKCS11KeyPairGenerationSpec(tokenManager, publicKeyTemplate, privateKeyTemplate, 
               PKCS11Spec.USE_READ_WRITE_SESSION, PKCS11Spec.USE_USER_SESSION);
                    
            keyPairGenerator.initialize(keyPairGenerationSpec);
            */
        } else {
            ECGenParameterSpec ecSpec = new ECGenParameterSpec(name);
            if (StringUtils.equals(name, "implicitlyCA")) {
                log.debug("Generating implicitlyCA encoded ECDSA key pair");
                // If the keySpec is null, we have "implicitlyCA" defined EC parameters
                // The parameters were already installed when we installed the provider
                // We just make sure that ecSpec == null here
                ecSpec = null;
            }
            kpg.initialize(ecSpec);
        }
    } catch (InvalidAlgorithmParameterException e) {
        log.debug("EC name " + name + " not supported.");
        throw e;
    }
    generateKeyPair(kpg, keyEntryName, "SHA1withECDSA");
    if (log.isTraceEnabled()) {
        log.trace("<generate: curve name " + name + ", keyEntryName " + keyEntryName);
    }
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Testing a key pair to verify that it is possible to first sign and then verify with it.
 * /*from   w w w  .j a  va2s. c  om*/
 * @param priv
 *            private key to sign a string with
 * @param pub
 *            public key to verify the signature with
 * @param provider
 *            A provider used for signing with the private key, or null if "BC" should be used.
 * 
 * @throws InvalidKeyException
 *             if the public key can not be used to verify a string signed by the private key, because the key is wrong or the signature operation
 *             fails for other reasons such as a NoSuchAlgorithmException or SignatureException.
 * @throws NoSuchProviderException
 *             if the provider is not installed.
 */
public static void testKey(final PrivateKey priv, final PublicKey pub, final String provider)
        throws InvalidKeyException { // NOPMD:this is not a junit test
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final byte signBV[];
    final String testSigAlg;
    {
        final Iterator<String> i = AlgorithmTools.getSignatureAlgorithms(pub).iterator();
        final String tmp = i.hasNext() ? i.next() : null;
        testSigAlg = tmp != null ? tmp : "SHA1WithRSA";
    }
    if (log.isDebugEnabled()) {
        log.debug("Testing keys with algorithm: " + pub.getAlgorithm());
        log.debug("testSigAlg: " + testSigAlg);
        log.debug("provider: " + provider);
        log.trace("privateKey: " + priv);
        log.trace("privateKey class: " + priv.getClass().getName());
        log.trace("publicKey: " + pub);
        log.trace("publicKey class: " + pub.getClass().getName());
    }
    try {
        {
            final Provider prov = Security.getProvider(provider != null ? provider : "BC");
            final Signature signature = Signature.getInstance(testSigAlg, prov);
            signature.initSign(priv);
            signature.update(input);
            signBV = signature.sign();
            if (signBV == null) {
                throw new InvalidKeyException("Result from signing is null.");
            }
            if (log.isDebugEnabled()) {
                log.trace("Created signature of size: " + signBV.length);
                log.trace("Created signature: " + new String(Hex.encode(signBV)));
            }
        }
        {
            Signature signature;
            try {
                signature = Signature.getInstance(testSigAlg, "BC");
            } catch (NoSuchProviderException e) {
                throw new IllegalStateException("BouncyCastle was not found as a provider.", e);
            }
            signature.initVerify(pub);
            signature.update(input);
            if (!signature.verify(signBV)) {
                throw new InvalidKeyException("Not possible to sign and then verify with key pair.");
            }
        }
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    } catch (SignatureException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    }
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private SSLSocketFactory generateSSLContextWhichAcceptAllSSLCertificats() {
    Security.addProvider(Security.getProvider("SunJCE"));
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override//w w w. jav  a2s  . c o  m
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

        }
    } };

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        sslContext.init(null, trustAllCerts, new SecureRandom());

        return sslContext.getSocketFactory();
    } catch (KeyManagementException e) {
        logger.error("A KeyManagementException occurred", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("A NoSuchAlgorithmException occurred", e);
    }
    return null;
}

From source file:org.ejbca.core.model.ca.catoken.BaseCAToken.java

private void setProvider(Provider prov) {
    if (prov != null) {
        String pName = prov.getName();
        if (pName.startsWith("LunaJCA")) {
            // Luna Java provider does not contain support for RSA/ECB/PKCS1Padding but this is 
            // the same as the alias below on small amounts of data  
            prov.put("Alg.Alias.Cipher.RSA/NONE/NoPadding", "RSA//NoPadding");
            prov.put("Alg.Alias.Cipher.1.2.840.113549.1.1.1", "RSA//NoPadding");
            prov.put("Alg.Alias.Cipher.RSA/ECB/PKCS1Padding", "RSA//PKCS1v1_5");
            prov.put("Alg.Alias.Cipher.1.2.840.113549.3.7", "DES3/CBC/PKCS5Padding");
        }/*from   w w  w. jav a 2s  .c  om*/
        if (Security.getProvider(pName) == null) {
            Security.addProvider(prov);
        }
        if (Security.getProvider(pName) == null) {
            throw new ProviderException("Not possible to install provider: " + pName);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("No provider passed to setProvider()");
        }
    }
}

From source file:org.ejbca.ui.web.admin.configuration.StartServicesServlet.java

@SuppressWarnings("deprecation")
private void ejbcaInit() {

    ////from   w ww.j  a v  a  2  s .co  m
    // Run all "safe" initializations first, 
    // i.e. those that does not depend on other running beans, components etc

    // Log a startup message
    String iMsg = intres.getLocalizedMessage("startservice.startup", GlobalConfiguration.EJBCA_VERSION);
    log.info(iMsg);

    // Reinstall BC-provider to help re-deploys to work
    log.trace(">init re-installing BC-provider");
    CryptoProviderTools.removeBCProvider();
    CryptoProviderTools.installBCProvider();

    // Run java seed collector, that can take a little time the first time it is run
    log.trace(">init initializing random seed");
    SecureRandom rand = new SecureRandom();
    rand.nextInt();

    //
    // Start services that requires calling other beans or components
    //

    // We really need BC to be installed. This is an attempt to fix a bug where the ServiceSessionBean
    // crashes from not finding the BC-provider.
    int waitTime = 0;
    while (Security.getProvider("BC") == null && waitTime++ < 5) {
        log.info("Waiting for BC provider to be installed..");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            log("Waiting for BC provider failed.", e);
            break;
        }
    }

    // We have to read CAs into cache (and upgrade them) early, because the log system may use CAs for signing logs

    log.trace(">init CryptoTokenFactory just to load those classes that are available");
    CryptoTokenFactory.instance();

    // Load CAs at startup to improve impression of speed the first time a CA is accessed, it takes a little time to load it.
    log.trace(">init loading CAs into cache");
    try {
        caAdminSession.initializeAndUpgradeCAs();
    } catch (Exception e) {
        log.error("Error creating CAAdminSession: ", e);
    }

    AuthenticationToken admin = new AlwaysAllowLocalAuthenticationToken(
            new UsernamePrincipal("StartServicesServlet.init"));

    // Make a log row that EJBCA is starting
    Map<String, Object> details = new LinkedHashMap<String, Object>();
    details.put("msg", iMsg);
    logSession.log(EjbcaEventTypes.EJBCA_STARTING, EventStatus.SUCCESS, EjbcaModuleTypes.SERVICE,
            EjbcaServiceTypes.EJBCA, admin.toString(), null, getHostName(), null, details);

    // Log the type of security audit configuration that we have enabled.
    log.trace(">init security audit device configuration");
    final Set<String> loggerIds = AuditDevicesConfig.getAllDeviceIds();
    if (loggerIds.isEmpty()) {
        final String msg = intres.getLocalizedMessage("startservices.noauditdevices");
        log.info(msg);
    } else {
        if (!checkForProtectedAudit(admin, loggerIds)) {
            // Make a log row that no integrity protected device is configured
            final String msg = intres.getLocalizedMessage("startservices.noprotectedauditdevices");
            final Map<String, Object> logdetails = new LinkedHashMap<String, Object>();
            logdetails.put("msg", msg);
            logSession.log(EventTypes.LOG_MANAGEMENT_CHANGE, EventStatus.VOID, ModuleTypes.SECURITY_AUDIT,
                    ServiceTypes.CORE, admin.toString(), null, null, null, logdetails);
        }
    }

    // Initialize authorization system, if not done already
    log.trace(">init ComplexAccessControlSession to check for initial root role");
    complexAccessControlSession.initializeAuthorizationModule();

    log.trace(">init calling ServiceSession.load");
    try {
        serviceSession.load();
    } catch (Exception e) {
        log.error("Error init ServiceSession: ", e);
    }

    // Load Certificate profiles at startup to upgrade them if needed
    log.trace(">init loading CertificateProfile to check for upgrades");
    try {
        certificateProfileSession.initializeAndUpgradeProfiles();
    } catch (Exception e) {
        log.error("Error initializing certificate profiles: ", e);
    }

    // Load EndEntity profiles at startup to upgrade them if needed
    // And add this node to list of nodes
    log.trace(">init loading EndEntityProfile to check for upgrades");
    try {
        endEntityProfileSession.initializeAndUpgradeProfiles();
    } catch (Exception e) {
        log.error("Error initializing end entity profiles: ", e);
    }

    // Add this node's hostname to list of nodes
    log.trace(">init checking if this node is in the list of nodes");
    try {
        // Requires a transaction in order to create the initial global configuration
        tx.begin();
        try {
            final GlobalConfiguration config = (GlobalConfiguration) globalConfigurationSession
                    .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
            final Set<String> nodes = config.getNodesInCluster();
            final String hostname = getHostName();
            if (hostname != null && !nodes.contains(hostname)) {
                log.debug("Adding this node (" + hostname + ") to the list of nodes");
                nodes.add(hostname);
                config.setNodesInCluster(nodes);
                globalConfigurationSession.saveConfiguration(admin, config);
            }
        } finally {
            tx.commit();
        }
    } catch (Exception e) {
        log.error("Error adding host to node list in global configuration: ", e);
    }

    log.trace(">init SignSession to check for unique issuerDN,serialNumber index");
    // Call the check for unique index, since first invocation will perform the database
    // operation and avoid a performance hit for the first request where this is checked.
    certCreateSession.isUniqueCertificateSerialNumberIndex();

    /*
     * FIXME: This is a hack, because we need some sort of annotation or service loader to make sure 
     * that the AccessMatchValue-implementing enums get initialized at runtime. Sadly, enums aren't 
     * initialized until they're called, which causes trouble with this registry. 
     * 
     * These lines are to be removed once a dynamic initialization heuristic has been developed.
     * 
     */
    try {
        Class.forName(X500PrincipalAccessMatchValue.class.getName());
        Class.forName(CliUserAccessMatchValue.class.getName());
    } catch (ClassNotFoundException e) {
        log.error("Failure during match value initialization", e);
    }
    // Check if there the default responder has been set. If not, try setting it using the old value.
    GlobalOcspConfiguration globalConfiguration = (GlobalOcspConfiguration) globalConfigurationSession
            .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID);
    if (StringUtils.isEmpty(globalConfiguration.getOcspDefaultResponderReference())) {
        globalConfiguration.setOcspDefaultResponderReference(OcspConfiguration.getDefaultResponderId());
        try {
            globalConfigurationSession.saveConfiguration(admin, globalConfiguration);
            globalConfigurationSession.flushConfigurationCache(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID);
        } catch (AuthorizationDeniedException e) {
            throw new IllegalStateException(
                    "An always allow token was not allowed access. Likely cause is that the database hasn't been configured.");
        }
    }
    // Upgrade the old Validation Authority Publisher in Community Edition (leave it be in Enterprise for the sake of 100% uptime)
    if (!enterpriseEditionEjbBridgeSession.isRunningEnterprise()) {
        publisherSession.adhocUpgradeTo6_3_1_1();
    }

    // Check and upgrade if this is the first time we start an instance that was previously an stand-alone VA
    ocspResponseGeneratorSession.adhocUpgradeFromPre60(null);
    // Start key reload timer
    ocspResponseGeneratorSession.initTimers();
    // Start CA certificate cache reload
    certificateStoreSession.initTimers();
    // Verify that the EJB CLI user (if present) cannot be used to generate certificates
    final String cliUsername = EjbcaConfiguration.getCliDefaultUser();
    try {
        final EndEntityInformation defaultCliUser = endEntityAccessSession.findUser(admin, cliUsername);
        if (defaultCliUser != null && defaultCliUser.getStatus() == EndEntityConstants.STATUS_NEW) {
            try {
                endEntityManagementSession.setUserStatus(admin, cliUsername,
                        EndEntityConstants.STATUS_GENERATED);
            } catch (ApprovalException e) {
                log.warn("The EJBCA CLI user '" + cliUsername
                        + "' could be used for certificate enrollment. Please correct the status manually. Failed with: "
                        + e.getMessage());
            } catch (FinderException e) {
                log.warn("The EJBCA CLI user '" + cliUsername
                        + "' could be used for certificate enrollment. Please correct the status manually. Failed with: "
                        + e.getMessage());
            } catch (WaitingForApprovalException e) {
                log.warn("The EJBCA CLI user '" + cliUsername
                        + "' could be used for certificate enrollment. Please correct the status manually. Failed with: "
                        + e.getMessage());
            }
        }
    } catch (AuthorizationDeniedException e) {
        log.warn("Unable to check if the EJBCA CLI user '" + cliUsername
                + "' could be used for certificate enrollment. Please check and correct the status manually. Failed with: "
                + e.getMessage());
    }
}

From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java

/** 
 * @see org.ejbca.util.keystore.KeyStoreContainer#generate(java.lang.String, java.lang.String)
 *//*from w w  w . java 2 s  .  co  m*/
private byte[] generateEC(final String name, final String keyEntryName) throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">generate EC: curve name " + name + ", keyEntryName " + keyEntryName);
    }
    // Generate the EC Keypair
    final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", this.providerName);
    try {
        Provider prov = Security.getProvider(this.providerName);
        if (StringUtils.contains(prov.getClass().getName(), "iaik")) {
            throw new InvalidAlgorithmParameterException("IAIK ECC key generation not implemented.");
            /*
            ECDSAPrivateKey privateKeyTemplate = new ECDSAPrivateKey();
            privateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
            privateKeyTemplate.getToken().setBooleanValue(Boolean.FALSE);
                    
            ECDSAPublicKey publicKeyTemplate = new ECDSAPublicKey();
            publicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE);
            publicKeyTemplate.getToken().setBooleanValue(Boolean.FALSE);
                    
            ObjectID eccCurveObjectID = new ObjectID(objectID);
            publicKeyTemplate.getEcdsaParams().setByteArrayValue(DerCoder.encode(eccCurveObjectID));
                    
            PKCS11KeyPairGenerationSpec keyPairGenerationSpec =
               new PKCS11KeyPairGenerationSpec(tokenManager, publicKeyTemplate, privateKeyTemplate, 
               PKCS11Spec.USE_READ_WRITE_SESSION, PKCS11Spec.USE_USER_SESSION);
                    
            keyPairGenerator.initialize(keyPairGenerationSpec);
            */
        } else {
            kpg.initialize(new ECGenParameterSpec(name));
        }
    } catch (InvalidAlgorithmParameterException e) {
        log.debug("EC name " + name + " not supported.");
        throw e;
    }
    final byte result[] = generate(kpg, keyEntryName, "SHA1withECDSA");
    if (log.isTraceEnabled()) {
        log.trace("<generate: curve name " + name + ", keyEntryName " + keyEntryName);
    }
    return result;
}

From source file:org.ejbca.util.keystore.KeyTools.java

/**
 * /*from w ww . ja  v a  2 s.  c  om*/
 * @param is for the SUN PKCS#11 provider
 * @param prop for the IAIK PKCS#11 provider
 * @return Java security Provider for a PCKS#11 token
 * @throws IOException if neither the IAIK or the SUN provider can be created
 */
private static Provider getP11Provider(final InputStream is, final Properties prop) throws IOException {

    // We will construct the PKCS11 provider (sun.security..., or iaik...) using reflection, because 
    // the sun class does not exist on all platforms in jdk5, and we want to be able to compile everything.
    // The below code replaces the single line (for the SUN provider):
    //   return new SunPKCS11(new ByteArrayInputStream(baos.toByteArray()));

    // We will first try to construct the more competent IAIK provider, if it exists in the classpath
    // if that does not exist, we will revert back to use the SUN provider
    Provider ret = null;
    if (prop != null) {
        try {
            final Class implClass = Class.forName(IAIKPKCS11CLASS);
            log.info("Using IAIK PKCS11 provider: " + IAIKPKCS11CLASS);
            // iaik PKCS11 has Properties as constructor argument
            ret = (Provider) implClass.getConstructor(Properties.class).newInstance(new Object[] { prop });
            // It's not enough just to add the p11 provider. Depending on algorithms we may have to install the IAIK JCE provider as well in order to support algorithm delegation
            final Class jceImplClass = Class.forName(KeyTools.IAIKJCEPROVIDERCLASS);
            Provider iaikProvider = (Provider) jceImplClass.getConstructor().newInstance();
            if (Security.getProvider(iaikProvider.getName()) == null) {
                log.info("Adding IAIK JCE provider for Delegation: " + KeyTools.IAIKJCEPROVIDERCLASS);
                Security.addProvider(iaikProvider);
            }
        } catch (Exception e) {
            // do nothing here. Sun provider is tested below.
        }
    }
    if (ret == null) {
        try {
            // Sun PKCS11 has InputStream as constructor argument
            final Class implClass = Class.forName(SUNPKCS11CLASS);
            log.info("Using SUN PKCS11 provider: " + SUNPKCS11CLASS);
            ret = (Provider) implClass.getConstructor(InputStream.class).newInstance(new Object[] { is });
        } catch (Exception e) {
            log.error("Error constructing pkcs11 provider: " + e.getMessage());
            final IOException ioe = new IOException("Error constructing pkcs11 provider: " + e.getMessage());
            ioe.initCause(e);
            throw ioe;
        }
    }
    return ret;
}

From source file:org.ejbca.util.keystore.KeyTools.java

/** Testing a key pair to verify that it is possible to first sign and then verify with it.
 * /*  w  w  w.ja  v a  2 s.c  o m*/
 * @param priv private key to sign a string with
 * @param pub public key to verify the signature with
 * @param provider A provider used for signing with the private key, or null if "BC" should be used.
 * 
 * @throws InvalidKeyException if the public key can not be used to verify a string signed by the private key, because the key is wrong or the signature operation fails for other reasons such as a NoSuchAlgorithmException or SignatureException.
 * @throws NoSuchProviderException if the provider is not installed.
 */
public static void testKey(final PrivateKey priv, final PublicKey pub, final String provider)
        throws InvalidKeyException, NoSuchProviderException {
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final byte signBV[];
    final String testSigAlg;
    {
        final Iterator<String> i = AlgorithmTools.getSignatureAlgorithms(pub).iterator();
        final String tmp = i.hasNext() ? i.next() : null;
        testSigAlg = tmp != null ? tmp : "SHA1WithRSA";
    }
    if (log.isDebugEnabled()) {
        log.debug("Testing keys with algorithm: " + pub.getAlgorithm());
        log.debug("testSigAlg: " + testSigAlg);
        log.debug("provider: " + provider);
        log.trace("privateKey: " + priv);
        log.trace("privateKey class: " + priv.getClass().getName());
        log.trace("publicKey: " + pub);
        log.trace("publicKey class: " + pub.getClass().getName());
    }
    try {
        {
            final Provider prov = Security.getProvider(provider != null ? provider : "BC");
            final Signature signature = Signature.getInstance(testSigAlg, prov);
            signature.initSign(priv);
            signature.update(input);
            signBV = signature.sign();
            if (signBV == null) {
                throw new InvalidKeyException("Result from signing is null.");
            }
            if (log.isDebugEnabled()) {
                log.trace("Created signature of size: " + signBV.length);
                log.trace("Created signature: " + new String(Hex.encode(signBV)));
            }
        }
        {
            final Signature signature = Signature.getInstance(testSigAlg, "BC");
            signature.initVerify(pub);
            signature.update(input);
            if (!signature.verify(signBV)) {
                throw new InvalidKeyException("Not possible to sign and then verify with key pair.");
            }
        }
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    } catch (SignatureException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    }
}