Example usage for java.security KeyStore getKey

List of usage examples for java.security KeyStore getKey

Introduction

In this page you can find the example usage for java.security KeyStore getKey.

Prototype

public final Key getKey(String alias, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Returns the key associated with the given alias, using the given password to recover it.

Usage

From source file:org.dasein.cloud.google.Google.java

public Compute getGoogleCompute() throws CloudException, InternalException {
    ProviderContext ctx = getContext();//from w w w  .ja  v  a 2s  . c om

    Cache<Compute> cache = Cache.getInstance(this, "ComputeAccess", Compute.class, CacheLevel.CLOUD_ACCOUNT,
            new TimePeriod<Hour>(1, TimePeriod.HOUR));
    Collection<Compute> googleCompute = (Collection<Compute>) cache.get(ctx);
    Compute gce = null;

    if (googleCompute == null) {
        googleCompute = new ArrayList<Compute>();
        HttpTransport transport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        try {
            String serviceAccountId = "";
            byte[] p12Bytes = null;
            String p12Password = "";

            List<ContextRequirements.Field> fields = getContextRequirements().getConfigurableValues();
            for (ContextRequirements.Field f : fields) {
                if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                    byte[][] keyPair = (byte[][]) getContext().getConfigurationValue(f);
                    p12Bytes = keyPair[0];
                    p12Password = new String(keyPair[1], "utf-8");
                } else if (f.type.equals(ContextRequirements.FieldType.TEXT)) {
                    serviceAccountId = (String) getContext().getConfigurationValue(f);
                }
            }

            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            InputStream p12AsStream = new ByteArrayInputStream(p12Bytes);
            keyStore.load(p12AsStream, p12Password.toCharArray());

            GoogleCredential creds = new GoogleCredential.Builder().setTransport(transport)
                    .setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountId)
                    .setServiceAccountScopes(ComputeScopes.all())
                    .setServiceAccountPrivateKey(
                            (PrivateKey) keyStore.getKey("privateKey", p12Password.toCharArray()))//This is always the password for p12 files
                    .build();
            creds.setExpirationTimeMilliseconds(3600000L);

            gce = new Compute.Builder(transport, jsonFactory, creds).setApplicationName(ctx.getAccountNumber())
                    .setHttpRequestInitializer(creds).build();
            googleCompute.add(gce);
            cache.put(ctx, googleCompute);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new CloudException(CloudErrorType.AUTHENTICATION, 400, "Bad Credentials",
                    "An authentication error has occurred: Bad Credentials");
        }
    } else {
        gce = googleCompute.iterator().next();
    }
    return gce;
}

From source file:org.dasein.cloud.google.Google.java

public Storage getGoogleStorage() throws CloudException, InternalException {
    ProviderContext ctx = getContext();/*from  w w  w  .j  a v  a2s  .  c o m*/

    Cache<Storage> cache = Cache.getInstance(this, "DriveAccess", Storage.class, CacheLevel.CLOUD,
            new TimePeriod<Hour>(1, TimePeriod.HOUR));
    Collection<Storage> googleDrive = (Collection<Storage>) cache.get(ctx);
    Storage drive = null;

    if (googleDrive == null) {
        googleDrive = new ArrayList<Storage>();

        HttpTransport transport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        try {
            String serviceAccountId = "";
            byte[] p12Bytes = null;
            String p12Password = "";

            List<ContextRequirements.Field> fields = getContextRequirements().getConfigurableValues();
            for (ContextRequirements.Field f : fields) {
                if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                    byte[][] keyPair = (byte[][]) getContext().getConfigurationValue(f);
                    p12Bytes = keyPair[0];
                    p12Password = new String(keyPair[1], "utf-8");
                } else if (f.type.equals(ContextRequirements.FieldType.TEXT)) {
                    serviceAccountId = (String) getContext().getConfigurationValue(f);
                }
            }

            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            InputStream p12AsStream = new ByteArrayInputStream(p12Bytes);
            keyStore.load(p12AsStream, p12Password.toCharArray());

            GoogleCredential creds = new GoogleCredential.Builder().setTransport(transport)
                    .setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountId)
                    .setServiceAccountScopes(ComputeScopes.all())
                    .setServiceAccountPrivateKey(
                            (PrivateKey) keyStore.getKey("privateKey", p12Password.toCharArray()))//This is always the password for p12 files
                    .build();
            creds.setExpirationTimeMilliseconds(3600000L);

            drive = new Storage.Builder(transport, jsonFactory, creds)
                    .setApplicationName(ctx.getAccountNumber()).setHttpRequestInitializer(creds).build();
            googleDrive.add(drive);
            cache.put(ctx, googleDrive);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new CloudException(CloudErrorType.AUTHENTICATION, 400, "Bad Credentials",
                    "An authentication error has occurred: Bad Credentials");
        }
    } else {
        drive = googleDrive.iterator().next();
    }
    return drive;
}

From source file:org.kuali.kra.s2s.service.impl.GrantsGovConnectorServiceImpl.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig/*from   www  .j  a  va 2  s.  c o m*/
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2SException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2SException {
    KeyStore keyStore = S2SCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(JKS_TYPE);
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = S2SCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (CertificateException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#applyCertificateRequest(String, File, File, String)
 *//*from w  w w. j ava  2  s .c om*/
public synchronized boolean applyCertificateRequest(final String commonName, final File certificateFile,
        final File keystoreFile, final String storePassword) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", commonName);
        DEBUGGER.debug("Value: {}", certificateFile);
        DEBUGGER.debug("Value: {}", keystoreFile);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final File certificateDirectory = FileUtils
            .getFile(certConfig.getCertificateDirectory() + "/" + commonName);
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + commonName);

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("certificateDirectory: {}", certificateDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("certificateFile: {}", certificateFile);
        DEBUGGER.debug("keystoreFile: {}", keystoreFile);
    }

    boolean isComplete = false;
    FileInputStream certStream = null;
    FileOutputStream storeStream = null;
    FileInputStream keystoreInput = null;
    FileInputStream rootCertStream = null;
    FileInputStream intermediateCertStream = null;

    try {
        if (!(rootDirectory.exists())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(rootDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(certConfig.getRootCertificateFile().exists())) {
            throw new CertificateManagementException("Root certificate file does not exist. Cannot continue.");
        }

        if (!(certConfig.getIntermediateCertificateFile().exists())) {
            throw new CertificateManagementException(
                    "Intermediate certificate file does not exist. Cannot continue.");
        }

        if (!(storeDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Keystore directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(keystoreFile.canWrite())) {
            throw new CertificateManagementException(
                    "Unable to write to applicable keystore. Cannot continue.");
        }

        keystoreInput = FileUtils.openInputStream(keystoreFile);
        certStream = FileUtils.openInputStream(certificateFile);

        if (DEBUG) {
            DEBUGGER.debug("keystoreInput: {}", keystoreInput);
            DEBUGGER.debug("certStream: {}", certStream);
        }

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keystoreInput, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        Key privateKey = keyStore.getKey(commonName, storePassword.toCharArray());
        CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

        if (DEBUG) {
            DEBUGGER.debug("CertificateFactory: {}", certFactory);
        }

        rootCertStream = FileUtils.openInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()));
        intermediateCertStream = FileUtils
                .openInputStream(FileUtils.getFile(certConfig.getIntermediateCertificateFile()));

        if (DEBUG) {
            DEBUGGER.debug("rootCertStream: {}", rootCertStream);
            DEBUGGER.debug("intermediateCertStream: {}", intermediateCertStream);
        }

        X509Certificate[] responseCert = new X509Certificate[] {
                (X509Certificate) certFactory.generateCertificate(rootCertStream),
                (X509Certificate) certFactory.generateCertificate(intermediateCertStream),
                (X509Certificate) certFactory.generateCertificate(certStream) };

        if (DEBUG) {
            DEBUGGER.debug("X509Certificate[]", (Object) responseCert);
        }

        storeStream = FileUtils.openOutputStream(keystoreFile);
        keyStore.setKeyEntry(commonName, privateKey, storePassword.toCharArray(), responseCert);
        keyStore.store(storeStream, storePassword.toCharArray());

        isComplete = true;
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } catch (UnrecoverableKeyException ukx) {
        throw new CertificateManagementException(ukx.getMessage(), ukx);
    } finally {
        if (storeStream != null) {
            IOUtils.closeQuietly(storeStream);
        }

        if (intermediateCertStream != null) {
            IOUtils.closeQuietly(intermediateCertStream);
        }

        if (rootCertStream != null) {
            IOUtils.closeQuietly(rootCertStream);
        }

        if (certStream != null) {
            IOUtils.closeQuietly(certStream);
        }

        if (keystoreInput != null) {
            IOUtils.closeQuietly(keystoreInput);
        }
    }

    return isComplete;
}

From source file:org.tolven.gatekeeper.CertificateHelper.java

public PrivateKey getPrivateKey(KeyStore keyStore, char[] password) {
    String alias = null;//  w ww .  j a v a2 s.  c o m
    try {
        Enumeration<String> aliases = keyStore.aliases();
        if (!aliases.hasMoreElements()) {
            throw new RuntimeException("KeyStore contains no aliases");
        }
        alias = aliases.nextElement();
    } catch (KeyStoreException ex) {
        throw new RuntimeException("Could obtain alias: " + alias + " in the userPKCS12 keystore", ex);
    }
    try {
        return (PrivateKey) keyStore.getKey(alias, password);
    } catch (Exception ex) {
        throw new RuntimeException("Could not get PrivateKey from KeyStore using alias: " + alias, ex);
    }
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

/**
 *       ?./*  ww  w  .j a  v  a  2  s.  c o  m*/
 * <p/>
 * <p/>
 *    ? ?   RSA.    ?  ?
 * ?,    ?    ?.  ???   ?. ? ??
 * ?  ?  ?  ?:
 * <ol>
 * <li>  ? ?  .</li>
 * <li>   ???  ?   ? ?.</li>
 * <li> ? ?  ?.</li>
 * <li> ?     ???.</li>
 * <li>  ? ? .</li>
 * <li>   ,  ?       ?.</li>
 * </ol>
 * <p/>
 * .. ?? ?,   ,  ?   ???,  ??, ?.  ?
 * ?  ? ? ? ?   ?.  ?  ?,  
 *   ,    ,    .
 * <p/>
 * ? ? ? ?  ? ??  ? ?,  ?? ? ???, 
 *  ?   ?.
 *
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 */
static void loadCertificate() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException {
    if (!started) {
        synchronized (CryptoProvider.class) {
            if (!started) {
                final long startMs = System.currentTimeMillis();
                final KeyStore keystore = KeyStore.getInstance("HDImageStore");
                keystore.load(null, null);

                final Properties properties = new Properties();
                properties.setProperty("name", DEFAULT_CERT_NAME);
                properties.setProperty("pass", DEFAULT_CERT_PASS);

                final File userHome = new File(System.getProperty("user.home"));
                final File keyFile = new File(userHome, "gses-key.properties");
                if (!keyFile.exists()) {
                    log.warn(keyFile
                            + "  , ???  ? ??");
                } else {
                    final FileInputStream is = new FileInputStream(keyFile);
                    properties.load(is);
                    is.close();
                }
                final String certName_ = properties.getProperty("name");
                final String certPass_ = properties.getProperty("pass");

                privateKey = ((PrivateKey) keystore.getKey(certName_, certPass_.toCharArray()));
                cert = ((X509Certificate) keystore.getCertificate(certName_));

                try {
                    cert.checkValidity();
                    log.info(" ?  " + cert.getNotAfter()
                            + " ? " + cert.getSubjectDN().getName());
                } catch (CertificateExpiredException e) {
                    log.error(
                            "? ? ?? ? ? "
                                    + cert.getSubjectDN().getName());
                    cert = null;
                    privateKey = null;
                } catch (CertificateNotYetValidException e) {
                    log.error("? ? ? ?? ? ? "
                            + cert.getSubjectDN().getName());
                    cert = null;
                    privateKey = null;
                }
                if ((privateKey != null) && (cert != null)) {
                    started = true;
                }
                if (log.isDebugEnabled()) {
                    log.debug("LOAD CERTIFICATE: " + (System.currentTimeMillis() - startMs) + "ms");
                }
            }
        }
    }
}

From source file:org.jenkinsci.plugins.androidsigning.SignApksBuilder.java

@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
        @Nonnull TaskListener listener) throws InterruptedException, IOException {
    if (isIntermediateFailure(run)) {
        listener.getLogger()//from   w  w w  .  j a  v  a  2 s  .  c o m
                .println("[SignApksBuilder] skipping Sign APKs step because a previous step failed");
        return;
    }

    if (getEntries() != null && !getEntries().isEmpty()) {
        List<SignApksBuilder> newModelBuilders = singleEntryBuildersFromEntriesOfBuilder(this);
        for (SignApksBuilder builder : newModelBuilders) {
            builder.perform(run, workspace, launcher, listener);
        }
        return;
    }

    EnvVars env;
    if (run instanceof AbstractBuild) {
        env = run.getEnvironment(listener);
        env.overrideAll(((AbstractBuild<?, ?>) run).getBuildVariables());
    } else {
        env = new EnvVars();
    }

    FilePath builderDir = workspace.child(BUILDER_DIR);
    String excludeBuilderDir = builderDir.getName() + "/**";
    ZipalignTool zipalign = new ZipalignTool(env, workspace, listener.getLogger(), androidHome, zipalignPath);
    Map<String, String> apksToArchive = new LinkedHashMap<>();

    StandardCertificateCredentials keyStoreCredential = getKeystore(getKeyStoreId(), run.getParent());
    char[] storePassword = keyStoreCredential.getPassword().getPlainText().toCharArray();
    // TODO: add key password support
    char[] keyPassword = storePassword;
    KeyStore keyStore = keyStoreCredential.getKeyStore();
    String alias = getKeyAlias();
    PrivateKey key;
    Certificate[] certChain;
    try {
        if (getKeyAlias() == null) {
            // TODO: search all entries to find key, throw error if multiple keys
        }
        key = (PrivateKey) keyStore.getKey(alias, keyPassword);
        certChain = keyStore.getCertificateChain(alias);
    } catch (GeneralSecurityException e) {
        PrintWriter details = listener.fatalError("Error reading keystore " + getKeyStoreId());
        e.printStackTrace(details);
        throw new AbortException("Error reading keystore " + getKeyStoreId());
    }

    if (key == null || certChain == null) {
        throw new AbortException("Alias " + alias
                + " does not exist or does not point to a key and certificate in certificate credentials "
                + getKeyStoreId());
    }

    String v1SigName = alias;
    if (v1SigName == null) {
        v1SigName = keyStoreCredential.getId();
    }

    Set<FilePath> matchedApks = new TreeSet<>(Comparator.comparing(FilePath::getRemote));
    String[] globs = getSelectionGlobs();
    for (String glob : globs) {
        FilePath[] globMatch = workspace.list(glob, excludeBuilderDir);
        if (globMatch.length == 0) {
            throw new AbortException("No APKs in workspace matching " + glob);
        }
        matchedApks.addAll(Arrays.asList(globMatch));
    }

    for (FilePath unsignedApk : matchedApks) {
        unsignedApk = unsignedApk.absolutize();
        FilePath archiveDir = builderDir.child(unsignedApk.getName());
        if (archiveDir.isDirectory()) {
            archiveDir.deleteContents();
        } else {
            archiveDir.mkdirs();
        }
        String archiveDirRelName = relativeToWorkspace(workspace, archiveDir);
        String unsignedPathName = unsignedApk.getRemote();
        Pattern stripUnsignedPattern = Pattern.compile("(-?unsigned)?.apk$", Pattern.CASE_INSENSITIVE);
        Matcher stripUnsigned = stripUnsignedPattern.matcher(unsignedApk.getName());
        String strippedApkName = stripUnsigned.replaceFirst("");
        String alignedRelName = archiveDirRelName + "/" + strippedApkName + "-aligned.apk";
        String signedRelName = archiveDirRelName + "/" + strippedApkName + "-signed.apk";

        ArgumentListBuilder zipalignCommand = zipalign.commandFor(unsignedPathName, alignedRelName);
        listener.getLogger().printf("[SignApksBuilder] %s%n", zipalignCommand);
        int zipalignResult = launcher.launch().cmds(zipalignCommand).pwd(workspace).stdout(listener)
                .stderr(listener.getLogger()).join();

        if (zipalignResult != 0) {
            listener.fatalError("[SignApksBuilder] zipalign failed: exit code %d", zipalignResult);
            throw new AbortException(
                    String.format("zipalign failed on APK %s: exit code %d", unsignedPathName, zipalignResult));
        }

        FilePath alignedPath = workspace.child(alignedRelName);
        if (!alignedPath.exists()) {
            throw new AbortException(String.format("aligned APK does not exist: %s", alignedRelName));
        }

        listener.getLogger().printf("[SignApksBuilder] signing APK %s%n", alignedRelName);

        FilePath signedPath = workspace.child(signedRelName);
        final SignApkCallable signApk = new SignApkCallable(key, certChain, v1SigName, signedPath.getRemote(),
                listener);
        alignedPath.act(signApk);

        listener.getLogger().printf("[SignApksBuilder] signed APK %s%n", signedRelName);

        if (getArchiveUnsignedApks()) {
            listener.getLogger().printf("[SignApksBuilder] archiving unsigned APK %s%n", unsignedPathName);
            apksToArchive.put(archiveDirRelName + "/" + unsignedApk.getName(),
                    relativeToWorkspace(workspace, unsignedApk));
        }
        if (getArchiveSignedApks()) {
            listener.getLogger().printf("[SignApksBuilder] archiving signed APK %s%n", signedRelName);
            apksToArchive.put(signedRelName, signedRelName);
        }
    }

    listener.getLogger().println("[SignApksBuilder] finished signing APKs");

    if (apksToArchive.size() > 0) {
        run.pickArtifactManager().archive(workspace, launcher, BuildListenerAdapter.wrap(listener),
                apksToArchive);
    }
}

From source file:org.signserver.server.cryptotokens.KeystoreCryptoToken.java

@Override
public void importCertificateChain(final List<Certificate> certChain, final String alias, final char[] authCode,
        final Map<String, Object> params, final IServices services)
        throws CryptoTokenOfflineException, IllegalArgumentException {
    if (certChain.size() < 1) {
        throw new IllegalArgumentException("Certificate chain can not be empty");
    }//from w  w w  .j a  va2s  .  c o  m

    try {
        final KeyStore keyStore = getKeyStore();
        final Key key = keyStore.getKey(alias, authCode != null ? authCode : authenticationCode);

        CryptoTokenHelper.ensureNewPublicKeyMatchesOld(keyStore, alias, certChain.get(0));

        keyStore.setKeyEntry(alias, key, authCode != null ? authCode : authenticationCode,
                certChain.toArray(new Certificate[0]));

        // persist keystore
        OutputStream out = null;

        if (!TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) {
            out = new FileOutputStream(new File(keystorepath));
        } else {
            // use internal worker data
            out = new ByteArrayOutputStream();
        }
        keyStore.store(out, authenticationCode);

        if (TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) {
            final byte[] data = ((ByteArrayOutputStream) out).toByteArray();

            getWorkerSession().setKeystoreData(new AdminInfo("Internal", null, null), this.workerId, data);
        }

        // update in-memory representation
        KeyEntry entry = getKeyEntry(alias);
        final Certificate signingCert = certChain.get(0);

        if (entry == null) {
            entry = new KeyEntry();
        }

        entry.setCertificate(signingCert);
        entry.setCertificateChain(certChain);
    } catch (Exception e) {
        throw new CryptoTokenOfflineException(e);
    }
}

From source file:org.kuali.coeus.propdev.impl.s2s.connect.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig//from  w  w w .j ava2 s .com
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2sCommunicationException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2sCommunicationException {
    KeyStore keyStore = s2sCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType());
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(
                    alias, key, s2SConfigurationService
                            .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = s2sCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | CertificateException
            | IOException e) {
        LOG.error(e.getMessage(), e);
        throw new S2sCommunicationException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testSwingParentLocale() throws Exception {
    Security.addProvider(new BeIDProvider());

    final JFrame frame = new JFrame("Test Parent frame");
    frame.setSize(200, 200);//from w  ww  . j ava2s. c  o  m
    frame.setLocation(300, 300);
    frame.setVisible(true);

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    final BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    keyStoreParameter.setLogoff(true);
    keyStoreParameter.setParentComponent(frame);
    keyStoreParameter.setLocale(new Locale("nl"));
    keyStore.load(keyStoreParameter);

    final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    signature.sign();
}