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:ee.sk.hwcrypto.demo.controller.SigningController.java

@RequestMapping(value = "/identify", method = RequestMethod.POST)
public Digest identifyUser(@RequestParam String certificate) {
    Digest digest = new Digest();
    try {//from w ww . j a va 2s  .c  o  m
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        byte[] bytes = Base64.decode(certificate);
        InputStream stream = new ByteArrayInputStream(bytes);
        X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
        cert.checkValidity();
        digest.setHex(cert.getSubjectDN().getName());
        digest.setResult(Result.OK);
        //TODO create session for user cert.getSubjectDN().getName()
        return digest;
    } catch (Exception e) {
        log.error("Error identify ", e);
        digest.setResult(Result.ERROR);
    }
    return digest;
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

public static Credential getKeyCredential(SAMLEngineModuleI module, KeyInfo keyInfo)
        throws SAMLEngineException {
    Credential credential;// w ww  .j  a  va  2s  .c o  m
    try {
        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        final CertificateFactory certFact = CertificateFactory.getInstance("X.509");
        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));
        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        credential = new BasicX509Credential();
        ((BasicX509Credential) credential).setEntityCertificate(cert);
        if (module != null) {
            module.checkCertificateIssuer(cert);
            module.checkCertificateValidityPeriod(cert);
        }
    } catch (CertificateException ce) {
        throw new SAMLEngineException(EIDASErrors.SAML_ENGINE_INVALID_CERTIFICATE.errorCode(),
                EIDASErrors.SAML_ENGINE_INVALID_CERTIFICATE.errorMessage(), ce);
    }
    return credential;
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

/**
 * Get a public key from a certificate./*from  w w w  . j  a v a  2  s. com*/
 * @param certPath
 * @return
 * @throws Exception
 */
public PublicKey readPublicKeyFromCertificate(String certPath) throws Exception {
    FileInputStream fin = new FileInputStream(certPath);
    CertificateFactory f = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) f.generateCertificate(fin);
    return certificate.getPublicKey();
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
 * validates a metadata entitydescriptor's signature against a trustkeystore
 * @param ed//w  w  w.  j  a v a 2s .  c  o  m
 * @param trustKeyStore
 * @throws SAMLEngineException
 */
public static void validateEntityDescriptorSignature(SignableXMLObject ed, KeyStore trustKeyStore)
        throws SAMLEngineException {
    if (ed == null) {
        throw new SAMLEngineException("invalid entity descriptor");
    }
    try {
        SAMLSignatureProfileValidator sigProfValidator = new SAMLSignatureProfileValidator();
        org.opensaml.xml.signature.Signature signature = ed.getSignature();
        sigProfValidator.validate(signature);
        //check that EntityDescriptor matches the signature
        final KeyInfo keyInfo = ed.getSignature().getKeyInfo();

        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        final CertificateFactory certFact = CertificateFactory.getInstance("X.509");
        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));
        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        final BasicX509Credential entityX509Cred = new BasicX509Credential();
        entityX509Cred.setEntityCertificate(cert);
        final SignatureValidator sigValidator = new SignatureValidator(entityX509Cred);
        sigValidator.validate(signature);
        if (trustKeyStore != null) {
            SAMLEngineUtils.checkTrust(entityX509Cred, trustKeyStore);
        }
    } catch (ValidationException exc) {
        throw new SAMLEngineException(EIDASErrors.INVALID_SIGNATURE_ALGORITHM.errorCode(), exc);
    } catch (CertificateException exc) {
        throw new SAMLEngineException(EIDASErrors.INVALID_SIGNATURE_ALGORITHM.errorCode(), exc);
    }

}

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();/*from  w  w  w.j a  va 2 s  . com*/
    return x509cert;
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 * Parses a X.509 certificate from a PEM certificate string
 *
 * @param certString/*  ww w .java 2s .  c  om*/
 * @return
 * @throws CertificateException
 */
public X509Certificate parseCertificate(String certString) throws CertificateException {
    CertificateFactory fac = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream stream = new ByteArrayInputStream(certString.getBytes());
    Certificate cert = fac.generateCertificate(stream);
    if (cert instanceof X509Certificate) {
        return (X509Certificate) cert;
    } else {
        throw new IllegalArgumentException("Provided certificate did not parse as a X509 certificate");
    }
}

From source file:be.solidx.hot.nio.http.SSLContextBuilder.java

private TrustManager[] handleTrustManagers(Map<String, Object> options)
        throws CertificateException, IOException, URISyntaxException {
    boolean rejectUnauthorized = (boolean) options.get(REJECTUNAUTHORIZED);
    if (options.get(CA) != null) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        return new TrustManager[] { new TrustManager(
                (X509Certificate) certificateFactory
                        .generateCertificate(getInputStream(new URI(options.get(CA).toString()))),
                rejectUnauthorized) };//from  w  w w .  j a v  a  2s.  co  m
    } else if (!rejectUnauthorized) {
        return new TrustManager[] { new TrustManager(null, rejectUnauthorized) };
    }
    return null;
}

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsWithCertificate(final URL url) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);// Make an empty store

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

    FileInputStream fis = new FileInputStream(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH);
    BufferedInputStream bis = new BufferedInputStream(fis);
    while (bis.available() > 0) {
        Certificate cert = cf.generateCertificate(bis);
        // System.out.println(cert.getPublicKey().toString());
        trustStore.setCertificateEntry("jetty" + bis.available(), cert);
    }/*www . ja  v  a  2s  .com*/

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory sslFactory = ctx.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if (0 == hostname.compareToIgnoreCase(url.getHost())) {
                return true;
            }
            return false;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslFactory);

    return urlConnection.getInputStream();
}

From source file:org.apache.airavata.credential.store.server.CredentialStoreServerHandler.java

@Override
public String addCertificateCredential(CertificateCredential certificateCredential)
        throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException {
    try {/*from   w ww  .j  a  v a2s  . com*/
        org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential credential = new org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential();
        credential.setPortalUserName(certificateCredential.getCommunityUser().getUsername());
        credential.setCommunityUser(new CommunityUser(certificateCredential.getCommunityUser().getGatewayName(),
                certificateCredential.getCommunityUser().getUsername(),
                certificateCredential.getCommunityUser().getUserEmail()));
        String token = TokenGenerator.generateToken(certificateCredential.getCommunityUser().getGatewayName(),
                null);
        credential.setToken(token);
        Base64 encoder = new Base64(64);
        byte[] decoded = encoder.decode(certificateCredential.getX509Cert()
                .replaceAll(X509Factory.BEGIN_CERT, "").replaceAll(X509Factory.END_CERT, ""));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) cf
                .generateCertificate(new ByteArrayInputStream(decoded));
        X509Certificate[] certificates = new X509Certificate[1];
        certificates[0] = certificate;
        credential.setCertificates(certificates);
        certificateCredentialWriter.writeCredentials(credential);
        return token;
    } catch (CredentialStoreException e) {
        log.error("Error occurred while saving Certificate Credentials.", e);
        throw new org.apache.airavata.credential.store.exception.CredentialStoreException(
                "Error occurred while saving Certificate Credentials.");
    } catch (Exception e) {
        log.error("Error occurred while converting to X509 certificate.", e);
        throw new org.apache.airavata.credential.store.exception.CredentialStoreException(
                "Error occurred while converting to X509 certificate..");
    }
}