Example usage for java.security KeyStore getDefaultType

List of usage examples for java.security KeyStore getDefaultType

Introduction

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

Prototype

public static final String getDefaultType() 

Source Link

Document

Returns the default keystore type as specified by the keystore.type security property, or the string "jks" (acronym for "Java keystore" ) if no such property exists.

Usage

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

@Override
public void savePKCS12Keystore(String keystore, String password) throws CertificateException {
    KeyStore keyStore = loadKeyStore(PKCS12_KEYSTORE_TYPE,
            new ByteArrayInputStream(Base64.decodeBase64(keystore)), password);
    final String newPassword = generateNewKeyStorePassword();
    KeyStore newKeyStore = loadKeyStore(KeyStore.getDefaultType(), null, newPassword);

    // change the password to our local random one
    copyNodeChain(keyStore, password, newKeyStore, newPassword);

    File ksFile = new File(getKeyStorePath());
    if (ksFile.isFile()) {
        ksFile.delete();/*from   w ww  . ja v a  2s .c  o m*/
    }
    saveKeyStore(newKeyStore, newPassword);
    setupIdentityDao
            .saveSetupIdentityInfo(setupIdentityDao.getSetupIdentityInfo().withKeyStorePassword(newPassword));
}

From source file:io.selendroid.standalone.builder.SelendroidServerBuilder.java

private String getSigAlg() {
    String sigAlg = "MD5withRSA";
    FileInputStream in;/*from w w w .ja va2 s  .c om*/
    try {
        if (serverConfiguration != null) {
            String keystoreFile = serverConfiguration.getKeystore();
            if (keystoreFile != null) {
                in = new FileInputStream(keystoreFile);

                KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
                String keystorePassword = serverConfiguration.getKeystorePassword();
                char[] keystorePasswordCharArray = (keystorePassword == null) ? null
                        : keystorePassword.toCharArray();
                if (keystorePasswordCharArray == null) {
                    throw new RuntimeException("No keystore password configured.");
                }
                keystore.load(in, keystorePasswordCharArray);
                cert509 = (X509Certificate) keystore.getCertificate(serverConfiguration.getKeystoreAlias());
                sigAlg = cert509.getSigAlgName();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING,
                String.format("Error getting signature algorithm for jarsigner. Defaulting to %s. Reason: %s",
                        sigAlg, e.getMessage()));
    }
    return sigAlg;
}

From source file:edu.vt.middleware.ldap.LdapTLSSocketFactory.java

/**
 * This attempts to load a keystore from the supplied <code>InputStream</code>
 * using the supplied password./*from  ww w  .  j  a v a 2 s  .c  om*/
 *
 * @param  is  <code>InputStream</code> containing the keystore
 * @param  password  <code>String</code> to unlock the keystore
 * @param  storeType  <code>String</code> of keystore
 *
 * @return  <code>KeyStore</code>
 *
 * @throws  IOException  if the keystore cannot be loaded
 * @throws  GeneralSecurityException  if an errors occurs while loading the
 * KeyManagers
 */
private KeyStore loadKeyStore(final InputStream is, final String password, final String storeType)
        throws IOException, GeneralSecurityException {
    KeyStore keystore = null;
    if (is != null) {
        String type = storeType;
        if (type == null) {
            type = KeyStore.getDefaultType();
        }
        keystore = KeyStore.getInstance(type);

        char[] pw = null;
        if (password != null) {
            pw = password.toCharArray();
        }
        keystore.load(is, pw);
    }
    return keystore;
}

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   www.  ja va  2s .  c o  m*/
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:net.i2p.util.I2PSSLSocketFactory.java

/**
 *  Loads certs from/* www  . j av  a 2  s  .com*/
 *  the ~/.i2p/certificates/ and $I2P/certificates/ directories.
 */
private static SSLSocketFactory initSSLContext(I2PAppContext context, boolean loadSystemCerts,
        String relativeCertPath) throws GeneralSecurityException {
    Log log = context.logManager().getLog(I2PSSLSocketFactory.class);
    KeyStore ks;
    if (loadSystemCerts) {
        ks = KeyStoreUtil.loadSystemKeyStore();
        if (ks == null)
            throw new GeneralSecurityException("Key Store init error");
    } else {
        try {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, "".toCharArray());
        } catch (IOException ioe) {
            throw new GeneralSecurityException("Key Store init error", ioe);
        }
    }

    File dir = new File(context.getConfigDir(), relativeCertPath);
    int adds = KeyStoreUtil.addCerts(dir, ks);
    int totalAdds = adds;
    if (adds > 0) {
        if (log.shouldLog(Log.INFO))
            log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath());
    }

    File dir2 = new File(context.getBaseDir(), relativeCertPath);
    if (!dir.getAbsolutePath().equals(dir2.getAbsolutePath())) {
        adds = KeyStoreUtil.addCerts(dir2, ks);
        totalAdds += adds;
        if (adds > 0) {
            if (log.shouldLog(Log.INFO))
                log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath());
        }
    }
    if (totalAdds > 0 || loadSystemCerts) {
        if (log.shouldLog(Log.INFO))
            log.info("Loaded total of " + totalAdds + " new trusted certificates");
    } else {
        String msg = "No trusted certificates loaded (looked in " + dir.getAbsolutePath()
                + (dir.getAbsolutePath().equals(dir2.getAbsolutePath()) ? ""
                        : (" and " + dir2.getAbsolutePath()))
                + ", SSL connections will fail. " + "Copy the cert in " + relativeCertPath
                + " from the router to the directory.";
        // don't continue, since we didn't load the system keystore, we have nothing.
        throw new GeneralSecurityException(msg);
    }

    SSLContext sslc = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    sslc.init(null, tmf.getTrustManagers(), context.random());
    return sslc.getSocketFactory();
}

From source file:org.structr.util.StructrLicenseManager.java

private static void sign(final Map<String, String> properties, final String keystoreFileName,
        final String password) {

    final String src = collectLicenseFieldsForSignature(properties);

    try {//from   ww w  .ja  va2  s  . co m

        final byte[] data = src.getBytes(CharSet);
        final Signature signer = Signature.getInstance(SignatureAlgorithm);
        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        try (final InputStream is = new FileInputStream(keystoreFileName)) {

            keyStore.load(is, password.toCharArray());

            final Key key = keyStore.getKey(KeystoreAlias, password.toCharArray());

            signer.initSign((PrivateKey) key);
            signer.update(data);

            properties.put(SignatureKey, Hex.encodeHexString(signer.sign()));
        }

    } catch (Throwable t) {
        logger.warn("Unable to sign license.", t);
    }
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * Retrieve the certificate which is represented by the given alias.
 *
 * @param alias : The alias of the required certificate.
 * @return : The Certificate as a ByteArrayInputStream.
 * @throws CertificateManagementException :
 *//*from w w  w . ja va2 s.c  om*/
public ByteArrayInputStream getCertificateContent(String alias) throws CertificateManagementException {

    File trustStoreFile = new File(TRUST_STORE);
    Certificate certificate;
    try {
        localTrustStoreStream = new FileInputStream(trustStoreFile);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD);

        if (trustStore.containsAlias(alias)) {
            certificate = trustStore.getCertificate(alias);
            return new ByteArrayInputStream(certificate.getEncoded());
        }
    } catch (IOException e) {
        throw new CertificateManagementException("Error in loading the certificate.", e);
    } catch (CertificateException e) {
        throw new CertificateManagementException("Error loading certificate.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateManagementException("Could not find the algorithm to load the certificate.", e);
    } catch (KeyStoreException e) {
        throw new CertificateManagementException("Error reading certificate contents.", e);
    } finally {
        closeStreams(localTrustStoreStream);
    }
    return null;
}