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:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegate.java

private X509Certificate getCertificateFromRequest(Object requestObject) throws CertificateException {
    UseKeyType useKeyType = extractType(requestObject, UseKeyType.class);
    byte[] x509 = null;
    if (null != useKeyType) {
        KeyInfoType keyInfoType = extractType(useKeyType.getAny(), KeyInfoType.class);
        if (null != keyInfoType) {
            for (Object keyInfoContent : keyInfoType.getContent()) {
                X509DataType x509DataType = extractType(keyInfoContent, X509DataType.class);
                if (null != x509DataType) {
                    for (Object x509Object : x509DataType.getX509IssuerSerialOrX509SKIOrX509SubjectName()) {
                        x509 = extractType(x509Object, byte[].class);
                        if (null != x509) {
                            break;
                        }/* w ww . j ava2 s. co m*/
                    }
                }
            }
        } else {
            Element elementNSImpl = (Element) useKeyType.getAny();
            NodeList x509CertData = elementNSImpl.getElementsByTagNameNS(Constants.SignatureSpecNS,
                    Constants._TAG_X509CERTIFICATE);
            if (x509CertData != null && x509CertData.getLength() > 0) {
                x509 = Base64.decodeBase64(x509CertData.item(0).getTextContent().getBytes());
            }
        }
        if (x509 != null) {
            CertificateFactory cf = CertificateFactory.getInstance(X_509);
            Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(x509));
            X509Certificate x509Cert = (X509Certificate) certificate;
            return x509Cert;
        }

    }
    return null;
}

From source file:org.apache.cloudstack.network.ssl.CertServiceImpl.java

private Certificate readCertificateFromPemObject(final PemObject pemObject) throws CertificateException {
    Preconditions.checkNotNull(pemObject);
    final ByteArrayInputStream bais = new ByteArrayInputStream(pemObject.getContent());
    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");

    return certificateFactory.generateCertificate(bais);
}

From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java

private KeyStore createKeyStore(KeyPair keyPair, HttpResponse response) throws Exception {
    Log.i("registration", "Got status from registration server: " + response.getStatusLine());

    HttpEntity entity = response.getEntity();
    byte[] contents = getBytes(entity.getContent());
    Collection<?> certs = extractCerts(contents);
    Certificate[] certificates = new Certificate[certs.size()];
    Log.i("registration", "Extracted out " + certs.size() + " certs");

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    Iterator<?> it = certs.iterator();
    int i = 0;/*from ww  w  .ja  v  a 2 s  . c  o  m*/
    while (it.hasNext()) {
        byte[] encoded = ((X509CertificateHolder) it.next()).getEncoded();
        certificates[i++] = (X509Certificate) certFactory
                .generateCertificate(new ByteArrayInputStream(encoded));
    }

    Log.d("registration", "Creating local keystore");
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setKeyEntry("Cert", keyPair.getPrivate(), "changeit".toCharArray(), certificates);

    return keyStore;
}

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

private void getCertificateForPartnership(byte[] cert, PropertyTree dom, String prefix) {
    if (cert != null) {
        try {/*from  ww  w .  j av  a  2s.  co m*/
            ByteArrayInputStream bais = new ByteArrayInputStream(cert);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate verifyCert = (X509Certificate) cf.generateCertificate(bais);
            bais.close();
            dom.setProperty(prefix + "issuer", verifyCert.getIssuerDN().getName());
            dom.setProperty(prefix + "subject", verifyCert.getSubjectDN().getName());
            dom.setProperty(prefix + "thumbprint", getCertFingerPrint(verifyCert));
            dom.setProperty(prefix + "valid-from", StringUtilities.toGMTString(verifyCert.getNotBefore()));
            dom.setProperty(prefix + "valid-to", StringUtilities.toGMTString(verifyCert.getNotAfter()));
        } catch (Exception e) {
            dom.setProperty(prefix + "Error", e.toString());
        }
    } else {
        dom.setProperty(prefix, "");
    }
}

From source file:be.fedict.eid.idp.admin.webapp.bean.ConfigBean.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.amazonaws.ipnreturnurlvalidation.SignatureUtilsForOutbound.java

/**
 * Verifies the signature using PKI.//www.java  2s  .c  o m
 */
private boolean validateSignatureV2(Map<String, String> parameters, String urlEndPoint, String httpMethod)
        throws SignatureException {

    // 1. input validation.
    String signature = parameters.get(SIGNATURE_KEYNAME);
    if (signature == null) {
        throw new SignatureException("'signature' is missing from the parameters.");
    }

    String signatureMethod = parameters.get(SIGNATURE_METHOD_KEYNAME);
    if (signatureMethod == null) {
        throw new SignatureException("'signatureMethod' is missing from the parameters.");
    }

    String signatureAlgorithm = getSignatureAlgorithm(signatureMethod);
    if (signatureAlgorithm == null) {
        throw new SignatureException("'signatureMethod' present in parameters is invalid. "
                + "Valid signatureMethods are : 'RSA-SHA1'");
    }

    String certificateUrl = parameters.get(CERTIFICATE_URL_KEYNAME);
    if (certificateUrl == null) {
        throw new SignatureException("'certificateUrl' is missing from the parameters.");
    }

    String certificate = getPublicKeyCertificateAsString(certificateUrl);
    if (certificate == null) {
        throw new SignatureException("public key certificate could not fetched from url: " + certificateUrl);
    }

    // 2. calculating the string to sign
    String stringToSign = EMPTY_STRING;
    try {
        URL url = new URL(urlEndPoint);
        String hostHeader = getHostHeader(url);
        String requestURI = getRequestURI(url);
        stringToSign = calculateStringToSignV2(parameters, httpMethod, hostHeader, requestURI);
    } catch (MalformedURLException e) {
        throw new SignatureException(e);
    }

    // 3. verify signature
    try {
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate x509Certificate = (X509Certificate) factory
                .generateCertificate(new ByteArrayInputStream(certificate.getBytes()));
        Signature signatureInstance = Signature.getInstance(signatureAlgorithm);
        signatureInstance.initVerify(x509Certificate.getPublicKey());
        signatureInstance.update(stringToSign.getBytes(UTF_8_Encoding));
        return signatureInstance.verify(Base64.decodeBase64(signature.getBytes()));
    } catch (CertificateException e) {
        throw new SignatureException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(e);
    } catch (InvalidKeyException e) {
        throw new SignatureException(e);
    } catch (UnsupportedEncodingException e) {
        throw new SignatureException(e);
    }
}

From source file:org.apache.cxf.fediz.service.idp.protocols.TrustedIdpSAMLProtocolHandler.java

private Crypto getCrypto(String certificate) throws ProcessingException {
    if (certificate == null) {
        return null;
    }/*from  www  .j a  v a  2 s  .co m*/

    // First see if it's a certificate file
    InputStream is = null;
    try {
        is = Merlin.loadInputStream(Thread.currentThread().getContextClassLoader(), certificate);

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is);
        return new CertificateStore(new X509Certificate[] { cert });
    } catch (WSSecurityException ex) {
        LOG.error("Failed to load keystore " + certificate, ex);
        throw new RuntimeException("Failed to load keystore " + certificate);
    } catch (IOException ex) {
        LOG.error("Failed to read keystore", ex);
        throw new RuntimeException("Failed to read keystore");
    } catch (CertificateException ex) {
        // This is ok as it could be a WSS4J properties file
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // Do nothing
            }
        }
    }

    // Maybe it's a WSS4J properties file...
    return CertsUtils.createCrypto(certificate);
}

From source file:pl.psnc.synat.wrdz.realm.db.WrdzUserDatabaseHandler.java

/**
 * Authenticates user using certificate he provided and comparing it to the data in the user database.
 * /* ww w. j av a 2s.  co  m*/
 * @param x509Certificate
 *            certificate of the user who is to be authenticated.
 * @return whether or not user data is valid (passed user data matches data in the database).
 */
public boolean isUserValid(X509Certificate x509Certificate) {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet rs = null;
    boolean valid = false;
    String username = findUsername(x509Certificate);
    try {
        connection = getConnection();
        statement = connection.prepareStatement(certificateQuery);
        statement.setString(1, username);
        rs = statement.executeQuery();
        if (rs.next()) {
            X509Certificate certificateFromDB = null;
            try {
                CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                certificateFromDB = (X509Certificate) certFactory
                        .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(rs.getString(1))));
            } catch (CertificateException e) {
                logger.log(Level.SEVERE, "Wrong certificate format or data corrupt.", e);
                return false;
            }
            if (certificateFromDB.equals(x509Certificate)) {
                valid = true;
            }
        }
    } catch (SQLException ex) {
        logger.log(Level.SEVERE, "Cannot validate user " + username + ", exception: " + ex.toString());
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "Cannot validate user", ex);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Invalid user " + username);
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "Cannot validate user", ex);
        }
    } finally {
        close(connection, statement, rs);
    }
    return valid;
}

From source file:be.fedict.eidviewer.lib.file.Version4XMLFileCertificates.java

public List<X509Certificate> toRRNChain() throws CertificateException {
    CertificateFactory certificateFactory = null;
    X509Certificate rootCert = null;
    X509Certificate rrnCert = null;
    List<X509Certificate> rrnChain = null;

    if (getRootCertificate() == null || getRRNCertificate() == null)
        return null;

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

    rootCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getRootCertificate().getBytes())));
    rrnCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(getRRNCertificate().getBytes())));

    rrnChain = new LinkedList<X509Certificate>();
    rrnChain.add(rrnCert);/*from w  w w . j ava  2 s . co m*/
    rrnChain.add(rootCert);

    return rrnChain;
}

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 .ja va2  s.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) {
            }
        }
    }
}