Example usage for java.security.cert CertificateFactory generateCertificate

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

Introduction

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

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:se.tillvaxtverket.ttsigvalws.ttwssigvalidation.pdf.PdfSignatureVerifier.java

License:asdf

/**
 * converts an X509CertificateHolder object to an X509Certificate object.
 *
 * @param certHolder the cert holder object
 * @return X509Certificate object//from w w w  . ja va 2  s.  c  o m
 * @throws IOException
 * @throws CertificateException
 */
public static X509Certificate getCert(X509CertificateHolder certHolder)
        throws IOException, CertificateException {
    X509Certificate cert = null;
    ByteArrayInputStream certIs = new ByteArrayInputStream(certHolder.getEncoded());

    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(certIs);

    } finally {
        certIs.close();
    }

    return cert;
}

From source file:Main.java

/**
 * Creates <code>TrustAnchor</code> instance
 * constructed using self signed test certificate
 *
 * @return <code>TrustAnchor</code> instance
 *///  w ww . j a  va 2 s .  c  o  m
public static TrustAnchor getTrustAnchor() {
    CertificateFactory cf = null;
    try {
        cf = CertificateFactory.getInstance(certType);
    } catch (CertificateException e) {
        // requested cert type is not available in the
        // default provider package or any of the other provider packages
        // that were searched
        throw new RuntimeException(e);
    }
    BufferedInputStream bis = null;
    try {
        bis = new BufferedInputStream(new ByteArrayInputStream(getEncodedX509Certificate()));
        X509Certificate c1 = (X509Certificate) cf.generateCertificate(bis);

        return new TrustAnchor(c1, null);
    } catch (Exception e) {
        // all failures are fatal
        throw new RuntimeException(e);
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ign) {
            }
        }
    }
}

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

public static X509Certificate loadDERCertificate(final String filePath)
        throws IOException, CertificateException {
    FileInputStream certificateFileInputStream = null;
    try {//from w  ww . j  ava 2 s .com
        File certFile = new File(filePath);
        if (!certFile.exists()) {
            // try loading it from the classpath
            URL localCertFile = PKSigningUtil.class.getClassLoader().getResource(filePath);
            if (localCertFile == null) {
                throw new FileNotFoundException("File at " + filePath + " not found");
            }
            certFile = new File(localCertFile.getFile());
        }
        certificateFileInputStream = new FileInputStream(certFile);

        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509",
                BouncyCastleProvider.PROVIDER_NAME);
        Certificate certificate = certificateFactory.generateCertificate(certificateFileInputStream);
        if (certificate instanceof X509Certificate) {
            return (X509Certificate) certificate;
        }
        throw new IOException("The key from '" + filePath + "' could not be decrypted");
    } catch (IOException ex) {
        throw new IOException("The key from '" + filePath + "' could not be decrypted", ex);
    } catch (NoSuchProviderException ex) {
        throw new IOException("The key from '" + filePath + "' could not be decrypted", ex);
    } finally {
        IOUtils.closeQuietly(certificateFileInputStream);
    }
}

From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java

static X509Certificate loadLicenseCaCertificate() throws CertificateException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream stream = CloudBeesUpdateSite.class.getResourceAsStream("/cloudbees-root-cacert.pem");
    try {/*from w  w  w  .j  a va2 s . c o m*/
        return stream != null ? (X509Certificate) cf.generateCertificate(stream) : null;
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.apache.atlas.web.filters.AtlasKnoxSSOAuthenticationFilter.java

public static RSAPublicKey parseRSAPublicKey(String pem)
        throws CertificateException, UnsupportedEncodingException, ServletException {
    String PEM_HEADER = "-----BEGIN CERTIFICATE-----\n";
    String PEM_FOOTER = "\n-----END CERTIFICATE-----";
    String fullPem = PEM_HEADER + pem + PEM_FOOTER;
    PublicKey key = null;/*w w  w  . jav  a 2  s.  com*/
    try {
        CertificateFactory fact = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream is = new ByteArrayInputStream(fullPem.getBytes("UTF8"));
        X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
        key = cer.getPublicKey();
    } catch (CertificateException ce) {
        String message = null;
        if (pem.startsWith(PEM_HEADER)) {
            message = "CertificateException - be sure not to include PEM header "
                    + "and footer in the PEM configuration element.";
        } else {
            message = "CertificateException - PEM may be corrupt";
        }
        throw new ServletException(message, ce);
    } catch (UnsupportedEncodingException uee) {
        throw new ServletException(uee);
    }
    return (RSAPublicKey) key;
}

From source file:com.zimbra.cs.service.mail.CreateContact.java

private static String parseCertificate(Element elt, String name, ZimbraSoapContext zsc, OperationContext octxt,
        Contact existing) throws ServiceException {
    String attachId = elt.getAttribute(MailConstants.A_ATTACHMENT_ID, null);
    String result = "";
    InputStream in = null;//w w w .j a  v  a 2s  . c  o m
    if (!Strings.isNullOrEmpty(attachId)) {
        Upload up = FileUploadServlet.fetchUpload(zsc.getAuthtokenAccountId(), attachId, zsc.getAuthToken());
        try {
            ZimbraLog.contact.debug("start processing contact certificate with aid=%s for account=%s", attachId,
                    zsc.getRequestedAccountId());
            in = up.getInputStream();
            byte[] certBytes = IOUtils.toByteArray(in);
            // Load the certificate using Keystore just to make sure it is a valid certificate file.
            // No other validation is done here.
            CertificateFactory factory = CertificateFactory.getInstance(SmimeConstants.PUB_CERT_TYPE);
            factory.generateCertificate(new ByteArrayInputStream(certBytes));
            result = ByteUtil.encodeLDAPBase64(certBytes);
        } catch (IOException | CertificateException e) {
            ZimbraLog.contact.error("Exception in adding user certificate with aid=%s for account %s", attachId,
                    zsc.getRequestedAccountId());
            throw ServiceException.INVALID_REQUEST("Exception in adding certificate", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    ZimbraLog.contact.error("Exception in closing inputstream for attachment", e);
                }
            }
        }
    }
    return result;
}

From source file:com.arm.connector.bridge.core.Utils.java

static public X509Certificate createX509CertificateFromPEM(ErrorLogger logger, String pem, String cert_type) {
    try {//w w w. j  a v  a 2 s.c  o  m
        String temp = Utils.escapeChars(pem);
        String certPEM = temp.replace("-----BEGIN CERTIFICATE-----", "");
        certPEM = certPEM.replace("-----END CERTIFICATE-----", "");

        // DEBUG
        //logger.info("createX509CertificateFromPEM: " + certPEM);

        Base64 b64 = new Base64();
        byte[] decoded = b64.decode(certPEM);

        CertificateFactory cf = CertificateFactory.getInstance(cert_type);
        return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(decoded));
    } catch (Exception ex) {
        // exception caught
        logger.warning("createX509CertificateFromPEM: Exception during private key gen", ex);
    }
    return null;
}

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

/**
 * X509??.//  ww w.  j a va 2  s .c  om
 * @param privateKeyFileName ???
 * @param certificateFileName ??
 * @param rootCertificateFileNames ??
 * @throws IOException IOException
 * @throws NoSuchAlgorithmException NoSuchAlgorithmException
 * @throws InvalidKeySpecException InvalidKeySpecException
 * @throws CertificateException CertificateException
 */
public static void configureX509(String privateKeyFileName, String certificateFileName,
        String[] rootCertificateFileNames)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {

    xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    // Read RootCA Certificate
    x509RootCertificateFileNames = new ArrayList<String>();
    if (rootCertificateFileNames != null) {
        for (String fileName : rootCertificateFileNames) {
            x509RootCertificateFileNames.add(fileName);
        }
    }

    // Read Private Key
    InputStream is = null;
    if (privateKeyFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH);
    } else {
        is = new FileInputStream(privateKeyFileName);
    }

    PEMReader privateKeyPemReader = new PEMReader(is);
    byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes();
    PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec());

    // Read Certificate
    if (certificateFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH);
    } else {
        is = new FileInputStream(certificateFileName);
    }
    PEMReader serverCertificatePemReader;
    serverCertificatePemReader = new PEMReader(is);
    byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes();
    CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE);
    x509Certificate = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert));

    // Create the KeyInfo containing the X509Data
    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    List x509Content = new ArrayList();
    x509Content.add(x509Certificate.getSubjectX500Principal().getName());
    x509Content.add(x509Certificate);
    X509Data xd = keyInfoFactory.newX509Data(x509Content);
    keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd));

    // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/

}

From source file:org.wso2.carbon.identity.relyingparty.saml.X509CredentialUtil.java

/**
 * Creates the certificate from the KeyInfo element.
 *//*from   w  w w  .ja v  a  2s .c o m*/
public static X509Credential loadCredentialFromSignature(Signature signature) throws RelyingPartyException {
    X509Credential credential = null;
    KeyInfo kinfo = signature.getKeyInfo();
    List<X509Data> dataList = null;
    List<KeyValue> keyValueList = null;

    if (kinfo == null) {
        return null;
    }

    try {
        dataList = kinfo.getX509Datas();
        keyValueList = kinfo.getKeyValues();

        if (dataList.size() > 0) {

            if (dataList.size() > 1) {
                throw new RelyingPartyException("invalidKeyValueCount");
            }

            X509Data data = dataList.get(0);
            List<X509Certificate> certList = data.getX509Certificates();
            Iterator<X509Certificate> certIterator = certList.iterator();

            while (certIterator.hasNext()) {
                X509Certificate certElem = null;
                String certValue = null;
                byte[] certInBytes = null;
                ByteArrayInputStream inputStream = null;
                CertificateFactory factory = null;
                java.security.cert.X509Certificate x509Cert = null;

                certElem = (X509Certificate) certIterator.next();
                certValue = certElem.getValue();
                certInBytes = Base64.decode(certValue);
                inputStream = new ByteArrayInputStream(certInBytes);
                factory = CertificateFactory.getInstance("X509");
                x509Cert = (java.security.cert.X509Certificate) factory.generateCertificate(inputStream);
                credential = new X509CredentialImpl(x509Cert);
            }
        } else if (keyValueList.size() > 0) {

            if (keyValueList.size() > 1) {
                throw new RelyingPartyException("invalidKeyValueCount");
            }

            KeyValue val = null;
            RSAKeyValue rsaKey = null;
            Element modElem = null;
            Element expElem = null;
            Element elem = null;
            OMElement omElem = null;
            BigInteger mod = null;
            BigInteger exp = null;

            val = (KeyValue) keyValueList.get(0);
            rsaKey = val.getRSAKeyValue();
            elem = rsaKey.getDOM();
            omElem = (OMElement) new OMDOMFactory().getDocument().importNode(elem, true);
            modElem = (Element) omElem.getFirstChildWithName(Modulus.DEFAULT_ELEMENT_NAME);
            expElem = (Element) omElem.getFirstChildWithName(Exponent.DEFAULT_ELEMENT_NAME);
            mod = Base64.decodeBigIntegerFromElement(modElem);

            if (expElem != null) {
                exp = Base64.decodeBigIntegerFromElement(expElem);
            } else {
                exp = DEFAULT_EXPONENET;
            }

            credential = new X509CredentialImpl(mod, exp);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("unknown key info");
            }
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        log.error("Error while loading credentials from signature", e);
        throw new RelyingPartyException("Error while loading credentials from signature", e);
    }

    return credential;
}

From source file:Main.java

private static TrustManager[] prepareTrustManager(InputStream... certificates) {
    if (certificates != null && certificates.length > 0) {
        try {/*from  w  w w .jav a  2s  . c  om*/
            CertificateFactory e = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load((KeyStore.LoadStoreParameter) null);
            int index = 0;
            InputStream[] trustManagerFactory = certificates;
            int trustManagers = certificates.length;

            for (int i$ = 0; i$ < trustManagers; ++i$) {
                InputStream certificate = trustManagerFactory[i$];
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, e.generateCertificate(certificate));

                try {
                    if (certificate != null) {
                        certificate.close();
                    }
                } catch (IOException var10) {
                    ;
                }
            }

            trustManagerFactory = null;
            TrustManagerFactory var15 = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            var15.init(keyStore);
            TrustManager[] var16 = var15.getTrustManagers();
            return var16;
        } catch (NoSuchAlgorithmException var11) {
            var11.printStackTrace();
        } catch (CertificateException var12) {
            var12.printStackTrace();
        } catch (KeyStoreException var13) {
            var13.printStackTrace();
        } catch (Exception var14) {
            var14.printStackTrace();
        }

        return null;
    } else {
        return null;
    }
}