Example usage for java.security KeyStore getInstance

List of usage examples for java.security KeyStore getInstance

Introduction

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

Prototype

public static KeyStore getInstance(String type) throws KeyStoreException 

Source Link

Document

Returns a keystore object of the specified type.

Usage

From source file:com.fanmei.pay4j.http.WeixinSSLRequestExecutor.java

public WeixinSSLRequestExecutor(WeixinConfig weixinConfig) throws WeixinException {
    InputStream inputStream = this.getClass().getClassLoader()
            .getResourceAsStream(weixinConfig.getCertificateFile());
    try {/*  ww w .  j a v a  2  s  .  co  m*/
        String password = weixinConfig.getAccount().getCertificateKey();
        KeyStore keyStore = KeyStore.getInstance(Constants.PKCS12);
        keyStore.load(inputStream, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(Constants.SunX509);
        kmf.init(keyStore, password.toCharArray());
        SSLContext sslContext = SSLContext.getInstance(Constants.TLS);
        sslContext.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (Exception e) {
        throw WeixinException.of("Key load error", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {

            }
        }
    }
}

From source file:com.thoughtworks.go.security.KeyStoreManager.java

public void storeCACertificate(File storeFile, String password, Certificate caCertificate, Registration entry)
        throws Exception {
    lazyLoadedStore = KeyStore.getInstance(KEYSTORE_TYPE);
    loadStore(lazyLoadedStore);//  ww w .j  a va 2s  . c  o m

    lazyLoadedStore.setCertificateEntry("ca-cert", caCertificate);
    lazyLoadedStore.setEntry("ca-intermediate", entry.asKeyStoreEntry(),
            new KeyStore.PasswordProtection(password.toCharArray()));
    writeStore(storeFile, password);
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.FroyoSupport.java

private static SSLSocketFactory createAdditionalCertsSSLSocketFactory() {
    try {/*from  ww  w  . j av a2s  .c  o m*/
        final KeyStore ks = KeyStore.getInstance("BKS");

        final InputStream in = MainActivity.getInstance().getResources()
                .openRawResource(R.raw.mobileservicestore);
        try {
            ks.load(in, "mobileservices".toCharArray());
        } finally {
            in.close();
        }

        return new AdditionalKeyStoresSSLSocketFactory(ks);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ee.sk.hwcrypto.demo.signature.TestSigningData.java

private static X509Certificate getSigningCert(String pkiContainer, String pkiContainerPassword) {
    try {//from  w ww  .j av  a 2s . c  o  m
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try (FileInputStream stream = new FileInputStream(pkiContainer)) {
            keyStore.load(stream, pkiContainerPassword.toCharArray());
        }
        return (X509Certificate) keyStore.getCertificate("1");
    } catch (Exception e) {
        throw new RuntimeException("Loading signer cert failed");
    }
}

From source file:psiprobe.controllers.truststore.TrustStoreController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    List<Map<String, String>> certificateList = new ArrayList<>();
    try {//from w  w w . j a  va  2  s  . co m
        String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType");
        KeyStore ks;
        if (trustStoreType != null) {
            ks = KeyStore.getInstance(trustStoreType);
        } else {
            ks = KeyStore.getInstance("JKS");
        }
        String trustStore = System.getProperty("javax.net.ssl.trustStore");
        String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
        if (trustStore != null) {
            try (FileInputStream fis = new FileInputStream(trustStore)) {
                ks.load(fis, trustStorePassword != null ? trustStorePassword.toCharArray() : null);
            }
            Map<String, String> attributes;
            for (String alias : Collections.list(ks.aliases())) {
                attributes = new HashMap<>();
                if (ks.getCertificate(alias).getType().equals("X.509")) {
                    X509Certificate cert = (X509Certificate) ks.getCertificate(alias);

                    attributes.put("alias", alias);
                    attributes.put("cn", cert.getSubjectDN().toString());
                    attributes.put("expirationDate",
                            new SimpleDateFormat("yyyy-MM-dd").format(cert.getNotAfter()));
                    certificateList.add(attributes);
                }
            }
        }
    } catch (Exception e) {
        logger.error("There was an exception obtaining truststore: ", e);
    }
    ModelAndView mv = new ModelAndView(getViewName());
    mv.addObject("certificates", certificateList);
    return mv;
}

From source file:com.pieframework.runtime.utils.CertificateUtils.java

public static X509Certificate getCertificate(File certificateFile, String pass, String certAlias) {
    X509Certificate certificate = null;

    try {//from w  w w  .  j av a 2 s .  c  o m
        FileInputStream cert = new FileInputStream(certificateFile);
        KeyStore pfxStore = KeyStore.getInstance("pkcs12");
        pfxStore.load(cert, pass.toCharArray());
        if (StringUtils.empty(certAlias) && pfxStore.size() > 0) {
            certAlias = pfxStore.aliases().nextElement();
        }
        certificate = (X509Certificate) pfxStore.getCertificate(certAlias);
        cert.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return certificate;
}

From source file:no.difi.sdp.client.SikkerDigitalPostKlientIntegrationTest.java

private Noekkelpar avsenderNoekkelpar() {
    try {//  w  w  w .j  av a2s  .c  om
        String alias = "meldingsformidler";
        String passphrase = "abcd1234";
        String keyStoreFile = "/keystore.jce";

        KeyStore keyStore = KeyStore.getInstance("JCEKS");
        keyStore.load(new ClassPathResource(keyStoreFile).getInputStream(), passphrase.toCharArray());
        return Noekkelpar.fraKeyStore(keyStore, alias, passphrase);
    } catch (Exception e) {
        throw new RuntimeException("Kunne ikke laste nkkelpar for kjring av tester. "
                + "For  kjre integrasjonstester m det ligge inne et gyldig virksomhetssertifikat for test (med tilhrende certificate chain). "
                + "Keystore med tilhrende alias og passphrase settes i " + this.getClass().getSimpleName()
                + ".", e);
    }
}

From source file:com.threerings.getdown.tools.Digester.java

/**
 * Creates a digest file in the specified application directory.
 *///ww w.  jav  a 2 s .  c  om
public static void signDigest(File appdir, File storePath, String storePass, String storeAlias)
        throws IOException, GeneralSecurityException {
    File inputFile = new File(appdir, Digest.DIGEST_FILE);
    File signatureFile = new File(appdir, Digest.DIGEST_FILE + Application.SIGNATURE_SUFFIX);

    FileInputStream storeInput = null, dataInput = null;
    FileOutputStream signatureOutput = null;
    try {
        // initialize the keystore
        KeyStore store = KeyStore.getInstance("JKS");
        storeInput = new FileInputStream(storePath);
        store.load(storeInput, storePass.toCharArray());
        PrivateKey key = (PrivateKey) store.getKey(storeAlias, storePass.toCharArray());

        // sign the digest file
        Signature sig = Signature.getInstance("SHA1withRSA");
        dataInput = new FileInputStream(inputFile);
        byte[] buffer = new byte[8192];
        int length;

        sig.initSign(key);
        while ((length = dataInput.read(buffer)) != -1) {
            sig.update(buffer, 0, length);
        }

        // Write out the signature
        signatureOutput = new FileOutputStream(signatureFile);
        String signed = new String(Base64.encodeBase64(sig.sign()));
        signatureOutput.write(signed.getBytes("utf8"));

    } finally {
        StreamUtil.close(signatureOutput);
        StreamUtil.close(dataInput);
        StreamUtil.close(storeInput);
    }
}

From source file:com.iaspec.rda.plugins.rfid.license.LicenseReader.java

public static void verifyChallengeCode(String challenge, String expect, Device device) throws RdaException {
    ChallengeVerifier verifier = ChallengeVerifier.getInstance();
    byte[] pkcs7 = Base64.decode(challenge);
    SignatureVerificationResultHolder resultHolder = null;
    try {/*  www.  j ava  2 s .c om*/
        resultHolder = verifier.verifySignature(pkcs7);
    } catch (SignatureInvalidException se) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    } catch (CryptoException se) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    }
    CertificateDnInfoDTO certSubjectDn = CertUtil.getCertificateSubjectInfo(resultHolder.signingCertChain[0]);
    // Handle CN checks
    String cn = certSubjectDn.getCn().get(0).toString();

    if (!cn.equalsIgnoreCase(device.getId())) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_LICENSE);
    }

    logger.debug("Signature Verification success: certSubject=["
            + resultHolder.signingCertChain[0].getSubjectDN().toString() + "], orignialContent=["
            + new String(resultHolder.originalData) + "]");

    if (!new String(resultHolder.originalData).equalsIgnoreCase(expect)) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    }

    try {
        KeyStore trustedStore = KeyStore.getInstance("JKS");
        trustedStore.load(null, null);
        // byte[] certBytes = IOUtils.toByteArray(new
        // FileInputStream("RDA_RFID_CA_2.cer")); //false CA certificate

        // byte[] certBytes = IOUtils.toByteArray(new
        // FileInputStream("RDA_RFID_CA.cer"));
        byte[] certBytes = IOUtils.toByteArray(ResourceHelper.readResource("RDA_RFID_CA.cer"));

        // valid CA certificate
        X509Certificate cert = CertUtil.getX509Certificate(certBytes);
        // may add any trusted certificate (CA or Self-signed) to the
        // keystore...
        trustedStore.setCertificateEntry(cert.getSubjectDN().getName().toString(), cert);

        verifier.isCertificateTrust(resultHolder.signingCertChain[0], trustedStore, null);

        // if trusted, do CRL verification if crl can supplied
        /*
         * if
        * (!CertUtil.verifyRevoked(ResourceHelper.readResource("crl.crl"),
        * cert)) { throw new
        * RdaException(ExceptionMessages.EXCEPTION_CERTIFICATE_IS_REVOKED);
        * }
        */

    } catch (com.iaspec.rda.rfid.server.crypto.exception.CertificateNotValidException se) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_LICENSE);
    } catch (CertificateException ce) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    } catch (RdaException e) {
        throw new RdaException(e.getMessage());
    } catch (Exception e) {
        throw new RdaException(ExceptionMessages.EXCEPTION_SYSTEM);
    }

    logger.debug("The certificate is trusted");
}

From source file:eu.europa.esig.dss.token.JKSSignatureToken.java

/**
 * Creates a SignatureTokenConnection with the provided InputStream to Java KeyStore file and password.
 *
 * @param ksStream/* ww  w . j a va 2  s .c om*/
 * @param ksPassword
 */
public JKSSignatureToken(InputStream ksStream, String ksPassword) {
    try {
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        password = (ksPassword == null) ? null : ksPassword.toCharArray();
        keyStore.load(ksStream, password);
    } catch (Exception e) {
        throw new DSSException(e);
    } finally {
        IOUtils.closeQuietly(ksStream);
    }
}