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.fedict.eidviewer.lib.file.imports.EidQuickKeyXMLFile.java

public void load(File file) throws CertificateException, FileNotFoundException, SAXException, IOException {
    logger.fine("Loading eID Quick Keys XML File");

    XMLReader reader = null;//from ww  w .  j a v a2s.  co  m

    certificateFactory = CertificateFactory.getInstance("X.509");
    FileInputStream fis = new FileInputStream(file);

    reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(this);
    reader.setErrorHandler(this);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));
    reader.parse(new InputSource(in));

    X509Utilities.setCertificateChainsFromCertificates(eidData, rootCert, citizenCert, authenticationCert,
            signingCert, rrnCert);
}

From source file:com.cedarsoft.crypt.CertTest.java

@Test
public void testCert() throws Exception {
    DataInputStream inStream = new DataInputStream(getClass().getResource("/test.crt").openStream());

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
    inStream.close();/*  w  w  w.java 2  s  .c om*/
    assertNotNull(cert);

    cert.checkValidity();

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, cert);

    byte[] clear = cipher.doFinal(Base64.decodeBase64(SCRAMBLED.getBytes()));
    assertEquals(PLAINTEXT, new String(clear));
}

From source file:com.sk89q.mclauncher.security.X509KeyStore.java

/**
 * Add root certificates from an input stream.
 * /* w w  w .ja  v  a  2 s .com*/
 * @param in
 *            input
 * @throws CertificateException
 *             on error
 * @throws IOException
 *             on I/O error
 */
public void addIntermediateCertificate(InputStream in) throws CertificateException, IOException {
    try {
        BufferedInputStream bufferedIn = new BufferedInputStream(in);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        while (bufferedIn.available() > 0) {
            Certificate cert = cf.generateCertificate(bufferedIn);
            addIntermediateCertificate((X509Certificate) cert);
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateJWTConfig.java

/**
 * The public key used to verify the signatures of JWT tokens.
 *
 * @param keyValue The string of the public key to use in either RSA or X.509 format
 * @return A public key object to use when validating JWT tokens
 * @throws IOException             On reading or closing byte array input stream
 * @throws JoseException           When trying to create the key using jose library
 * @throws InvalidKeySpecException When the cert has an invalid spec
 * @throws CertificateException    When trying to create a X.509 specification object
 *//*from  w  w w . j  a  v  a  2 s.com*/
@Bean
public PublicKey jwtPublicKey(
        @Value("${genie.security.oauth2.pingfederate.jwt.keyValue}") final String keyValue)
        throws IOException, JoseException, InvalidKeySpecException, CertificateException {
    final String certBegin = "-----BEGIN CERTIFICATE-----";
    final String rsaBegin = "-----BEGIN PUBLIC KEY-----";
    if (StringUtils.isEmpty(keyValue)) {
        // In future try a key resolver to pull the key from the server
        throw new IllegalArgumentException("No value set for security.oauth2.resource.jwt.keyValue");
    }

    if (keyValue.startsWith(certBegin)) {
        // X.509 cert
        try (final ByteArrayInputStream bis = new ByteArrayInputStream(keyValue.getBytes("UTF-8"))) {
            final CertificateFactory fact = CertificateFactory.getInstance("X.509");
            final X509Certificate cer = (X509Certificate) fact.generateCertificate(bis);
            return cer.getPublicKey();
        }
    } else if (keyValue.startsWith(rsaBegin)) {
        // RSA Public Key
        return new RsaKeyUtil().fromPemEncoded(keyValue);
    } else {
        throw new IllegalArgumentException(
                "Only support X.509 pem certs or Public RSA Keys for security.oauth2.resource.jwt.keyValue");
    }
}

From source file:be.fedict.trust.client.ServerCrypto.java

public X509Certificate loadCertificate(InputStream in) throws WSSecurityException {
    LOG.debug("loadCertificate");
    CertificateFactory certificateFactory;
    try {/*from  w  w  w  . j ava2  s. c o m*/
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new WSSecurityException("X509 algo", e);
    }
    X509Certificate certificate;
    try {
        certificate = (X509Certificate) certificateFactory.generateCertificate(in);
    } catch (CertificateException e) {
        throw new WSSecurityException("X509 error: " + e.getMessage(), e);
    }
    if (null == this.certificate) {
        LOG.debug("trusting incoming certificate as is");
        this.certificate = certificate;
    }
    return certificate;
}

From source file:com.netflix.genie.security.oauth2.pingfederate.PingFederateJWTConfig.java

/**
 * The public key used to verify the signatures of JWT tokens.
 *
 * @param keyValue The string of the public key to use in either RSA or X.509 format
 * @return A public key object to use when validating JWT tokens
 * @throws IOException             On reading or closing byte array input stream
 * @throws JoseException           When trying to create the key using jose library
 * @throws InvalidKeySpecException When the cert has an invalid spec
 * @throws CertificateException    When trying to create a X.509 specification object
 *//*from  w  w  w. j a  va 2 s.  c  o m*/
@Bean
public PublicKey jwtPublicKey(
        @Value("${genie.security.oauth2.pingfederate.jwt.keyValue}") final String keyValue)
        throws IOException, JoseException, InvalidKeySpecException, CertificateException {
    final String certBegin = "-----BEGIN CERTIFICATE-----";
    final String rsaBegin = "-----BEGIN PUBLIC KEY-----";
    if (StringUtils.isEmpty(keyValue)) {
        // In future try a key resolver to pull the key from the server
        throw new IllegalArgumentException("No value set for security.oauth2.resource.jwt.keyValue");
    }

    if (keyValue.startsWith(certBegin)) {
        // X.509 cert
        try (ByteArrayInputStream bis = new ByteArrayInputStream(keyValue.getBytes("UTF-8"))) {
            final CertificateFactory fact = CertificateFactory.getInstance("X.509");
            final X509Certificate cer = (X509Certificate) fact.generateCertificate(bis);
            return cer.getPublicKey();
        }
    } else if (keyValue.startsWith(rsaBegin)) {
        // RSA Public Key
        return new RsaKeyUtil().fromPemEncoded(keyValue);
    } else {
        throw new IllegalArgumentException(
                "Only support X.509 pem certs or Public RSA Keys for security.oauth2.resource.jwt.keyValue");
    }
}

From source file:nl.surfnet.spring.security.opensaml.util.KeyStoreUtil.java

/**
 * Append a certificate to the given key store
 * @param keyStore/* w ww .j ava 2  s.  c om*/
 * @param keyAlias
 * @param pemCert
 */
public static void appendCertificateToKeyStore(KeyStore keyStore, String keyAlias, String pemCert) {
    String wrappedCert = "-----BEGIN CERTIFICATE-----\n" + pemCert + "\n-----END CERTIFICATE-----";
    ByteArrayInputStream certificateInputStream = new ByteArrayInputStream(wrappedCert.getBytes());
    try {
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        final Certificate cert = certificateFactory.generateCertificate(certificateInputStream);
        IOUtils.closeQuietly(certificateInputStream);
        keyStore.setCertificateEntry(keyAlias, cert);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cloud.utils.security.CertificateHelper.java

public static Certificate buildCertificate(String content) throws CertificateException {
    assert (content != null);

    BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content.getBytes()));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    return cf.generateCertificate(bis);
}

From source file:org.josso.auth.scheme.validation.CRLX509CertificateValidator.java

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {/*from  w w w.j a  v  a 2  s  . c  o m*/
        URL crlUrl = null;
        if (_url != null) {
            crlUrl = new URL(_url);
            log.debug("Using the CRL server at: " + _url);
        } else {
            log.debug("Using the CRL server specified in the certificate.");
            System.setProperty("com.sun.security.enableCRLDP", "true");
        }

        // configure the proxy
        if (_httpProxyHost != null && _httpProxyPort != null) {
            System.setProperty("http.proxyHost", _httpProxyHost);
            System.setProperty("http.proxyPort", _httpProxyPort);
        } else {
            System.clearProperty("http.proxyHost");
            System.clearProperty("http.proxyPort");
        }

        // get certificate path
        CertPath cp = generateCertificatePath(certificate);

        // get trust anchors
        Set<TrustAnchor> trustedCertsSet = generateTrustAnchors();

        // init PKIX parameters
        PKIXParameters params = new PKIXParameters(trustedCertsSet);

        // activate certificate revocation checking
        params.setRevocationEnabled(true);

        // disable OCSP
        Security.setProperty("ocsp.enable", "false");

        // get a certificate revocation list
        if (crlUrl != null) {
            URLConnection connection = crlUrl.openConnection();
            connection.setDoInput(true);
            connection.setUseCaches(false);
            DataInputStream inStream = new DataInputStream(connection.getInputStream());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509CRL crl = (X509CRL) cf.generateCRL(inStream);
            inStream.close();
            params.addCertStore(CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(Collections.singletonList(crl))));
        }

        // perform validation
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            log.debug("Trsuted Cert = NULL");
        } else {
            log.debug("Trusted CA DN = " + trustedCert.getSubjectDN());
        }

    } catch (CertPathValidatorException e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    } catch (Exception e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    }
    log.debug("CERTIFICATE VALIDATION SUCCEEDED");
}

From source file:org.panbox.core.pairing.PAKCorePairingRequester.java

@Override
public void runOperation(Cipher cipher, SecretKeySpec spec) throws Exception {
    logger.debug("PAKCorePairingHandler : runOperation : Started to request pairing");

    KeyFactory keyFactory = KeyFactory.getInstance(KeyConstants.ASYMMETRIC_ALGORITHM_ALGO_ONLY);
    CertificateFactory certificateFactory = CertificateFactory.getInstance(KeyConstants.CERTIFICATE_ENCODING);

    cipher.init(Cipher.DECRYPT_MODE, spec);

    String base64received;//  www  . j a v  a 2s  . com

    base64received = (String) dataInputStream.readObject();
    logger.debug("PAKCorePairingRequester : runOperation : Received pairingType: " + base64received);
    byte[] encType = Base64.decodeBase64(base64received);
    String strType = new String(cipher.doFinal(encType));
    type = PairingType.valueOf(strType);

    switch (type) {
    case MASTER:
        logger.info("PAKCorePairingRequester : runOperation : This device will be paired as master device!");

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received email: " + base64received);
        eMail = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received firstname: " + base64received);
        firstName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received lastname: " + base64received);
        lastName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received devicename: " + base64received);
        deviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received keyPassword: " + base64received);

        keyPassword = Utils.toChars(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received ownerKeyEnc: " + base64received);
        PKCS8EncodedKeySpec ownerKeyEncSpec = new PKCS8EncodedKeySpec(
                cipher.doFinal(Base64.decodeBase64(base64received)));
        PrivateKey pKey = keyFactory.generatePrivate(ownerKeyEncSpec);
        ownerKeyEnc = CryptCore.privateKeyToKeyPair(pKey);

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received ownerKeySign: " + base64received);
        PKCS8EncodedKeySpec ownerKeySignSpec = new PKCS8EncodedKeySpec(
                cipher.doFinal(Base64.decodeBase64(base64received)));
        pKey = keyFactory.generatePrivate(ownerKeySignSpec);
        ownerKeySign = CryptCore.privateKeyToKeyPair(pKey);

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received numOfDevices: " + base64received);

        int numOfDevices = Integer.valueOf(new String(cipher.doFinal(Base64.decodeBase64(base64received))));

        knownDevices = new HashMap<String, X509Certificate>();

        for (int i = 0; i < numOfDevices; ++i) {
            base64received = (String) dataInputStream.readObject();
            logger.debug("PAKCorePairingRequester : runOperation : Received device name (" + i + "): "
                    + base64received);

            String knownDeviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

            base64received = (String) dataInputStream.readObject();
            logger.debug("PAKCorePairingRequester : runOperation : Received device certificate (" + i + "): "
                    + base64received);

            InputStream is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));
            X509Certificate knownDeviceCert = (X509Certificate) certificateFactory.generateCertificate(is);

            knownDevices.put(knownDeviceName, knownDeviceCert);
            logger.debug("PAKCorePairingRequester : runOperation : Added device (" + i + "): " + knownDeviceName
                    + ": " + knownDeviceCert);
        }

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received contacts: " + base64received);

        InputStream is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));

        knownContacts = Ezvcard.parse(is).all();

        // --- SEND Device Type and Key ---

        cipher.init(Cipher.ENCRYPT_MODE, spec);

        byte[] encDevType = cipher.doFinal(devType.toString().getBytes());

        devCert = CryptCore.createSelfSignedX509Certificate(devKey.getPrivate(), devKey.getPublic(),
                new PairingIPersonDummy(eMail, firstName, lastName));

        byte[] encDevCert = cipher.doFinal(devCert.getEncoded());

        String base64encDevType = Base64.encodeBase64String(encDevType);
        String base64encDevCert = Base64.encodeBase64String(encDevCert);
        logger.debug("PAKCorePairingRequester : runOperation : Send devicetype: " + base64encDevType);
        logger.debug("PAKCorePairingRequester : runOperation : Send devicecert: " + base64encDevCert);

        dataOutputStream.writeObject(base64encDevType);
        dataOutputStream.flush();
        dataOutputStream.writeObject(base64encDevCert);
        dataOutputStream.flush();

        break;
    case SLAVE:
        logger.info("PAKCorePairingRequester : runOperation : This device will be paired as slave device!");

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received email: " + base64received);
        eMail = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received firstname: " + base64received);
        firstName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received lastname: " + base64received);
        lastName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received devicename: " + base64received);
        deviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received ownerCertEnc: " + base64received);
        is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));
        ownerCertEnc = (X509Certificate) certificateFactory.generateCertificate(is);

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received ownerCertSign: " + base64received);
        is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));
        ownerCertSign = (X509Certificate) certificateFactory.generateCertificate(is);

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received numOfDevices: " + base64received);

        numOfDevices = Integer.valueOf(new String(cipher.doFinal(Base64.decodeBase64(base64received))));

        knownDevices = new HashMap<String, X509Certificate>();

        for (int i = 0; i < numOfDevices; ++i) {
            base64received = (String) dataInputStream.readObject();
            logger.debug("PAKCorePairingRequester : runOperation : Received device name (" + i + "): "
                    + base64received);

            String knownDeviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received)));

            base64received = (String) dataInputStream.readObject();
            logger.debug("PAKCorePairingRequester : runOperation : Received device certificate (" + i + "): "
                    + base64received);

            is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));
            X509Certificate knownDeviceCert = (X509Certificate) certificateFactory.generateCertificate(is);

            knownDevices.put(knownDeviceName, knownDeviceCert);
            logger.debug("PAKCorePairingRequester : runOperation : Added device (" + i + "): " + knownDeviceName
                    + ": " + knownDeviceCert);
        }

        base64received = (String) dataInputStream.readObject();
        logger.debug("PAKCorePairingRequester : runOperation : Received contacts: " + base64received);

        is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received)));

        knownContacts = Ezvcard.parse(is).all();

        // --- SEND Device Type and Key ---

        cipher.init(Cipher.ENCRYPT_MODE, spec);

        encDevType = cipher.doFinal(devType.toString().getBytes());

        devCert = CryptCore.createSelfSignedX509Certificate(devKey.getPrivate(), devKey.getPublic(),
                new PairingIPersonDummy(eMail, firstName, lastName));

        encDevCert = cipher.doFinal(devCert.getEncoded());

        base64encDevType = Base64.encodeBase64String(encDevType);
        base64encDevCert = Base64.encodeBase64String(encDevCert);
        logger.debug("PAKCorePairingRequester : runOperation : Send devicetype: " + base64encDevType);
        logger.debug("PAKCorePairingRequester : runOperation : Send devicecert: " + base64encDevCert);

        dataOutputStream.writeObject(base64encDevType);
        dataOutputStream.flush();
        dataOutputStream.writeObject(base64encDevCert);
        dataOutputStream.flush();
        break;
    default:
        logger.error("PAKCorePairingRequester : runOperation : Unknown pairing type!");
        break;
    }

    logger.debug(
            "PAKCorePairingRequester : runOperation : Pairing finished. Will wait for session to be closed!.");

    try {
        dataInputStream.readBoolean();
    } catch (Exception ex) {
        // Connection has been closed successfully! Pairing done :)
    }
}