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:tf.nox.wifisetup.WifiSetup.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private void applyAndroid43EnterpriseSettings(WifiConfiguration currentConfig,
        HashMap<String, String> configMap) {
    try {/*  w  w  w  .  jav a 2  s  .c  o  m*/
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = getResources().openRawResource(R.raw.cacert);
        // InputStream in = new ByteArrayInputStream(Base64.decode(ca.replaceAll("-----(BEGIN|END) CERTIFICATE-----", ""), 0));
        X509Certificate caCert = (X509Certificate) certFactory.generateCertificate(in);

        WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
        enterpriseConfig.setPhase2Method(Phase2.PAP);
        enterpriseConfig.setAnonymousIdentity(configMap.get(INT_ANONYMOUS_IDENTITY));
        enterpriseConfig.setEapMethod(Eap.TTLS);

        enterpriseConfig.setCaCertificate(caCert);
        enterpriseConfig.setIdentity(s_username);
        enterpriseConfig.setPassword(s_password);
        enterpriseConfig.setSubjectMatch(configMap.get(INT_SUBJECT_MATCH));
        currentConfig.enterpriseConfig = enterpriseConfig;

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Creates a new instance of {@code Certificate}
 * /*from  w  w  w .  j  a v  a2s  . c o m*/
 * @return the new {@code Certificate} instance.
 * @throws CertificateException
 *             if the specified certificate type is not available at any
 *             installed provider.
 * @throws IOException
 *             if an error occurs while closing this stream
 */
private Certificate getServerCertificate() throws CertificateException, IOException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // deepak
    InputStream caInput = mContext.getResources().openRawResource(R.raw.server);
    // ankit
    // InputStream caInput =
    // mContext.getResources().openRawResource(R.raw.localhost);

    Certificate ca;
    try {
        ca = cf.generateCertificate(caInput);
    } finally {
        caInput.close();
    }

    return ca;
}

From source file:test.integ.be.agiv.security.IPSTSTest.java

private X509Certificate generateSelfSignedCertificate(KeyPair keyPair, String subjectDn, DateTime notBefore,
        DateTime notAfter) throws IOException, InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, CertificateException {
    PublicKey subjectPublicKey = keyPair.getPublic();
    PrivateKey issuerPrivateKey = keyPair.getPrivate();
    String signatureAlgorithm = "SHA1WithRSAEncryption";
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();/*from   w ww . jav  a  2 s.  c  om*/
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm(signatureAlgorithm);
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());
    X509Principal issuerDN = new X509Principal(subjectDn);
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom()));

    certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(subjectPublicKey));
    PublicKey issuerPublicKey;
    issuerPublicKey = subjectPublicKey;
    certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerPublicKey));

    certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));

    X509Certificate certificate;
    certificate = certificateGenerator.generate(issuerPrivateKey);

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificate.getEncoded()));
    return certificate;
}

From source file:org.commonjava.maven.galley.transport.htcli.internal.SSLUtils.java

public static KeyStore readKeyAndCert(final String pemContent, final String keyPass)
        throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
        InvalidKeySpecException {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);// w w w.  jav  a 2 s. c o m

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    final KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    final List<String> lines = readLines(pemContent);

    String currentHeader = null;
    final StringBuilder current = new StringBuilder();
    final Map<String, String> entries = new LinkedHashMap<String, String>();
    for (final String line : lines) {
        if (line == null) {
            continue;
        }

        if (line.startsWith("-----BEGIN")) {
            currentHeader = line.trim();
            current.setLength(0);
        } else if (line.startsWith("-----END")) {
            entries.put(currentHeader, current.toString());
        } else {
            current.append(line.trim());
        }
    }

    final List<Certificate> certs = new ArrayList<Certificate>();
    for (int pass = 0; pass < 2; pass++) {
        for (final Map.Entry<String, String> entry : entries.entrySet()) {
            final String header = entry.getKey();
            final byte[] data = decodeBase64(entry.getValue());

            if (pass > 0 && header.contains("BEGIN PRIVATE KEY")) {
                final KeySpec spec = new PKCS8EncodedKeySpec(data);
                final PrivateKey key = keyFactory.generatePrivate(spec);
                ks.setKeyEntry("key", key, keyPass.toCharArray(), certs.toArray(new Certificate[] {}));
            } else if (pass < 1 && header.contains("BEGIN CERTIFICATE")) {
                final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data));

                ks.setCertificateEntry("certificate", c);
                certs.add(c);
            }
        }
    }

    return ks;
}

From source file:eu.eidas.auth.engine.core.impl.SignSW.java

private BasicX509Credential getKeyInfoCredential(KeyInfo keyInfo) throws CertificateException {
    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);
    return entityX509Cred;
}

From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java

private X509Certificate generateCACertificate(final KeyPair keyPair, final String subject,
        final DateTime notBefore, final DateTime notAfter) throws Exception {
    LOG.debug("generate CA certificate: " + subject);

    final X500Name issuer = new X500Name(subject);
    final X500Name subjectX500Name = new X500Name(subject);

    final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    final SecureRandom secureRandom = new SecureRandom();
    final byte[] serialValue = new byte[8];
    secureRandom.nextBytes(serialValue);
    final BigInteger serial = new BigInteger(serialValue);

    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer, serial,
            notBefore.toDate(), notAfter.toDate(), subjectX500Name, publicKeyInfo);

    try {//from ww  w  . ja  v  a  2  s.com
        final JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
        x509v3CertificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
                extensionUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
        x509v3CertificateBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
                extensionUtils.createAuthorityKeyIdentifier(keyPair.getPublic()));

        x509v3CertificateBuilder.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
                new NetscapeCertType(
                        NetscapeCertType.sslCA | NetscapeCertType.smimeCA | NetscapeCertType.objectSigningCA));

        x509v3CertificateBuilder.addExtension(X509Extension.keyUsage, true,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));

        x509v3CertificateBuilder.addExtension(X509Extension.basicConstraints, true,
                new BasicConstraints(2147483647));

    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter;
    try {
        asymmetricKeyParameter = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    ContentSigner contentSigner;
    try {
        contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKeyParameter);
    } catch (final OperatorCreationException e) {
        throw new RuntimeException(e);
    }
    final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate;
    try {
        encodedCertificate = x509CertificateHolder.getEncoded();
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }

    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (final CertificateException e) {
        throw new RuntimeException(e);
    }
    X509Certificate certificate;
    try {
        certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (final CertificateException e) {
        throw new RuntimeException(e);
    }
    return certificate;
}

From source file:view.CertificateManagementDialog.java

private void btnAddCertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddCertActionPerformed
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(true);
    chooser.showOpenDialog(null);//from   w  w w . j ava2s .c  om

    File[] files = chooser.getSelectedFiles();
    final ArrayList<Certificate> toAddList = new ArrayList<>();
    for (File file : files) {
        try {
            CertificateFactory fact = CertificateFactory.getInstance("X.509");
            FileInputStream is = new FileInputStream(file);
            Certificate cert = fact.generateCertificate(is);
            toAddList.add(cert);
        } catch (Exception ex) {
        }
    }
    if (!toAddList.isEmpty()) {
        String password = getUserInputPassword();
        if (password == null) {
            return;
        }
        addCertsToKeystore(toAddList, password);
        refresh(keystore);
    }
}

From source file:eu.stork.peps.auth.engine.core.impl.SignSW.java

/**
 * @param tokenSaml token SAML// ww w . j  av a  2 s  .c  o  m
 * @return the SAMLObject validated.
 * @throws SAMLEngineException error validate signature
 * @see eu.stork.peps.auth.engine.core.SAMLEngineSignI#validateSignature(org.opensaml.common.SignableSAMLObject)
 */
public final SAMLObject validateSignature(final SignableSAMLObject tokenSaml) throws SAMLEngineException {
    LOG.info("Start signature validation.");
    try {

        // Validate structure signature
        final SAMLSignatureProfileValidator sigProfValidator = new SAMLSignatureProfileValidator();
        try {
            // Indicates signature id conform to SAML Signature profile
            sigProfValidator.validate(tokenSaml.getSignature());
        } catch (ValidationException e) {
            LOG.error("ValidationException: signature isn't conform to SAML Signature profile.");
            throw new SAMLEngineException(e);
        }

        String aliasCert = null;
        X509Certificate certificate;

        final List<Credential> trustCred = new ArrayList<Credential>();

        for (final Enumeration<String> e = storkOwnKeyStore.aliases(); e.hasMoreElements();) {
            aliasCert = e.nextElement();
            final BasicX509Credential credential = new BasicX509Credential();
            certificate = (X509Certificate) storkOwnKeyStore.getCertificate(aliasCert);
            credential.setEntityCertificate(certificate);
            trustCred.add(credential);
        }

        final KeyInfo keyInfo = tokenSaml.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);

        // Exist only one certificate
        final BasicX509Credential entityX509Cred = new BasicX509Credential();
        entityX509Cred.setEntityCertificate(cert);

        try {
            cert.checkValidity();
        } catch (CertificateExpiredException exp) {
            throw new SAMLEngineException("Certificate expired.");
        } catch (CertificateNotYetValidException exp) {
            throw new SAMLEngineException("Certificate not yet valid.");
        }

        /* A better use of PKI based validation but not wanted for STORK... 
          boolean trusted = false;
                
        for (final Enumeration<String> e = storkOwnKeyStore.aliases(); e.hasMoreElements();) 
         {
            aliasCert = e.nextElement();      
            certificate = (X509Certificate) storkOwnKeyStore.getCertificate(aliasCert);               
            try {
               cert.verify(certificate.getPublicKey());
               trusted = true;
               break;
            }
            catch (Exception ex) {
               //Do nothing - cert not trusted yet
            }
         }
                
        if (!trusted)
            throw new SAMLEngineException("Certificate is not trusted.");*/

        // Validate trust certificates
        final ExplicitX509CertificateTrustEvaluator chainTrustEvaluator = new ExplicitX509CertificateTrustEvaluator();

        if (!chainTrustEvaluator.validate(entityX509Cred, trustCred)) {
            throw new SAMLEngineException("Certificate is not trusted.");
        }
        final ExplicitKeyTrustEvaluator keyTrustEvaluator = new ExplicitKeyTrustEvaluator();

        if (!keyTrustEvaluator.validate(entityX509Cred, trustCred)) {
            throw new SAMLEngineException("Certificate is not trusted.");
        }

        // Validate signature
        final SignatureValidator sigValidator = new SignatureValidator(entityX509Cred);
        sigValidator.validate(tokenSaml.getSignature());

    } catch (ValidationException e) {
        LOG.error("ValidationException.");
        throw new SAMLEngineException(e);
    } catch (KeyStoreException e) {
        LOG.error("KeyStoreException.", e);
        throw new SAMLEngineException(e);
    } catch (GeneralSecurityException e) {
        LOG.error("GeneralSecurityException.", e);
        throw new SAMLEngineException(e);
    }
    LOG.info(tokenSaml.getSignatureReferenceID());
    LOG.info("Start signature validation - END.");
    return tokenSaml;
}

From source file:org.signserver.module.mrtdsodsigner.MRTDSODSigner.java

private void verifySignatureAndChain(final SODFile sod, final Collection<Certificate> chain)
        throws TigerSignerException {
    try {// w w  w  .  j  a va 2 s  .c o m
        if (log.isDebugEnabled()) {
            final StringBuilder buff = new StringBuilder();
            buff.append("Verifying SOD signed by DS with issuer: ");
            buff.append(sod.toString());
            log.debug(buff.toString());
        }

        // Get Signer certificate from SOD
        final X509Certificate sodCert = sod.getDocSigningCertificate();

        // We need a Bouncy Castle certificate so reconstruct it
        final CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
        final X509Certificate signerCert = (X509Certificate) factory
                .generateCertificate(new ByteArrayInputStream(sodCert.getEncoded()));

        // Verify the SOD signature using certificate from SOD
        final boolean consistent = sod.checkDocSignature(signerCert);
        if (!consistent) {
            log.error("Failed to verify the SOD we signed ourselves.");
            log.error("Cert: " + signerCert);
            log.error("SOD: " + sod);
            throw new TigerSignerException("GeneralSecurityException : Signature not consistent");
        }

        // Find the issuer certificate from the configured chain
        final X509Certificate issuerCert = (chain == null ? null : findIssuerCert(chain, signerCert));
        if (issuerCert == null) {
            log.error("Failed to verify certificate chain");
            log.error("Cert: " + signerCert);
            log.error("SOD Cert: " + signerCert);
            log.error("Chain: " + chain);
            throw new TigerSignerException("GeneralSecurityException :Issuer of cert not in chain.");
        }

        // Verify the signer certificate using the issuer from the chain
        signerCert.verify(issuerCert.getPublicKey());
    } catch (IOException e) {
        log.error("Getting signer certificate from SOD failed", e);
        throw new TigerSignerException("GeneralSecurityException : Getting signer certificate from SOD failed",
                e);
    } catch (CertificateEncodingException e) {
        throw new TigerSignerException("CertificateEncodingException : ", e);
    } catch (CertificateException e) {
        throw new TigerSignerException("CertificateException : ", e);
    } catch (NoSuchAlgorithmException e) {
        throw new TigerSignerException("NoSuchAlgorithmException : ", e);
    } catch (InvalidKeyException e) {
        throw new TigerSignerException("InvalidKeyException : ", e);
    } catch (SignatureException e) {
        throw new TigerSignerException("SignatureException : ", e);
    } catch (NoSuchProviderException e) {
        throw new TigerSignerException("NoSuchProviderException : ", e);
    } catch (GeneralSecurityException e) {
        throw new TigerSignerException("GeneralSecurityException : ", e);
    }
}

From source file:eu.eidas.auth.engine.core.impl.SignSW.java

private X509Certificate getSignatureCertificate(final Signature signature) throws SAMLEngineException {
    try {//w  w w  .  ja  v  a2 s .  co  m
        final KeyInfo keyInfo = signature.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);
        return cert;
    } catch (GeneralSecurityException e) {
        LOG.debug("ERROR : GeneralSecurityException.", e);
        LOG.warn("ERROR : GeneralSecurityException.", e.getMessage());
        throw new SAMLEngineException(e);
    }
}