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.cesecore.keys.util.KeyTools.java

/**
 * Convert a KeyStore to PEM format.//from w ww. j a v  a 2s  .  c om
 */
public static byte[] getSinglePemFromKeyStore(final KeyStore ks, final char[] password)
        throws KeyStoreException, CertificateEncodingException, IOException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    // Find the key private key entry in the keystore
    final Enumeration<String> e = ks.aliases();
    Object o = null;
    String alias = "";
    PrivateKey serverPrivKey = null;
    while (e.hasMoreElements()) {
        o = e.nextElement();
        if (o instanceof String) {
            if ((ks.isKeyEntry((String) o))
                    && ((serverPrivKey = (PrivateKey) ks.getKey((String) o, password)) != null)) {
                alias = (String) o;
                break;
            }
        }
    }

    byte[] privKeyEncoded = "".getBytes();

    if (serverPrivKey != null) {
        privKeyEncoded = serverPrivKey.getEncoded();
    }

    final Certificate[] chain = KeyTools.getCertChain(ks, (String) o);
    final X509Certificate userX509Certificate = (X509Certificate) chain[0];

    final byte[] output = userX509Certificate.getEncoded();
    String sn = CertTools.getSubjectDN(userX509Certificate);

    String subjectdnpem = sn.replace(',', '/');
    String issuerdnpem = CertTools.getIssuerDN(userX509Certificate).replace(',', '/');

    buffer.write(BAG_ATTRIBUTES);
    buffer.write(FRIENDLY_NAME);
    buffer.write(alias.getBytes());
    buffer.write(NL);
    buffer.write(BEGIN_PRIVATE_KEY);
    buffer.write(NL);

    final byte[] privKey = Base64.encode(privKeyEncoded);
    buffer.write(privKey);
    buffer.write(NL);
    buffer.write(END_PRIVATE_KEY);
    buffer.write(NL);
    buffer.write(BAG_ATTRIBUTES);
    buffer.write(FRIENDLY_NAME);
    buffer.write(alias.getBytes());
    buffer.write(NL);
    buffer.write(SUBJECT_ATTRIBUTE);
    buffer.write(subjectdnpem.getBytes());
    buffer.write(NL);
    buffer.write(ISSUER_ATTRIBUTE);
    buffer.write(issuerdnpem.getBytes());
    buffer.write(NL);
    buffer.write(BEGIN_CERTIFICATE);
    buffer.write(NL);

    final byte[] userCertB64 = Base64.encode(output);
    buffer.write(userCertB64);
    buffer.write(NL);
    buffer.write(END_CERTIFICATE);
    buffer.write(NL);

    if (!CertTools.isSelfSigned(userX509Certificate)) {
        for (int num = 1; num < chain.length; num++) {
            final X509Certificate tmpX509Cert = (X509Certificate) chain[num];
            sn = CertTools.getSubjectDN(tmpX509Cert);

            String cn = CertTools.getPartFromDN(sn, "CN");
            if (StringUtils.isEmpty(cn)) {
                cn = "Unknown";
            }

            subjectdnpem = sn.replace(',', '/');
            issuerdnpem = CertTools.getIssuerDN(tmpX509Cert).replace(',', '/');

            buffer.write(BAG_ATTRIBUTES);
            buffer.write(FRIENDLY_NAME);
            buffer.write(cn.getBytes());
            buffer.write(NL);
            buffer.write(SUBJECT_ATTRIBUTE);
            buffer.write(subjectdnpem.getBytes());
            buffer.write(NL);
            buffer.write(ISSUER_ATTRIBUTE);
            buffer.write(issuerdnpem.getBytes());
            buffer.write(NL);

            final byte[] tmpOutput = tmpX509Cert.getEncoded();
            buffer.write(BEGIN_CERTIFICATE);
            buffer.write(NL);

            final byte[] tmpCACertB64 = Base64.encode(tmpOutput);
            buffer.write(tmpCACertB64);
            buffer.write(NL);
            buffer.write(END_CERTIFICATE);
            buffer.write(NL);
        }
    }
    return buffer.toByteArray();
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Get the Certificate Authority private key
 * /*from   ww w  .  j a  v a 2s  .  co  m*/
 * @return
 */
private PrivateKey getCaKey(KeyStore trustedKs) {
    PrivateKey caKey = null;
    String keyAlias = config.getProperty(RepositoryManagedSignatureProviderFactory.TRUSTED_KEY_ALIAS);
    String keyPassword = config.getProperty(RepositoryManagedSignatureProviderFactory.TRUSTED_KEY_PASSWORD);

    try {
        caKey = (PrivateKey) trustedKs.getKey(keyAlias, keyPassword.toCharArray());
    } catch (KeyStoreException kse) {
        throw new AlfrescoRuntimeException(kse.getMessage());
    } catch (UnrecoverableKeyException uke) {
        throw new AlfrescoRuntimeException(uke.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        throw new AlfrescoRuntimeException(nsae.getMessage());
    }

    return caKey;
}

From source file:org.guanxi.sp.engine.service.saml2.WebBrowserSSOAuthConsumerService.java

/**
 * This is the handler for the initial /s2/wbsso/acs page. This receives the
 * browser after it has visited the IdP.
 *
 * @param request ServletRequest/*  w w w.j a v  a2  s . c  om*/
 * @param response ServletResponse
 * @throws java.io.IOException if an error occurs
 * @throws org.guanxi.common.GuanxiException if an error occurs
 * @throws java.security.KeyStoreException if an error occurs
 * @throws java.security.NoSuchAlgorithmException if an error occurs
 * @throws java.security.cert.CertificateException if an error occurs
 */
public void acs(HttpServletRequest request, HttpServletResponse response)
        throws IOException, GuanxiException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
    String guardSession = request.getParameter("RelayState");
    String b64SAMLResponse = request.getParameter("SAMLResponse");

    if ((getServletContext().getAttribute(guardSession.replaceAll("GUARD", "ENGINE")) == null)) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("Metadata error<br /><br />");
        out.println("Not a valid session");
        out.flush();
        out.close();
        return;
    }

    // We previously changed the Guard session ID to an Engine one...
    EntityDescriptorType guardEntityDescriptor = (EntityDescriptorType) getServletContext()
            .getAttribute(guardSession.replaceAll("GUARD", "ENGINE"));
    // ...so now change it back as it will be passed to the Guard
    guardSession = guardSession.replaceAll("ENGINE", "GUARD");

    try {
        // Decode and unmarshall the response from the IdP
        ResponseDocument responseDocument = null;
        if (request.getMethod().equalsIgnoreCase("post")) {
            responseDocument = ResponseDocument.Factory
                    .parse(new StringReader(Utils.decodeBase64(b64SAMLResponse)));
        } else {
            byte[] decodedRequest = Utils.decodeBase64b(b64SAMLResponse);
            responseDocument = ResponseDocument.Factory
                    .parse(Utils.inflate(decodedRequest, Utils.RFC1951_NO_WRAP));
        }
        String idpProviderId = responseDocument.getResponse().getIssuer().getStringValue();

        HashMap<String, String> namespaces = new HashMap<String, String>();
        namespaces.put(SAML.NS_SAML_20_PROTOCOL, SAML.NS_PREFIX_SAML_20_PROTOCOL);
        namespaces.put(SAML.NS_SAML_20_ASSERTION, SAML.NS_PREFIX_SAML_20_ASSERTION);
        XmlOptions xmlOptions = new XmlOptions();
        xmlOptions.setSavePrettyPrint();
        xmlOptions.setSavePrettyPrintIndent(2);
        xmlOptions.setUseDefaultNamespace();
        xmlOptions.setSaveAggressiveNamespaces();
        xmlOptions.setSaveSuggestedPrefixes(namespaces);
        xmlOptions.setSaveNamespacesFirst();

        if (logResponse) {
            logger.info("=======================================================");
            logger.info("IdP response from providerId " + idpProviderId);
            logger.info("");
            StringWriter sw = new StringWriter();
            responseDocument.save(sw, xmlOptions);
            logger.info(sw.toString());
            sw.close();
            logger.info("");
            logger.info("=======================================================");
        }

        // Do the trust
        if (responseDocument.getResponse().getSignature() != null) {
            if (!TrustUtils.verifySignature(responseDocument)) {
                throw new GuanxiException("Trust failed");
            }
            EntityFarm farm = (EntityFarm) getServletContext()
                    .getAttribute(Guanxi.CONTEXT_ATTR_ENGINE_ENTITY_FARM);
            EntityManager manager = farm.getEntityManagerForID(idpProviderId);
            X509Certificate x509 = TrustUtils.getX509CertFromSignature(responseDocument);
            if (x509 != null) {
                Metadata idpMetadata = manager.getMetadata(idpProviderId);
                if (!manager.getTrustEngine().trustEntity(idpMetadata, x509)) {
                    throw new GuanxiException("Trust failed");
                }
            } else {
                throw new GuanxiException("No X509 from signature");
            }
        }

        /* Load up the Guard's private key. We need this to decrypt the secret key
         * which was used to encrypt the attributes.
         */
        KeyStore guardKeystore = KeyStore.getInstance("JKS");
        GuardRoleDescriptorExtensions guardNativeMetadata = Util.getGuardNativeMetadata(guardEntityDescriptor);
        FileInputStream fis = new FileInputStream(guardNativeMetadata.getKeystore());
        guardKeystore.load(fis, guardNativeMetadata.getKeystorePassword().toCharArray());
        fis.close();
        PrivateKey guardPrivateKey = (PrivateKey) guardKeystore.getKey(guardEntityDescriptor.getEntityID(),
                guardNativeMetadata.getKeystorePassword().toCharArray());

        // Decrypt the response if required
        if (isEncrypted(responseDocument)) {
            try {
                responseDocument = decryptResponse(responseDocument, xmlOptions, guardPrivateKey);
            } catch (GuanxiException ge) {
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.println("Decryption error<br /><br />");
                out.println(ge.getMessage());
                out.flush();
                out.close();
                return;
            }
        }

        Config config = (Config) getServletContext().getAttribute(Guanxi.CONTEXT_ATTR_ENGINE_CONFIG);
        processGuardConnection(guardNativeMetadata.getAttributeConsumerServiceURL(),
                guardEntityDescriptor.getEntityID(), guardNativeMetadata.getKeystore(),
                guardNativeMetadata.getKeystorePassword(), config.getTrustStore(),
                config.getTrustStorePassword(), responseDocument, guardSession);

        /* Stop replay attacks.
         * If another message comes in with the same RelayState we won't be able
         * to find the Guard metadata it refers to as we've deleted it.
         */
        getServletContext().removeAttribute(guardSession.replaceAll("GUARD", "ENGINE"));

        response.sendRedirect(guardNativeMetadata.getPodderURL() + "?id=" + guardSession);
    } catch (XmlException xe) {
        logger.error(xe);
    } catch (Exception e) {
        logger.error(e);
    }
}

From source file:com.grarak.kerneladiutor.activities.SecurityActivity.java

private void loadFingerprint() {
    try {/* w  ww.j  a  v a 2 s . c o m*/
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
                "AndroidKeyStore");
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);

        keyStore.load(null);
        keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
        keyGenerator.generateKey();

        SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
        mCipher.init(Cipher.ENCRYPT_MODE, key);
    } catch (KeyStoreException | NoSuchProviderException | NoSuchAlgorithmException | NoSuchPaddingException
            | UnrecoverableKeyException | InvalidKeyException | CertificateException
            | InvalidAlgorithmParameterException | IOException e) {
        return;
    }

    mCryptoObject = new FingerprintManagerCompat.CryptoObject(mCipher);
    FrameLayout fingerprintParent = (FrameLayout) findViewById(R.id.fingerprint_parent);
    final SwirlView swirlView = new SwirlView(new ContextThemeWrapper(this, R.style.Swirl));
    swirlView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    fingerprintParent.addView(swirlView);
    fingerprintParent.setVisibility(View.VISIBLE);

    mFingerprintUiHelper = new FingerprintUiHelper.FingerprintUiHelperBuilder(mFingerprintManagerCompat)
            .build(swirlView, new FingerprintUiHelper.Callback() {
                @Override
                public void onAuthenticated() {
                    try {
                        mCipher.doFinal(SECRET_MESSAGE.getBytes());
                        mPasswordWrong.setVisibility(View.GONE);
                        setResult(1);
                        finish();
                    } catch (IllegalBlockSizeException | BadPaddingException e) {
                        e.printStackTrace();
                        swirlView.setState(SwirlView.State.ERROR);
                    }
                }

                @Override
                public void onError() {
                }
            });
    mFingerprintUiHelper.startListening(mCryptoObject);
}

From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java

@Override
public void afterPropertiesSet() throws Exception {
    if (this.keystore == null) {
        this.logger.warn("No S/MIME KeyStore configured. Email update notifications will NOT be signed");
    } else {/* w w w . j av a 2s  . c  o  m*/
        Security.addProvider(new BouncyCastleProvider());

        final KeyStore signingKeyStore = KeyStore.getInstance("JKS");

        final InputStream keyStoreStream = this.keystore.getInputStream();
        try {
            signingKeyStore.load(keyStoreStream, this.keystorePassword.toCharArray());
        } finally {
            IOUtils.closeQuietly(keyStoreStream);
        }

        final List<Certificate> certList = new ArrayList<Certificate>(1);
        for (final Enumeration<String> aliasesEnum = signingKeyStore.aliases(); aliasesEnum
                .hasMoreElements();) {
            final String alias = aliasesEnum.nextElement();
            final Certificate cert = signingKeyStore.getCertificate(alias);
            if (cert != null) {
                certList.add(cert);
            }
        }

        final PrivateKey signingKey = (PrivateKey) signingKeyStore.getKey(this.certificateAlias,
                this.keystorePassword.toCharArray());
        final X509Certificate signingCert = (X509Certificate) signingKeyStore
                .getCertificate(this.certificateAlias);

        // create a CertStore containing the certificates we want carried
        // in the signature
        final CertStore certsAndcrls = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(certList), "BC");

        // create the generator for creating an smime/signed message
        smimeSignedGenerator = new SMIMESignedGenerator();

        // add a signer to the generator - this specifies we are using SHA1 and
        // adding the smime attributes above to the signed attributes that
        // will be generated as part of the signature. The encryption algorithm
        // used is taken from the key - in this RSA with PKCS1Padding
        smimeSignedGenerator.addSigner(signingKey, signingCert, SMIMESignedGenerator.DIGEST_SHA1);

        // add our pool of certs and cerls (if any) to go with the signature
        smimeSignedGenerator.addCertificatesAndCRLs(certsAndcrls);
    }
}

From source file:org.ejbca.ui.cli.CMPKeyUpdateStressTest.java

@Override
protected void execute(String[] args) {
    final String hostName;
    final String keystoreFile;
    final String keystorePassword;
    final String certNameInKeystore;
    final int numberOfThreads;
    final int waitTime;
    final int port;
    final String urlPath;
    final String resultFilePrefix;
    if (args.length < 5) {
        System.out.println(args[0]
                + " <host name> <keystore (p12)> <keystore password> <friendlyname in keystore> [<number of threads>] [<wait time (ms) between each thread is started>] [<port>] [<URL path of servlet. use 'null' to get EJBCA (not proxy) default>] [<certificate file prefix. set this if you want all received certificates stored on files>]");
        System.out.println(//from   w w w.j a  v a 2 s .  com
                "EJBCA build configuration requirements: cmp.operationmode=normal, cmp.allowraverifypopo=true, cmp.allowautomatickeyupdate=true, cmp.allowupdatewithsamekey=true");
        //            System.out.println("EJBCA build configuration optional: cmp.ra.certificateprofile=KeyId cmp.ra.endentityprofile=KeyId (used when the KeyId argument should be used as profile name).");
        System.out.println(
                "Ejbca expects the following: There exists an end entity with a generated certificate. The end entity's certificate and its private key are stored in the keystore used "
                        + "in the commandline. The end entity's certificate's 'friendly name' in the keystore is the one used in the command line. Such keystore can be obtained, for example, by specifying "
                        + "the token to be 'P12' when creating the end entity and then download the keystore by choosing 'create keystore' from the public web");
        return;
    }
    hostName = args[1];
    keystoreFile = args[2];
    keystorePassword = args[3];
    certNameInKeystore = args[4];
    numberOfThreads = args.length > 5 ? Integer.parseInt(args[5].trim()) : 1;
    waitTime = args.length > 6 ? Integer.parseInt(args[6].trim()) : 0;
    port = args.length > 7 ? Integer.parseInt(args[7].trim()) : 8080;
    //        isHttp = true;
    urlPath = args.length > 8 && args[8].toLowerCase().indexOf("null") < 0 ? args[8].trim() : null;
    resultFilePrefix = args.length > 9 ? args[9].trim() : null;

    CryptoProviderTools.installBCProviderIfNotAvailable();

    Certificate cacert = null;
    Certificate extracert = null;
    PrivateKey oldCertKey = null;

    FileInputStream file_inputstream;
    try {
        file_inputstream = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(file_inputstream, keystorePassword.toCharArray());
        Key key = keyStore.getKey(certNameInKeystore, keystorePassword.toCharArray());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        oldCertKey = keyFactory.generatePrivate(keySpec);
        //extracert = keyStore.getCertificate(certNameInKeystore);

        Certificate[] certs = keyStore.getCertificateChain(certNameInKeystore);
        extracert = certs[0];
        cacert = certs[1];

    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
        System.exit(-1);
    } catch (KeyStoreException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (CertificateException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    try {
        new StressTest(hostName, port, numberOfThreads, waitTime, urlPath, resultFilePrefix, keystorePassword,
                cacert, oldCertKey, extracert);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.texai.x509.X509Utils.java

/** Gets the root private key or null if not executing on a trusted root system.
 *
 * @return the root private key or null if not executing on a trusted root system
 *///from   w w  w. ja va2 s . c o m
public static PrivateKey getRootPrivateKey() {
    if (!isTrustedDevelopmentSystem()) {
        return null;
    }
    try {
        final String filePath = System.getenv("SECURITY_DIR") + "/texai-keystore.jceks";
        final File serverKeyStoreFile = new File(filePath);
        assert serverKeyStoreFile.exists();
        final char[] keyStorePassword = getRootKeyStorePassword();
        assert keyStorePassword != null;
        final boolean isJCEUnlimitedStrenthPolicy1 = isJCEUnlimitedStrengthPolicy();
        setIsJCEUnlimitedStrengthPolicy(true);
        final KeyStore rootKeyStore = findKeyStore(System.getenv("SECURITY_DIR") + "/texai-keystore.jceks",
                getRootKeyStorePassword());
        setIsJCEUnlimitedStrengthPolicy(isJCEUnlimitedStrenthPolicy1);
        assert rootKeyStore != null;
        final PrivateKey privateKey = (PrivateKey) rootKeyStore.getKey(ROOT_ALIAS, keyStorePassword);

        //Postconditions
        assert privateKey != null : "privateKey must not be null";
        assert !isTrustedDevelopmentSystem()
                || X509Utils.isJCEUnlimitedStrengthPolicy() : "JCE unlimited strength policy must be in effect";

        return privateKey;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
            | NoSuchProviderException | UnrecoverableKeyException ex) {
        throw new TexaiException(ex);
    }
}

From source file:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java

private int importKeyStoreTransacted(KeyStore keyStore, MissingKey missingKey) throws KeyStoreException {
    Check.notNull(keyStore, "keyStore");
    Check.notNull(missingKey, "missingKey");

    int importedEntries = 0;

    Enumeration<String> aliases = keyStore.aliases();

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();

        logger.debug("Alias: " + alias);

        Certificate certificate = keyStore.getCertificate(alias);

        if (!(certificate instanceof X509Certificate)) {
            /*/*from   w  ww  .  j a  va2s. c o  m*/
             * only X509Certificates are supported
             */
            continue;
        }

        try {
            Key key = keyStore.getKey(alias, null);

            if (!(key instanceof PrivateKey)) {
                key = null;
            }

            if (key == null && missingKey == MissingKey.SKIP_CERTIFICATE) {
                logger.debug("Certificate found but missing Private key. Skipping certificate");

                continue;
            }

            KeyAndCertificate keyAndCertificate = new KeyAndCertificateImpl((PrivateKey) key,
                    (X509Certificate) certificate);

            if (keyAndCertStore.addKeyAndCertificate(keyAndCertificate)) {
                importedEntries++;
            }

            Certificate[] chain = keyStore.getCertificateChain(alias);

            importedEntries += importChain(chain);
        } catch (UnrecoverableKeyException e) {
            logger.error("Unable to retrieve the key.", e);
        } catch (NoSuchAlgorithmException e) {
            logger.error("Unable to retrieve the key.", e);
        } catch (KeyStoreException e) {
            logger.error("Unable to retrieve the key.", e);
        } catch (CertStoreException e) {
            logger.error("Unable to retrieve the key.", e);
        }
    }

    return importedEntries;
}

From source file:com.sshtools.j2ssh.authentication.UserGridCredential.java

private static GSSCredential retrieveRemoteProxy(SshConnectionProperties properties, int proxyType,
        int lifetimeHours) throws IOException {
    GSSCredential gsscredential = null;
    CoGProperties cogproperties = CoGProperties.getDefault();

    String hostname = DEFAULT_MYPROXY_SERVER;
    hostname = PreferencesStore.get(SshTerminalPanel.PREF_DEFAULT_MYPROXY_HOSTNAME, hostname);
    String username = System.getProperty("user.name");
    username = PreferencesStore.get(SshTerminalPanel.PREF_MYPROXY_UNAME, username);

    if (properties instanceof SshToolsConnectionProfile) {
        SshToolsConnectionProfile profile = (SshToolsConnectionProfile) properties;
        hostname = profile.getApplicationProperty(SshTerminalPanel.PREF_DEFAULT_MYPROXY_HOSTNAME, hostname);
        username = profile.getApplicationProperty(SshTerminalPanel.PREF_MYPROXY_UNAME, username);
    }//from w  w w  .  j a va2 s  .c om

    do {
        boolean flag = false;
        StringBuffer stringbuffer = new StringBuffer();
        StringBuffer stringbuffer1 = new StringBuffer();
        StringBuffer stringbuffer2 = new StringBuffer();
        if (myProxyPrompt != null) {

            myProxyPrompt.setHost(hostname);
            myProxyPrompt.setAccountName(username);

            boolean flag1 = myProxyPrompt.doGet(properties.getWindow(), stringbuffer, stringbuffer1,
                    stringbuffer2);
            myProxyPrompt.setError("");
            if (flag1)
                throw new IOException("Canceled by user.");
            if (myProxyPrompt.getAnother())
                return null;

            StringBuffer stringbufferF = new StringBuffer();
            StringBuffer stringbufferP = new StringBuffer();
            if (myProxyPrompt.getBrowser()) {
                gsscredential = chooseCert(proxyType, lifetimeHours, properties);
                if (gsscredential == null)
                    continue;
                else
                    return gsscredential;
            }
            if (myProxyPrompt.keyBased(stringbufferF, stringbufferP)) {
                try {
                    KeyStore store = null;
                    String passphrase = stringbufferP.toString();
                    File keyfile = new File(stringbufferF.toString());
                    Security.addProvider(new BouncyCastleProvider());
                    store = KeyStore.getInstance("PKCS12", "BC");
                    FileInputStream in = new FileInputStream(keyfile);
                    store.load(in, passphrase.toCharArray());

                    Enumeration e = store.aliases();
                    if (!e.hasMoreElements()) {
                        JOptionPane.showMessageDialog(properties.getWindow(),
                                "Could not access your certificate: no certificates found in file.",
                                "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE);
                        continue;
                    }
                    String alias = (String) e.nextElement();
                    java.security.cert.Certificate cert = store.getCertificate(alias);
                    Key key = store.getKey(alias, passphrase.toCharArray());

                    if (!(cert instanceof X509Certificate)) {
                        JOptionPane.showMessageDialog(properties.getWindow(),
                                "Could not access your certificate: bad certificate type.",
                                "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE);
                        continue;
                    }
                    if (!(key instanceof PrivateKey)) {
                        JOptionPane.showMessageDialog(properties.getWindow(),
                                "Could not access your certificate: bad key type.",
                                "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE);
                        continue;
                    }

                    BouncyCastleCertProcessingFactory factory = BouncyCastleCertProcessingFactory.getDefault();

                    GlobusCredential globuscredential = factory.createCredential(
                            new X509Certificate[] { (X509Certificate) cert }, (PrivateKey) key,
                            cogproperties.getProxyStrength(), lifetimeHours * 3600, proxyType,
                            (X509ExtensionSet) null);

                    if (globuscredential != null) {
                        if (SAVE_PKCS12_PROXY) {
                            ProxyHelper.saveProxy(globuscredential, properties);
                        }
                        try {
                            globuscredential.verify();
                            gsscredential = new GlobusGSSCredentialImpl(globuscredential, 1);
                        } catch (Exception exception1) {
                            exception1.printStackTrace();
                            StringWriter stringwriter1 = new StringWriter();
                            exception1.printStackTrace(new PrintWriter(stringwriter1));
                            log.debug(stringwriter1);
                            if (exception1.getMessage().indexOf("Expired credentials") >= 0) {
                                JOptionPane.showMessageDialog(properties.getWindow(),
                                        "Your certificate has expired, please renew your certificate or try another method for authentication.",
                                        "GSI-SSHTerm Authentication", JOptionPane.ERROR_MESSAGE);
                                continue;
                            } else {
                                errorReport(properties.getWindow(), "Could not load your certificate",
                                        exception1);
                                continue;
                            }
                        }

                    }
                    return gsscredential;
                } catch (java.io.FileNotFoundException exception) {
                    exception.printStackTrace();
                    StringWriter stringwriter = new StringWriter();
                    exception.printStackTrace(new PrintWriter(stringwriter));
                    log.debug(stringwriter);
                    myProxyPrompt.setError("Certificate: could not find file");
                    continue;
                } catch (Exception exception) {
                    if (exception.getMessage().indexOf("Illegal key size") >= 0) {
                        exception.printStackTrace();
                        StringWriter stringwriter = new StringWriter();
                        exception.printStackTrace(new PrintWriter(stringwriter));
                        log.debug(stringwriter);
                        errorReport(properties.getWindow(),
                                "To use this PKCS#12 file you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files\n (see http://java.sun.com/javase/downloads/index.jsp for Java 6 and http://java.sun.com/javase/downloads/index_jdk5.jsp for Java 5)",
                                exception);
                        continue;
                    } else if (exception.getMessage().indexOf("wrong password") >= 0) {
                        exception.printStackTrace();
                        StringWriter stringwriter = new StringWriter();
                        exception.printStackTrace(new PrintWriter(stringwriter));
                        log.debug(stringwriter);
                        myProxyPrompt.setError("Certificate: wrong password?");
                        continue;
                    } else {
                        exception.printStackTrace();
                        StringWriter stringwriter = new StringWriter();
                        exception.printStackTrace(new PrintWriter(stringwriter));
                        log.debug(stringwriter);
                        errorReport(properties.getWindow(), "Unknown problem while loading your certificate",
                                exception);
                        continue;
                    }
                }
            }
        }
        CertUtil.init();
        // save username if changed:
        if (!stringbuffer1.toString().equals(username)) {
            PreferencesStore.put(SshTerminalPanel.PREF_LAST_MYPROXY_USERNAME, stringbuffer1.toString());
        }
        String port_S = DEFAULT_MYPROXY_PORT;
        port_S = PreferencesStore.get(SshTerminalPanel.PREF_MYPROXY_PORT, port_S);
        if (properties instanceof SshToolsConnectionProfile) {
            SshToolsConnectionProfile profile = (SshToolsConnectionProfile) properties;
            port_S = profile.getApplicationProperty(SshTerminalPanel.PREF_MYPROXY_PORT, port_S);
        }
        int port = 7512;
        try {
            port = Integer.parseInt(port_S);
        } catch (NumberFormatException e) {
            log.warn("Could not parse the port number from defaults file (property name"
                    + SshTerminalPanel.PREF_MYPROXY_PORT + ", property value= " + port_S + ").");
        }
        MyProxy myproxy = null;
        myproxy = new MyProxy(stringbuffer.toString(), port);
        try {
            gsscredential = myproxy.get(null, stringbuffer1.toString(), stringbuffer2.toString(),
                    lifetimeHours * 3600);

            if (SAVE_MYPROXY_PROXY) {
                GlobusCredential proxy = ((GlobusGSSCredentialImpl) gsscredential).getGlobusCredential();
                ProxyHelper.saveProxy(proxy, properties);
            }
            log.debug("A proxy has been received for user " + stringbuffer1);
            return gsscredential;
        } catch (Exception exception) {
            if (exception.getMessage().indexOf("Credentials do not exist") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: No credentials on server (wrong username?)");
            } else if (exception.getMessage().indexOf("Bad password") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Bad username and/or password");
            } else if (exception.getMessage()
                    .indexOf("Failed to map username too DN via grid-mapfile CA failed to map user") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Bad username/password");
            } else if (exception.getMessage().indexOf("PAM authentication failed") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Bad username/password");
            } else if (exception.getMessage().indexOf("credentials have expired") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Credentials on server has expired");
            } else if (exception.getMessage().indexOf(stringbuffer.toString()) >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Could not connect to MyProxy server");
            } else if (exception.getMessage().indexOf("Password must be at least 6 characters long") >= 0) {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                myProxyPrompt.setError("MyProxy: Password must be at least 6 characters long.");
            } else {
                exception.printStackTrace();
                StringWriter stringwriter = new StringWriter();
                exception.printStackTrace(new PrintWriter(stringwriter));
                log.debug(stringwriter);
                errorReport(properties.getWindow(), "Unknown problem while accessing MyProxy", exception);
                continue;
            }
        }
    } while (true);
}

From source file:org.nuxeo.ecm.core.blob.binary.AESBinaryManager.java

/**
 * Gets the AES key from the keystore.// w  ww. j a v a  2 s.co  m
 */
protected Key getSecretKey() throws GeneralSecurityException, IOException {
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    char[] kspw = keyStorePassword == null ? null : keyStorePassword.toCharArray();
    if (keyStoreFile != null) {
        try (InputStream in = new BufferedInputStream(new FileInputStream(keyStoreFile))) {
            keyStore.load(in, kspw);
        }
    } else {
        // some keystores are not backed by a file
        keyStore.load(null, kspw);
    }
    clearPassword(kspw);
    char[] kpw = keyPassword == null ? null : keyPassword.toCharArray();
    Key key = keyStore.getKey(keyAlias, kpw);
    clearPassword(kpw);
    return key;
}