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:be.solidx.hot.nio.http.SSLContextBuilder.java

private KeyManagerFactory handleClientKeyCertURLProvided(Map<String, Object> options)
        throws SSLContextInitializationException {

    InputStream keyInputStream = null;
    InputStream certInputStream = null;

    try {/*w  w  w.j  a v  a  2s  . c o m*/
        KeyManagerFactory keyManagerFactory = null;
        KeyStore keyStore = KeyStore.getInstance(JKS);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

        byte[] key = IOUtils.toByteArray(getInputStream(new URI(options.get(KEY).toString())));
        Certificate certCertificate = certificateFactory
                .generateCertificate(getInputStream(new URI(options.get(CERT).toString())));
        char[] password = options.get(PASSPHRASE).toString().toCharArray();

        keyStore.load(null, null);
        // No CA needed, just add pivate key and associated public key to a keystore
        keyStore.setKeyEntry(KEY, SSLUtils.toPrivateKey(new ByteArrayInputStream(key)), password,
                new Certificate[] { certCertificate });

        keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(keyStore, password);

        return keyManagerFactory;
    } catch (NullPointerException | UnrecoverableKeyException | KeyStoreException | CertificateException
            | NoSuchAlgorithmException | IOException | URISyntaxException | InvalidKeySpecException e) {
        throw new SSLContextInitializationException(e);
    } finally {
        if (keyInputStream != null) {
            try {
                keyInputStream.close();
            } catch (IOException e) {
            }
        }
        if (certInputStream != null) {
            try {
                certInputStream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.verisign.epp.serverstub.LaunchDomainHandler.java

/**
 * Loads the trust store file and the Certificate Revocation List (CRL) file
 * into the <code>PKIXParameters</code> used to verify the certificate chain
 * and verify the certificate against the CRL. Both the Java Trust Store is
 * loaded with the trusted root CA certificates (trust anchors) and the CRL
 * file is attempted to be loaded to identify the revoked certificates. If
 * the CRL file is not found, then no CRL checking will be done.
 * //from w  w w  .  ja v  a 2 s . c o  m
 * @param aTrustStoreName
 *            Trust store file name
 * @param aCrls
 *            List of Certificate Revocation List (CRL) file names
 * 
 * @return Initialized <code>PKIXParameters</code> instance.
 * 
 * @throws Exception
 *             Error initializing the PKIX parameters
 */
private PKIXParameters loadPKIXParameters(String aTrustStoreName, List<String> aCrls) throws Exception {
    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): enter");

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream trustStoreFile = new FileInputStream(aTrustStoreName);
    trustStore.load(trustStoreFile, null);
    trustStoreFile.close();
    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): truststore = " + aTrustStoreName);
    PKIXParameters pkixParameters = new PKIXParameters(trustStore);

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

    Collection crlContentsList = new ArrayList();

    for (String currCrl : aCrls) {
        File crlFile = new File(currCrl);
        if (crlFile.exists()) {
            InputStream inStream = null;

            try {
                cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): adding CRL " + currCrl);
                inStream = new FileInputStream(currCrl);
                crlContentsList.add(certFactory.generateCRL(inStream));
            } finally {
                if (inStream != null) {
                    inStream.close();
                }
            }
        } else {
            throw new EPPException("CRL file " + currCrl + " does not exist.");
        }

    }

    // At least 1 CRL was loaded
    if (crlContentsList.size() != 0) {

        List<CertStore> certStores = new ArrayList<CertStore>();
        certStores.add(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crlContentsList)));

        pkixParameters.setCertStores(certStores);
        pkixParameters.setRevocationEnabled(true);
        cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): Revocation enabled");
    } else {
        pkixParameters.setRevocationEnabled(false);
        cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): Revocation disabled");
    }

    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): exit");
    return pkixParameters;
}

From source file:be.fedict.trust.service.bean.TrustDomainServiceBean.java

private X509Certificate getCertificate(byte[] certificateBytes) throws CertificateException {

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
}

From source file:com.xiaomi.account.utils.SysHelper.java

private static String parseSignature(byte[] signature) {
    try {//from   w  w  w .j  ava  2s  .  c o  m
        return ((X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(signature))).getPublicKey().toString();
    } catch (CertificateException e) {
        Log.e(TAG, "Error when parseSignature ", e);
        return null;
    }
}

From source file:org.bankinterface.util.KeyStoreUtil.java

public static Certificate pemToCert(Reader r) throws IOException, CertificateException {
    String header = "-----BEGIN CERTIFICATE-----";
    String footer = "-----END CERTIFICATE-----";

    BufferedReader reader = new BufferedReader(r);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);

    String line;// ww w.ja va2  s .  c  o  m

    // ignore up to the header
    while ((line = reader.readLine()) != null && !line.equals(header)) {
    }

    // no header found
    if (line == null) {
        throw new IOException("Error reading certificate, missing BEGIN boundary");
    }

    // in between the header and footer is the actual certificate
    while ((line = reader.readLine()) != null && !line.equals(footer)) {
        line = line.replaceAll("\\s", "");
        ps.print(line);
    }

    // no footer found
    if (line == null) {
        throw new IOException("Error reading certificate, missing END boundary");
    }
    ps.close();

    // decode the buffer to a X509Certificate
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    byte[] certBytes = Base64.decodeBase64(baos.toByteArray());
    return cf.generateCertificate(new ByteArrayInputStream(certBytes));
}

From source file:at.alladin.rmbt.client.RMBTClient.java

public static SSLContext getSSLContext(final String caResource, final String certResource)
        throws NoSuchAlgorithmException, KeyManagementException {
    X509Certificate _ca = null;//from  www .  jav a 2 s  .  c om
    try {
        if (caResource != null) {
            final CertificateFactory cf = CertificateFactory.getInstance("X.509");
            _ca = (X509Certificate) cf
                    .generateCertificate(RMBTClient.class.getClassLoader().getResourceAsStream(caResource));
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }

    final X509Certificate ca = _ca;

    X509Certificate _cert = null;
    try {
        if (certResource != null) {
            final CertificateFactory cf = CertificateFactory.getInstance("X.509");
            _cert = (X509Certificate) cf
                    .generateCertificate(RMBTClient.class.getClassLoader().getResourceAsStream(certResource));
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
    final X509Certificate cert = _cert;

    // TrustManagerFactory tmf = null;
    // try
    // {
    // if (cert != null)
    // {
    // final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    // ks.load(null, null);
    // ks.setCertificateEntry("crt", cert);
    //
    // tmf =
    // TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    // tmf.init(ks);
    // }
    // }
    // catch (Exception e)
    // {
    // e.printStackTrace();
    // }

    final TrustManager tm;
    if (cert == null)
        tm = getTrustingManager();
    else
        tm = new javax.net.ssl.X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // System.out.println("getAcceptedIssuers");
                if (ca == null)
                    return new X509Certificate[] { cert };
                else
                    return new X509Certificate[] { ca };
            }

            public void checkClientTrusted(final X509Certificate[] certs, final String authType)
                    throws CertificateException {
                // System.out.println("checkClientTrusted: " +
                // Arrays.toString(certs) + " - " + authType);
            }

            public void checkServerTrusted(final X509Certificate[] certs, final String authType)
                    throws CertificateException {
                // System.out.println("checkServerTrusted: " +
                // Arrays.toString(certs) + " - " + authType);
                if (certs == null)
                    throw new CertificateException();
                for (final X509Certificate c : certs)
                    if (cert.equals(c))
                        return;
                throw new CertificateException();
            }
        };

    final TrustManager[] trustManagers = new TrustManager[] { tm };

    javax.net.ssl.SSLContext sc;
    sc = javax.net.ssl.SSLContext.getInstance(Config.RMBT_ENCRYPTION_STRING);

    sc.init(null, trustManagers, new java.security.SecureRandom());
    return sc;
}

From source file:com.alfaariss.oa.profile.aselect.ws.security.OACrypto.java

/**
 * Retrieve the singleton instance of the certificate factory. 
 * @see org.apache.ws.security.components.crypto.Crypto#getCertificateFactory()
 *//*from   w  w w . j a  v  a2  s  .  c om*/
public CertificateFactory getCertificateFactory() throws WSSecurityException {
    if (_certFactory == null) {
        try {
            Provider provider = _factory.getKeyStore().getProvider();
            String sProvider = null;
            if (provider != null) {
                sProvider = provider.getName();
            }
            if (sProvider == null || sProvider.length() == 0) {
                _certFactory = CertificateFactory.getInstance("X.509");
            } else {
                _certFactory = CertificateFactory.getInstance("X.509", provider);
            }
        } catch (CertificateException e) {
            throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "unsupportedCertType",
                    null, e);
        }
    }
    return _certFactory;
}

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

private void generateCertificate() {
    X500Name name = new X500Name(this.name);
    BigInteger serial = BigInteger.valueOf(1);
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo
            .getInstance(this.keyPair.getPublic().getEncoded());
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(name, serial,
            this.notBefore, this.notAfter, name, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter;
    try {//from www  .ja v a2s. c om
        asymmetricKeyParameter = PrivateKeyFactory.createKey(this.keyPair.getPrivate().getEncoded());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    ContentSigner contentSigner;
    try {
        contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKeyParameter);
    } catch (OperatorCreationException e) {
        throw new RuntimeException(e);
    }
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate;
    try {
        encodedCertificate = x509CertificateHolder.getEncoded();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    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(e);
    }
}

From source file:IntergrationTest.OCSPIntegrationTest.java

private X509Certificate getX509Certificate(byte[] bcert) throws CertificateException, IOException {
    if (bcert == null)
        return null;
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(bcert);
    X509Certificate x509cert = (X509Certificate) cf.generateCertificate(bais);
    bais.close();//w w w.  j  a va  2s .  co  m
    return x509cert;
}

From source file:hk.hku.cecid.edi.as2.admin.listener.PartnershipPageletAdaptor.java

/**
 * @param request//w  w  w .  ja  va  2  s  .  c  o m
 * @throws DAOException
 * @throws IOException
 */
private void updatePartnership(Hashtable ht, HttpServletRequest request, PropertyTree dom)
        throws DAOException, IOException {

    // get the parameters
    String requestAction = (String) ht.get("request_action");
    String partnershipId = (String) ht.get("partnership_id");
    String subject = (String) ht.get("subject");
    String recipientAddress = (String) ht.get("recipient_address");
    boolean isHostnameVerified = new Boolean((String) ht.get("is_hostname_verified")).booleanValue();
    String receiptAddress = (String) ht.get("receipt_address");
    boolean isSyncReply = new Boolean((String) ht.get("is_sync_reply")).booleanValue();
    boolean isReceiptRequested = new Boolean((String) ht.get("is_receipt_requested")).booleanValue();
    boolean isOutboundSignRequired = new Boolean((String) ht.get("is_outbound_sign_required")).booleanValue();
    boolean isOutboundEncryptRequired = new Boolean((String) ht.get("is_outbound_encrypt_required"))
            .booleanValue();
    boolean isOutboundCompressRequired = new Boolean((String) ht.get("is_outbound_compress_required"))
            .booleanValue();
    boolean isReceiptSignRequired = new Boolean((String) ht.get("is_receipt_sign_required")).booleanValue();
    boolean isInboundSignRequired = new Boolean((String) ht.get("is_inbound_sign_required")).booleanValue();
    boolean isInbouhndEncryptRequired = new Boolean((String) ht.get("is_inbound_encrypt_required"))
            .booleanValue();
    String signAlgorithm = (String) ht.get("sign_algorithm");
    String encryptAlgorithm = (String) ht.get("encrypt_algorithm");
    String micAlgorithm = (String) ht.get("mic_algorithm");
    String as2From = (String) ht.get("as2_from");
    String as2To = (String) ht.get("as2_to");
    String retries = (String) ht.get("retries");
    String retryInterval = (String) ht.get("retry_interval");
    boolean isDisabled = new Boolean((String) ht.get("disabled")).booleanValue();
    boolean hasEncryptCert = ht.get("encrypt_cert") != null;
    InputStream encryptCertInputStream = null;
    if (hasEncryptCert) {
        encryptCertInputStream = (InputStream) ht.get("encrypt_cert");
    }
    boolean hasRemoveEncryptCert = false;
    if (ht.get("encrypt_cert_remove") != null) {
        if (((String) ht.get("encrypt_cert_remove")).equalsIgnoreCase("on")) {
            hasRemoveEncryptCert = true;
        }
    }
    boolean hasVerifyCert = ht.get("verify_cert") != null;
    InputStream verifyCertInputStream = null;
    if (hasVerifyCert) {
        verifyCertInputStream = (InputStream) ht.get("verify_cert");
    }
    boolean hasRemoveVerifyCert = false;
    if (ht.get("verify_cert_remove") != null) {
        if (((String) ht.get("verify_cert_remove")).equalsIgnoreCase("on")) {
            hasRemoveVerifyCert = true;
        }
    }

    if ("add".equalsIgnoreCase(requestAction) || "update".equalsIgnoreCase(requestAction)
            || "delete".equalsIgnoreCase(requestAction)) {

        // validate and set to dao
        PartnershipDAO partnershipDAO = (PartnershipDAO) AS2PlusProcessor.getInstance().getDAOFactory()
                .createDAO(PartnershipDAO.class);
        PartnershipDVO partnershipDAOData = (PartnershipDVO) partnershipDAO.createDVO();

        partnershipDAOData.setPartnershipId(partnershipId);
        if ("update".equalsIgnoreCase(requestAction)) {
            partnershipDAO.retrieve(partnershipDAOData);
        }
        partnershipDAOData.setAs2From(as2From);
        partnershipDAOData.setAs2To(as2To);
        partnershipDAOData.setSubject(subject);
        partnershipDAOData.setRecipientAddress(recipientAddress);
        partnershipDAOData.setIsHostnameVerified(isHostnameVerified);
        partnershipDAOData.setReceiptAddress(receiptAddress);
        partnershipDAOData.setIsSyncReply(isSyncReply);
        partnershipDAOData.setIsReceiptRequired(isReceiptRequested);
        partnershipDAOData.setIsOutboundSignRequired(isOutboundSignRequired);
        partnershipDAOData.setIsOutboundEncryptRequired(isOutboundEncryptRequired);
        partnershipDAOData.setIsOutboundCompressRequired(isOutboundCompressRequired);
        partnershipDAOData.setIsReceiptSignRequired(isReceiptSignRequired);
        partnershipDAOData.setIsInboundSignRequired(isInboundSignRequired);
        partnershipDAOData.setIsInboundEncryptRequired(isInbouhndEncryptRequired);
        partnershipDAOData.setSignAlgorithm(signAlgorithm);
        partnershipDAOData.setEncryptAlgorithm(encryptAlgorithm);
        partnershipDAOData.setMicAlgorithm(micAlgorithm);
        partnershipDAOData.setIsDisabled(isDisabled);
        partnershipDAOData.setRetries(StringUtilities.parseInt(retries));
        partnershipDAOData.setRetryInterval(StringUtilities.parseInt(retryInterval));

        if ("add".equalsIgnoreCase(requestAction)) {
            getPartnership(partnershipDAOData, dom, "add_partnership/");
        }

        if (partnershipId.equals("")) {
            request.setAttribute(ATTR_MESSAGE, "Partnership ID cannot be empty");
            return;
        }
        if (as2From.equals("")) {
            request.setAttribute(ATTR_MESSAGE, "AS2 From cannot be empty");
            return;
        }
        if (as2To.equals("")) {
            request.setAttribute(ATTR_MESSAGE, "AS2 To cannot be empty");
            return;
        }
        if (as2From.length() > 100) {
            request.setAttribute(ATTR_MESSAGE, "AS2 From cannot be longer than 100 characters.");
            return;
        }
        if (as2To.length() > 100) {
            request.setAttribute(ATTR_MESSAGE, "AS2 To cannot be longer than 100 characters.");
            return;
        }

        if (partnershipDAOData.getRetries() == Integer.MIN_VALUE) {
            request.setAttribute(ATTR_MESSAGE, "Retries must be integer");
            return;
        }
        if (partnershipDAOData.getRetryInterval() == Integer.MIN_VALUE) {
            request.setAttribute(ATTR_MESSAGE, "Retry Interval must be integer");
            return;
        }

        // encrypt cert
        if (hasRemoveEncryptCert) {
            partnershipDAOData.setEncryptCert(null);
        }
        if (hasEncryptCert) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOHandler.pipe(encryptCertInputStream, baos);
                CertificateFactory.getInstance("X.509")
                        .generateCertificate(new ByteArrayInputStream(baos.toByteArray()));
                partnershipDAOData.setEncryptCert(baos.toByteArray());
            } catch (Exception e) {
                request.setAttribute(ATTR_MESSAGE, "Uploaded encrypt cert is not an X.509 cert");
                return;
            }
        }
        // verify cert
        if (hasRemoveVerifyCert) {
            partnershipDAOData.setVerifyCert(null);
        }
        if (hasVerifyCert) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOHandler.pipe(verifyCertInputStream, baos);
                CertificateFactory.getInstance("X.509")
                        .generateCertificate(new ByteArrayInputStream(baos.toByteArray()));
                partnershipDAOData.setVerifyCert(baos.toByteArray());
            } catch (Exception e) {
                request.setAttribute(ATTR_MESSAGE, "Uploaded verify cert is not an X.509 cert");
                return;
            }
        }

        // check partnership conflict
        if (!partnershipDAOData.isDisabled()) {
            Iterator allConflictDAOData = partnershipDAO
                    .findPartnershipsByPartyID(partnershipDAOData.getAS2From(), partnershipDAOData.getAs2To())
                    .iterator();
            while (allConflictDAOData.hasNext()) {
                PartnershipDVO conflictDAOData = (PartnershipDVO) allConflictDAOData.next();
                if (conflictDAOData != null
                        && !conflictDAOData.getPartnershipId().equals(partnershipDAOData.getPartnershipId())
                        && !conflictDAOData.isDisabled()) {
                    request.setAttribute(ATTR_MESSAGE, "Partnership '" + conflictDAOData.getPartnershipId()
                            + "' with same From/To party IDs has already been enabled");
                    return;
                }
            }
        }

        // dao action
        if ("add".equalsIgnoreCase(requestAction)) {

            partnershipDAO.create(partnershipDAOData);
            request.setAttribute(ATTR_MESSAGE, "Partnership added successfully");
            dom.removeProperty("/partnerships/add_partnership");
            dom.setProperty("/partnerships/add_partnership", "");
        }
        if ("update".equalsIgnoreCase(requestAction)) {
            partnershipDAO.persist(partnershipDAOData);
            request.setAttribute(ATTR_MESSAGE, "Partnership updated successfully");
        }
        if ("delete".equalsIgnoreCase(requestAction)) {
            partnershipDAO.remove(partnershipDAOData);
            request.setAttribute(ATTR_MESSAGE, "Partnership deleted successfully");
        }
    }
}