Example usage for java.security.cert CertificateFactory getInstance

List of usage examples for java.security.cert CertificateFactory getInstance

Introduction

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

Prototype

public static final CertificateFactory getInstance(String type) throws CertificateException 

Source Link

Document

Returns a certificate factory object that implements the specified certificate type.

Usage

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

private X509CRL readCRL(PublicKey signatureKey) throws Exception {
    // We could return a X509CRLHolder but that class isn't as fully featured as the built in
    // X509CRL./*from w w w  . j  av  a2s. c om*/
    InputStream changedStream = new BufferedInputStream(new FileInputStream(outfile));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509CRL changedCrl = (X509CRL) cf.generateCRL(changedStream);
    changedCrl.verify(signatureKey, BC.PROVIDER_NAME);

    return changedCrl;
}

From source file:com.microsoft.azure.batch.CertificateOperations.java

/**
 * Creates a new {@link Certificate} from .cer format data in stream.
 *
 * @param certStream The certificate data in .cer format.
 * @param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
 * @throws BatchErrorException Exception thrown from REST call
 * @throws IOException Exception thrown from serialization/deserialization
 * @throws CertificateException Exception thrown on parsing errors
 * @throws NoSuchAlgorithmException Exception thrown if the X509 provider is not registered in the security provider list.
 */// www  .  ja  v a 2s .c  o  m
public void createCertificate(InputStream certStream, Iterable<BatchClientBehavior> additionalBehaviors)
        throws BatchErrorException, IOException, CertificateException, NoSuchAlgorithmException {
    CertificateFactory x509CertFact = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) x509CertFact.generateCertificate(certStream);

    CertificateAddParameter addParam = new CertificateAddParameter();
    addParam.withCertificateFormat(CertificateFormat.CER);
    addParam.withThumbprintAlgorithm(SHA1_CERTIFICATE_ALGORITHM);
    addParam.withThumbprint(getThumbPrint(cert));
    addParam.withData(Base64.encodeBase64String(cert.getEncoded()));

    createCertificate(addParam, additionalBehaviors);
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

/**
 * Loader constructor. Loads an existing MyCareNet session key.
 * /*  w w w  . ja v  a 2  s .co  m*/
 * @param encodedPrivateKey
 * @param encodedPublicKey
 * @param encodedCertificate
 * @param notBefore
 * @param notAfter
 */
public SessionKey(byte[] encodedPrivateKey, byte[] encodedPublicKey, byte[] encodedCertificate, Date notBefore,
        Date notAfter) {
    this.notBefore = notBefore;
    this.notAfter = notAfter;

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("RSA", e);
    }
    PublicKey publicKey;
    try {
        publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid public key: " + e.getMessage(), e);
    }

    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey;
    try {
        privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid private key: " + e.getMessage(), e);
    }

    this.keyPair = new KeyPair(publicKey, privateKey);

    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
    try {
        this.certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (CertificateException e) {
        throw new RuntimeException("certificate decoding error: " + e.getMessage(), e);
    }
}

From source file:org.kuali.rice.ksb.messaging.KSBHttpInvokerRequestExecutor.java

/**
 * Returns a wrapped InputStream which is responsible for verifying the digital signature on the response after all
 * data has been read.// w ww  .  j  a va  2s.  com
 */
@Override
protected InputStream getResponseBody(HttpInvokerClientConfiguration config, HttpResponse postMethod)
        throws IOException {
    if (isSecure()) {
        // extract and validate the headers
        Header digitalSignatureHeader = postMethod.getFirstHeader(KSBConstants.DIGITAL_SIGNATURE_HEADER);
        Header keyStoreAliasHeader = postMethod.getFirstHeader(KSBConstants.KEYSTORE_ALIAS_HEADER);
        Header certificateHeader = postMethod.getFirstHeader(KSBConstants.KEYSTORE_CERTIFICATE_HEADER);

        if (digitalSignatureHeader == null || StringUtils.isEmpty(digitalSignatureHeader.getValue())) {
            throw new RuntimeException(
                    "A digital signature header was required on the response but none was found.");
        }

        boolean foundValidKeystoreAlias = (keyStoreAliasHeader != null
                && StringUtils.isNotBlank(keyStoreAliasHeader.getValue()));
        boolean foundValidCertificate = (certificateHeader != null
                && StringUtils.isNotBlank(certificateHeader.getValue()));

        if (!foundValidCertificate && !foundValidKeystoreAlias) {
            throw new RuntimeException(
                    "Either a key store alias header or a certificate header was required on the response but neither were found.");
        }

        // decode the digital signature from the header into binary
        byte[] digitalSignature = Base64.decodeBase64(digitalSignatureHeader.getValue().getBytes("UTF-8"));
        String errorQualifier = "General Security Error";

        try {
            Signature signature = null;

            if (foundValidCertificate) {
                errorQualifier = "Error with given certificate";
                // get the Signature for verification based on the alias that was sent to us
                byte[] encodedCertificate = Base64.decodeBase64(certificateHeader.getValue().getBytes("UTF-8"));
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                signature = getDigitalSignatureService().getSignatureForVerification(
                        cf.generateCertificate(new ByteArrayInputStream(encodedCertificate)));
            } else if (foundValidKeystoreAlias) {
                // get the Signature for verification based on the alias that was sent to us
                String keystoreAlias = keyStoreAliasHeader.getValue();
                errorQualifier = "Error with given alias " + keystoreAlias;
                signature = getDigitalSignatureService().getSignatureForVerification(keystoreAlias);
            }

            // wrap the InputStream in an input stream that will verify the signature
            return new SignatureVerifyingInputStream(digitalSignature, signature,
                    super.getResponseBody(config, postMethod));
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("Problem verifying signature: " + errorQualifier, e);
        }
    }

    return super.getResponseBody(config, postMethod);
}

From source file:eu.optimis.trustedinstance.TrustedInstanceImpl.java

private synchronized void initialize() {
    //storage = new DBStorage();

    String keystore = ComponentConfigurationProvider.getString("trusted.instance.keystore"); //$NON-NLS-1$
    String password = ComponentConfigurationProvider.getString("trusted.instance.keystore.password"); //$NON-NLS-1$
    String alias = ComponentConfigurationProvider.getString("trusted.instance.keystore.alias"); //$NON-NLS-1$
    String publicCert = ComponentConfigurationProvider.getString("trusted.instance.keystore.public.cert"); //$NON-NLS-1$
    infoServiceName = ComponentConfigurationProvider.getString("trusted.instance.infoservice.client.name");
    infoServiceUrl = ComponentConfigurationProvider.getString("trusted.instance.infoservice.client.url");

    try {/*  ww w.j av  a  2  s.c o m*/

        keyStore_input_stream = getClass().getResourceAsStream(keystore);

        if (keyStore_input_stream == null) {
            throw new Exception("unable to load keystore of the trusted instance");
        }

        if (password == null) {
            throw new Exception("unable to load passowrd of the keystore");
        }

        ti_keyStorePass = password.toCharArray();

        if (alias == null) {
            throw new Exception("unable to load alias of the keystore");
        }

        ti_keyStoreAlias = alias;

        publicCert_input_stream = getClass().getResourceAsStream(publicCert);

        if (publicCert_input_stream == null) {
            throw new Exception("unable to load public certificate of the trusted instance");
        }

        CertificateFactory ti_cf = CertificateFactory.getInstance("X.509");
        ti_certificate = (X509Certificate) ti_cf.generateCertificate(publicCert_input_stream);

        ti_ks = KeyStore.getInstance("JKS");
        ti_ks.load(keyStore_input_stream, ti_keyStorePass);

        if (infoServiceName == null) {
            throw new Exception("unable to find name for ProviderInfoService");
        }

        if (infoServiceUrl == null) {
            throw new Exception("unable to find URL for ProviderInfoService");
        }

    } catch (Exception e) {
        System.out.println("ERROR: " + e.getMessage());
    }
}

From source file:kr.co.exsoft.eframework.util.LicenseUtil.java

/**
 * //from ww  w .j av a 2  s.c  o  m
 * <pre> 
 * 1.  :  ??   WAS
 * 2.  :
 * </pre>
 * @Method Name : decipherLicenseKeyWeb
 * @param licenseKey
 * @return String
 * @throws Exception
 */
public static String decipherLicenseKeyWeb(String licenseKey) throws Exception {

    String ret = null;

    if (StringUtils.isNotBlank(licenseKey)) {

        // URLDecoder - ? ?   
        String certName = URLDecoder.decode(
                LicenseUtil.class.getResource("/").getPath() + "kr/co/exsoft/eframework/cert/exsoft.cer",
                "utf-8");

        //  WAS  
        if (certName.indexOf("WEB-INF/") != -1) {
            certName = certName.replace("WEB-INF", "WEB-INF/");
        }

        FileInputStream certfis = null;

        try {
            certfis = new FileInputStream(certName);
        } catch (Exception e) {
            // JBOSS?  Jboss system property?   .
            // Jboss system  ? standalone.xml ? 
            /*<system-properties>
               <property name="org.apache.catalina.connector.URI_ENCODING" value="UTF-8" />
               <property name="org.apache.catalina.connector.USE_BODY_ENCODING_FOR_QUERY_STRING" value="true" />
               <property name="exsoft.license.cert.path" value="D:/jboss-eap-6.3/standalone/deployments/EDMS3.0.war/WEB-INF/classes" /> 
            </system-properties>*/
            // Jboss exception ?  WAS System property    

            certName = URLDecoder.decode(
                    System.getProperty("exsoft.license.cert.path") + "/kr/co/exsoft/eframework/cert/exsoft.cer",
                    "utf-8");

            try {
                certfis = new FileInputStream(certName);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate cert = cf.generateCertificate(certfis);

        PublicKey key = cert.getPublicKey();

        // ??  .
        ret = unspell(licenseKey, key);
    }

    return ret;
}

From source file:io.fabric8.utils.cxf.WebClients.java

public static KeyStore createKeyStore(String clientCertData, File clientCertFile, String clientKeyData,
        File clientKeyFile, String clientKeyAlgo, char[] clientKeyPassword) throws Exception {
    try (InputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

        InputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile);
        PEMReader reader = new PEMReader(keyInputStream);
        RSAPrivateCrtKeySpec keySpec = new PKCS1EncodedKeySpec(reader.getDerBytes()).getKeySpec();
        KeyFactory kf = KeyFactory.getInstance(clientKeyAlgo);
        RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null);/*from w  w w .java2s.c o  m*/

        String alias = cert.getSubjectX500Principal().getName();
        keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert });

        return keyStore;
    }
}

From source file:eidassaml.starterkit.Utils.java

/**
 * /* w  w  w.jav a2  s  .c  o  m*/
 * @param is
 * @return
 * @throws IOException
 * @throws CertificateException
 */
public static X509Certificate readX509Certificate(InputStream is) throws IOException, CertificateException {
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    return (X509Certificate) certFactory.generateCertificate(is);
}

From source file:be.fgov.kszbcss.rhq.websphere.connector.agent.ConnectorSubsystemComponent.java

public OperationResult invokeOperation(String name, Configuration parameters)
        throws InterruptedException, Exception {
    if (name.equals("importCertificateFromFile")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream in = new FileInputStream(parameters.getSimple("file").getStringValue());
        try {//from   w  w w .j  av a  2 s. c  om
            Iterator<? extends Certificate> it = cf.generateCertificates(in).iterator();
            if (it.hasNext()) {
                TrustStoreManager.getInstance().addCertificate(parameters.getSimple("alias").getStringValue(),
                        (X509Certificate) it.next());
            } else {
                throw new Exception("No certificate found");
            }
        } finally {
            in.close();
        }
        return null;
    } else if (name.equals("retrieveCellCertificate")) {
        DeploymentManager dm = new DeploymentManager(null, new ConfigurationBasedProcessLocator(parameters));
        String cell = dm.getCell();
        ConfigQueryExecutor configQueryExecutor = ConfigQueryServiceFactory.getInstance()
                .getConfigQueryExecutor(dm);
        try {
            X509Certificate cert = configQueryExecutor.query(CellRootCertificateQuery.INSTANCE);
            TrustStoreManager.getInstance().addCertificate("cell:" + cell, cert);
        } finally {
            configQueryExecutor.destroy();
        }
        return null;
    } else if (name.equals("retrieveCertificateFromPort")) {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(new KeyManager[0],
                new TrustManager[] {
                        new AutoImportTrustManager(parameters.getSimple("alias").getStringValue()) },
                new SecureRandom());
        SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket(
                parameters.getSimple("host").getStringValue(), parameters.getSimple("port").getIntegerValue());
        try {
            socket.startHandshake();
        } finally {
            socket.close();
        }
        return null;
    } else if (name.equals("listCertificates")) {
        final PropertyList certificates = new PropertyList("certificates");
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                // Sort the aliases for convenience
                Set<String> aliases = new TreeSet<String>();
                for (Enumeration<String> e = truststore.aliases(); e.hasMoreElements();) {
                    aliases.add(e.nextElement());
                }
                for (String alias : aliases) {
                    X509Certificate cert = (X509Certificate) truststore.getCertificate(alias);
                    PropertyMap map = new PropertyMap("certificate");
                    map.put(new PropertySimple("alias", alias));
                    map.put(new PropertySimple("subject", cert.getSubjectDN().toString()));
                    MessageDigest md = MessageDigest.getInstance("SHA-1");
                    md.update(cert.getEncoded());
                    byte[] digest = md.digest();
                    StringBuilder fingerprint = new StringBuilder();
                    for (int i = 0; i < digest.length; i++) {
                        if (i > 0) {
                            fingerprint.append(':');
                        }
                        fingerprint.append(getHexDigit(((int) digest[i] & 0xf0) >> 4));
                        fingerprint.append(getHexDigit((int) digest[i] & 0x0f));
                    }
                    map.put(new PropertySimple("fingerprint", fingerprint.toString()));
                    certificates.add(map);
                }
            }
        }, true);
        if (log.isDebugEnabled()) {
            log.debug("certificates=" + certificates);
        }
        OperationResult result = new OperationResult();
        result.getComplexResults().put(certificates);
        return result;
    } else if (name.equals("removeCertificate")) {
        final String alias = parameters.getSimple("alias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                truststore.deleteEntry(alias);
            }
        }, false);
        return null;
    } else if (name.equals("renameCertificate")) {
        final String oldAlias = parameters.getSimple("oldAlias").getStringValue();
        final String newAlias = parameters.getSimple("newAlias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                Certificate cert = truststore.getCertificate(oldAlias);
                truststore.setCertificateEntry(newAlias, cert);
                truststore.deleteEntry(oldAlias);
            }
        }, false);
        return null;
    } else {
        return null;
    }
}

From source file:org.eclipse.che.ide.ext.datasource.server.ssl.KeyStoreObject.java

public void addNewKey(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception {
    PrivateKey privateKey = null;
    Certificate[] certs = null;//from  w  ww .ja v  a2  s.  c o  m
    while (uploadedFilesIterator.hasNext()) {
        FileItem fileItem = uploadedFilesIterator.next();
        if (!fileItem.isFormField()) {
            if ("keyFile".equals(fileItem.getFieldName())) {
                KeyFactory kf = KeyFactory.getInstance("RSA");
                privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(fileItem.get()));
            }
            if ("certFile".equals(fileItem.getFieldName())) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {});
            }
        }
    }

    if (privateKey == null || certs == null) {
        throw new WebApplicationException(
                Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build());
    }

    keystore.setKeyEntry(alias, privateKey, keyStorePassword.toCharArray(), certs);
    save();
}