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.cesecore.util.CertTools.java

/**
 * Creates Certificate from byte[], can be either an X509 certificate or a CVCCertificate
 * //from   w ww .j  av a  2s . c  o  m
 * @param cert byte array containing certificate in binary (DER) format, or PEM encoded X.509 certificate
 * @param provider provider for example "SUN" or "BC", use null for the default provider (BC)
 * 
 * @return a Certificate 
 * @throws CertificateParsingException if certificate couldn't be parsed from cert
 * 
 */
public static Certificate getCertfromByteArray(byte[] cert, String provider)
        throws CertificateParsingException {
    Certificate ret = null;
    String prov = provider;
    if (provider == null) {
        prov = BouncyCastleProvider.PROVIDER_NAME;
    }
    try {
        final CertificateFactory cf = CertTools.getCertificateFactory(prov);
        ret = cf.generateCertificate(new ByteArrayInputStream(cert));
    } catch (CertificateException e) {
        log.debug("CertificateException trying to read X509Certificate.", e);
    }
    if (ret == null) {
        // We could not create an X509Certificate, see if it is a CVC certificate instead
        try {
            final CVCertificate parsedObject = CertificateParser.parseCertificate(cert);
            ret = new CardVerifiableCertificate(parsedObject);
        } catch (ParseException e) {
            log.debug("ParseException trying to read CVCCertificate.", e);
        } catch (ConstructionException e) {
            log.debug("ConstructionException trying to read CVCCertificate.", e);
        }
    }
    if (ret == null) {
        throw new CertificateParsingException(
                "No certificate could be parsed from byte array. See debug logs for details.");
    }
    return ret;
}

From source file:org.cesecore.util.CertTools.java

/**
 * Gets subject or issuer DN in the format we are sure about (BouncyCastle),supporting UTF8.
 * /*from ww  w  . j  a  v  a 2s. co  m*/
 * @param cert X509Certificate
 * @param which 1 = subjectDN, anything else = issuerDN
 * 
 * @return String containing the DN.
 */
private static String getDN(final Certificate cert, final int which) {
    String ret = null;
    if (cert == null) {
        return null;
    }
    if (cert instanceof X509Certificate) {
        // cert.getType=X.509
        try {
            final CertificateFactory cf = CertTools.getCertificateFactory();
            final X509Certificate x509cert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cert.getEncoded()));
            String dn = null;
            if (which == 1) {
                dn = x509cert.getSubjectDN().toString();
            } else {
                dn = x509cert.getIssuerDN().toString();
            }
            ret = stringToBCDNString(dn);
        } catch (CertificateException ce) {
            log.info("Could not get DN from X509Certificate. " + ce.getMessage());
            log.debug("", ce);
            return null;
        }
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        try {
            ReferenceField rf = null;
            if (which == 1) {
                rf = cvccert.getCVCertificate().getCertificateBody().getHolderReference();
            } else {
                rf = cvccert.getCVCertificate().getCertificateBody().getAuthorityReference();
            }
            if (rf != null) {
                // Construct a "fake" DN which can be used in EJBCA
                // Use only mnemonic and country, since sequence is more of a serialnumber than a DN part
                String dn = "";
                if (rf.getMnemonic() != null) {
                    if (StringUtils.isNotEmpty(dn)) {
                        dn += ", ";
                    }
                    dn += "CN=" + rf.getMnemonic();
                }
                if (rf.getCountry() != null) {
                    if (StringUtils.isNotEmpty(dn)) {
                        dn += ", ";
                    }
                    dn += "C=" + rf.getCountry();
                }
                ret = stringToBCDNString(dn);
            }
        } catch (NoSuchFieldException e) {
            log.error("NoSuchFieldException: ", e);
            return null;
        }
    }
    return ret;
}

From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java

/**
 * This function drives the accepting side of the context establishment
 * process. It is expected to be called in tandem with the
 * {@link #initSecContext(byte[], int, int) initSecContext} function.
 * <BR>/*from   w w w  . j  a v a 2 s .c o m*/
 * The behavior of context establishment process can be modified by
 * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE}
 * and {@link GSSConstants#REJECT_LIMITED_PROXY
 * GSSConstants.REJECT_LIMITED_PROXY} context options. If the
 * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE}
 * option is set to
 * {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL}
 * the context establishment process will be compatible with regular SSL
 * (no credential delegation support). If the option is set to
 * {@link GSIConstants#MODE_GSI GSIConstants.MODE_GSI}
 * credential delegation during context establishment process will be accepted.
 * If the {@link GSSConstants#REJECT_LIMITED_PROXY
 * GSSConstants.REJECT_LIMITED_PROXY} option is enabled, a peer
 * presenting limited proxy credential will be automatically
 * rejected and the context establishment process will be aborted.
 *
 * @return a byte[] containing the token to be sent to the peer.
 *         null indicates that no token is generated (needs more data)
 */
public byte[] acceptSecContext(byte[] inBuff, int off, int len) throws GSSException {
    logger.debug("enter acceptSecContext");

    if (!this.conn) {
        this.role = ACCEPT;

        logger.debug("enter initializing in acceptSecContext");

        if (this.ctxCred.getName().isAnonymous()) {
            throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN,
                    "acceptCtx00");
        }

        if (this.ctxCred.getUsage() != GSSCredential.ACCEPT_ONLY
                && this.ctxCred.getUsage() != GSSCredential.INITIATE_AND_ACCEPT) {
            throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN,
                    "badCredUsage");
        }

        setCredential();

        try {
            init(this.role);
        } catch (SSLException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        this.conn = true;
        logger.debug("done initializing in acceptSecContext");
    }

    /*DEL
            this.out.reset();
            this.in.putToken(inBuff, off, len);
    */
    this.outByteBuff.clear();
    ByteBuffer inByteBuff;
    if (savedInBytes != null) {
        if (len > 0) {
            byte[] allInBytes = new byte[savedInBytes.length + len];
            logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n");
            System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length);
            System.arraycopy(inBuff, off, allInBytes, savedInBytes.length, len);
            inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length);
        } else {
            inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length);
        }
        savedInBytes = null;
    } else {
        inByteBuff = ByteBuffer.wrap(inBuff, off, len);
    }

    switch (state) {

    case HANDSHAKE:

        try {
            logger.debug("STATUS BEFORE: " + this.sslEngine.getHandshakeStatus().toString());
            SSLEngineResult.HandshakeStatus handshake_status = sslEngine.getHandshakeStatus();

            if (handshake_status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
                // return null;
                throw new Exception("GSSAPI in HANDSHAKE state but " + "SSLEngine in NOT_HANDSHAKING state!");
            } else {
                outByteBuff = this.sslProcessHandshake(inByteBuff, outByteBuff);
            }

            logger.debug("STATUS AFTER: " + this.sslEngine.getHandshakeStatus().toString());

            outByteBuff.flip();

            /*DEL
                            if (this.conn.getHandshake().finishedP()) {
            */
            if (this.sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
                // the wrap/unwrap above has resulted in handshaking
                // being complete on our end.

                logger.debug("acceptSecContext handshake finished");
                handshakeFinished();

                // acceptor
                for (X509Certificate cert : this.ctxCred.getCertificateChain()) {
                    setGoodUntil(cert.getNotAfter());
                }
                this.targetName = this.ctxCred.getName();

                // initiator - peer
                /*DEL
                                    Vector chain = this.conn.getCertificateChain();
                */
                Certificate[] chain;
                try {
                    chain = this.sslEngine.getSession().getPeerCertificates();
                } catch (SSLPeerUnverifiedException e) {
                    chain = null;
                }
                if (chain == null || chain.length == 0) {
                    this.sourceName = new GlobusGSSName();
                    this.anonymity = true;
                } else {
                    /*DEL
                                            X509Cert crt = (X509Cert)chain.elementAt(chain.size()-1);
                                            setGoodUntil(crt.getValidityNotAfter());
                            
                                            String identity = verifyChain(chain);
                    */
                    for (X509Certificate cert : (X509Certificate[]) chain) {
                        setGoodUntil(cert.getNotAfter());
                    }

                    String identity = BouncyCastleUtil.getIdentity(
                            bcConvert(BouncyCastleUtil.getIdentityCertificate((X509Certificate[]) chain)));
                    this.sourceName = new GlobusGSSName(CertificateUtil.toGlobusID(identity, false));
                    this.peerLimited = Boolean.valueOf(ProxyCertificateUtil
                            .isLimitedProxy(BouncyCastleUtil.getCertificateType((X509Certificate) chain[0])));

                    logger.debug("Peer Identity is: " + identity + " Target name is: " + this.targetName
                            + " Limited Proxy: " + this.peerLimited.toString());

                    this.anonymity = false;
                }

                if (this.gssMode == GSIConstants.MODE_GSI) {
                    this.state = SERVER_START_DEL;
                } else {
                    setDone();
                }
            }
        } catch (IOException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        } catch (Exception e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        break;

    case SERVER_START_DEL:

        try {
            if (inByteBuff.remaining() <= 0) {
                return null;
            }

            /*DEL
                            int delChar = this.conn.getInStream().read();
            */
            outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff);
            outByteBuff.flip();
            byte[] delChar = new byte[outByteBuff.remaining()];
            outByteBuff.get(delChar, 0, delChar.length);
            /*DEL
                            if (delChar != GSIConstants.DELEGATION_CHAR) {
            */
            if (!Arrays.equals(delChar, DELEGATION_TOKEN)) {
                setDone();
                break;
            }

            /*DEL
                            Vector chain = this.conn.getCertificateChain();
            */
            Certificate[] chain;
            try {
                chain = this.sslEngine.getSession().getPeerCertificates();
            } catch (SSLPeerUnverifiedException e) {
                chain = null;
            }
            if (chain == null || chain.length == 0) {
                throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.DELEGATION_ERROR,
                        "noClientCert");
            }

            X509Certificate tmpCert = (X509Certificate) chain[0];
            /*DEL
            PureTLSUtil.convertCert((X509Cert)chain.lastElement());
            */
            byte[] req = generateCertRequest(tmpCert);
            /*DEL
                            this.conn.getOutStream().write(req, 0, req.length);
            */
            inByteBuff = ByteBuffer.wrap(req, 0, req.length);
            outByteBuff.clear();
            outByteBuff = sslDataWrap(inByteBuff, outByteBuff);
            outByteBuff.flip();

        } catch (GeneralSecurityException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        this.state = SERVER_END_DEL;
        break;

    case SERVER_END_DEL:

        try {
            if (inByteBuff.remaining() <= 0) {
                return null;
            }

            /*DEL
                            X509Certificate certificate = CertUtil.loadCertificate(this.conn.getInStream());
            */
            outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff);
            outByteBuff.flip();
            if (!outByteBuff.hasRemaining())
                break;
            byte[] buf = new byte[outByteBuff.remaining()];
            outByteBuff.get(buf, 0, buf.length);
            ByteArrayInputStream inStream = new ByteArrayInputStream(buf, 0, buf.length);
            CertificateFactory cf = null;
            X509Certificate certificate = null;
            try {
                cf = CertificateFactory.getInstance("X.509");
                certificate = (X509Certificate) cf.generateCertificate(inStream);
            } finally {
                inStream.close();
            }

            if (logger.isTraceEnabled()) {
                logger.trace("Received delegated cert: " + certificate.toString());
            }

            verifyDelegatedCert(certificate);

            /*DEL
                            Vector chain = this.conn.getCertificateChain();
            */
            Certificate[] chain = this.sslEngine.getSession().getPeerCertificates();
            int chainLen = chain.length;
            X509Certificate[] newChain = new X509Certificate[chainLen + 1];
            newChain[0] = bcConvert((X509Certificate) certificate);
            for (int i = 0; i < chainLen; i++) {
                /*DEL
                                    newChain[i+1] = PureTLSUtil.convertCert((X509Cert)chain.elementAt(chainLen - 1 - i));
                */
                newChain[i + 1] = bcConvert((X509Certificate) chain[i]);
            }

            X509Credential proxy = new X509Credential(this.keyPair.getPrivate(), newChain);

            this.delegCred = new GlobusGSSCredentialImpl(proxy, GSSCredential.INITIATE_AND_ACCEPT);

        } catch (GeneralSecurityException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        } catch (IOException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }
        setDone();
        break;

    default:
        throw new GSSException(GSSException.FAILURE);
    }

    if (inByteBuff.hasRemaining()) {
        // Likely BUFFER_UNDERFLOW; save the
        // inByteBuff bytes here like in the unwrap() case
        logger.debug("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining()
                + " Handshaking status: " + sslEngine.getHandshakeStatus());
        logger.debug("SAVING unprocessed " + inByteBuff.remaining() + "BYTES\n");
        savedInBytes = new byte[inByteBuff.remaining()];
        inByteBuff.get(savedInBytes, 0, savedInBytes.length);
    }

    logger.debug("exit acceptSecContext");
    /*DEL
            return (this.out.size() > 0) ? this.out.toByteArray() : null;
    */
    if (this.outByteBuff.hasRemaining()) {
        // TODO can we avoid this copy if the ByteBuffer is array based
        // and we return that array, each time allocating a new array
        // for outByteBuff?
        byte[] out = new byte[this.outByteBuff.remaining()];
        this.outByteBuff.get(out, 0, out.length);
        return out;
    } else
        return null;
}

From source file:org.apache.juddi.webconsole.hub.UddiHub.java

/**
 * Converts a UDDI Signature to a readable representation of the signing
 * certificate subject name/*from   ww w.j  a v a  2  s  .c om*/
 *
 * @param sig
 * @return human readable signature
 */
public static String SignatureToReadable(SignatureType sig) {
    StringBuilder sb = new StringBuilder();
    // X509Certificate signingcert = null;
    //sb.append("Signature Id: ").append(sig.getKeyInfo().getId());
    for (int i = 0; i < sig.getKeyInfo().getContent().size(); i++) {
        //sb.append("Signature #").append((i + 1)).append(": ");
        JAXBElement get = (JAXBElement) sig.getKeyInfo().getContent().get(i);

        if (get.getValue() instanceof org.w3._2000._09.xmldsig_.X509DataType) {
            X509DataType xd = (X509DataType) get.getValue();
            for (int k = 0; k < xd.getX509IssuerSerialOrX509SKIOrX509SubjectName().size(); k++) {
                if (xd.getX509IssuerSerialOrX509SKIOrX509SubjectName().get(k) instanceof JAXBElement) {
                    JAXBElement element = (JAXBElement) xd.getX509IssuerSerialOrX509SKIOrX509SubjectName()
                            .get(k);
                    if (element.getValue() instanceof byte[]) {
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            InputStream is = new ByteArrayInputStream((byte[]) element.getValue());
                            X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
                            is.close();
                            sb.append(cert.getSubjectDN().getName());
                        } catch (Exception ex) {
                        }
                    } else if (element.getValue() instanceof String) {
                        // sb.append((String) element.getValue());
                    }
                }
            }
        }
    }
    return sb.toString();
}

From source file:eu.stork.peps.auth.engine.STORKSAMLEngine.java

/**
 * Gets the country from X.509 Certificate.
 * /*from   w  w w .j a va 2s  . com*/
 * @param keyInfo the key info
 * 
 * @return the country
 */
private String getCountry(final KeyInfo keyInfo) {
    LOG.debug("Recover country information.");

    String result = "";
    try {
        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        // Transform the KeyInfo to X509Certificate.
        CertificateFactory certFact;
        certFact = CertificateFactory.getInstance("X.509");

        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));

        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        String distName = cert.getSubjectDN().toString();

        distName = StringUtils.deleteWhitespace(StringUtils.upperCase(distName));

        final String countryCode = "C=";
        final int init = distName.indexOf(countryCode);

        if (init > StringUtils.INDEX_NOT_FOUND) { // Exist country code.
            int end = distName.indexOf(',', init);

            if (end <= StringUtils.INDEX_NOT_FOUND) {
                end = distName.length();
            }

            if (init < end && end > StringUtils.INDEX_NOT_FOUND) {
                result = distName.substring(init + countryCode.length(), end);
                //It must be a two characters value
                if (result.length() > 2) {
                    result = result.substring(0, 2);
                }
            }
        }

    } catch (CertificateException e) {
        LOG.error("Procces getCountry from certificate.");
    }
    return result.trim();
}

From source file:eu.stork.peps.auth.engine.STORKSAMLEngine.java

/**
 * Gets the alias from X.509 Certificate at keystore.
 * /*from w  w w.  j  a va  2 s .c  o m*/
 * @param keyInfo the key info
 * @param storkOwnKeyStore 
 * @param storkOwnKeyStore 
 * 
 * @return the alias
 */
private String getAlias(final KeyInfo keyInfo, KeyStore storkOwnKeyStore) {

    LOG.debug("Recover alias information");

    String alias = null;
    try {
        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        // Transform the KeyInfo to X509Certificate.
        CertificateFactory certFact;
        certFact = CertificateFactory.getInstance("X.509");

        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));

        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        final String tokenSerialNumber = cert.getSerialNumber().toString(16);
        final X509Principal tokenIssuerDN = new X509Principal(cert.getIssuerDN().getName());

        String aliasCert;
        X509Certificate certificate;
        boolean find = false;

        for (final Enumeration<String> e = storkOwnKeyStore.aliases(); e.hasMoreElements() && !find;) {
            aliasCert = e.nextElement();
            certificate = (X509Certificate) storkOwnKeyStore.getCertificate(aliasCert);

            final String serialNum = certificate.getSerialNumber().toString(16);

            X509Principal issuerDN = new X509Principal(certificate.getIssuerDN().getName());

            if (serialNum.equalsIgnoreCase(tokenSerialNumber)
                    && X509PrincipalUtil.equals2(issuerDN, tokenIssuerDN)) {
                alias = aliasCert;
                find = true;
            }

        }

    } catch (KeyStoreException e) {
        LOG.error("Procces getAlias from certificate associated into the signing keystore..", e);
    } catch (CertificateException e) {
        LOG.error("Procces getAlias from certificate associated into the signing keystore..", e);
    } catch (RuntimeException e) {
        LOG.error("Procces getAlias from certificate associated into the signing keystore..", e);
    }
    return alias;
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

public X509TrustManager getTrustManager(final Iterable<String> identitiesToTest,
        final CertificateMatcher clientVerifier, final CertificateMatcher serverVerifier)
        throws GeneralSecurityException {
    // obtain the default X509 trust manager
    X509TrustManager defaultTm = null;
    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    //workaround for https://bugs.openjdk.java.net/browse/JDK-6672015
    KeyStore ks = null;//from w w w.j  a v a  2  s .  co m
    String tsType = System.getProperty("javax.net.ssl.trustStoreType", null);
    if ("Windows-ROOT".equals(tsType)) {
        try {
            ks = KeyStore.getInstance(tsType);
            ks.load(null, null);
            int numEntries = keyStoreAppendIndex(ks);
            logger.info(
                    "Using Windows-ROOT. Aliases sucessfully renamed on " + numEntries + " root certificates.");
        } catch (Exception e) {
            logger.error("Could not rename Windows-ROOT aliases", e);
        }
    }

    tmFactory.init(ks);
    for (TrustManager m : tmFactory.getTrustManagers()) {
        if (m instanceof X509TrustManager) {
            defaultTm = (X509TrustManager) m;
            break;
        }
    }
    if (defaultTm == null)
        throw new GeneralSecurityException("No default X509 trust manager found");

    final X509TrustManager tm = defaultTm;

    return new X509TrustManager() {
        private boolean serverCheck;

        public X509Certificate[] getAcceptedIssuers() {
            return tm.getAcceptedIssuers();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = true;
            checkCertTrusted(chain, authType);
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = false;
            checkCertTrusted(chain, authType);
        }

        private void checkCertTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // check and default configurations for property
            // if missing default is null - false
            String defaultAlwaysTrustMode = CertificateVerificationActivator.getResources()
                    .getSettingsString(CertificateService.PNAME_ALWAYS_TRUST);

            if (config.getBoolean(PNAME_ALWAYS_TRUST, Boolean.parseBoolean(defaultAlwaysTrustMode)))
                return;

            try {
                // check the certificate itself (issuer, validity)
                try {
                    chain = tryBuildChain(chain);
                } catch (Exception e) {
                } // don't care and take the chain as is

                if (serverCheck)
                    tm.checkServerTrusted(chain, authType);
                else
                    tm.checkClientTrusted(chain, authType);

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext())
                    return;
                else if (serverCheck)
                    serverVerifier.verify(identitiesToTest, chain[0]);
                else
                    clientVerifier.verify(identitiesToTest, chain[0]);

                // ok, globally valid cert
            } catch (CertificateException e) {
                String thumbprint = getThumbprint(chain[0], THUMBPRINT_HASH_ALGORITHM);
                String message = null;
                List<String> propNames = new LinkedList<String>();
                List<String> storedCerts = new LinkedList<String>();
                String appName = R.getSettingsString("service.gui.APPLICATION_NAME");

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext()) {
                    String propName = PNAME_CERT_TRUST_PREFIX + ".server." + thumbprint;
                    propNames.add(propName);

                    message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT_NOHOST",
                            new String[] { appName });

                    // get the thumbprints from the permanent allowances
                    String hashes = config.getString(propName);
                    if (hashes != null)
                        for (String h : hashes.split(","))
                            storedCerts.add(h);

                    // get the thumbprints from the session allowances
                    List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                    if (sessionCerts != null)
                        storedCerts.addAll(sessionCerts);
                } else {
                    if (serverCheck) {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    } else {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_PEER_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    }
                    for (String identity : identitiesToTest) {
                        String propName = PNAME_CERT_TRUST_PREFIX + ".param." + identity;
                        propNames.add(propName);

                        // get the thumbprints from the permanent allowances
                        String hashes = config.getString(propName);
                        if (hashes != null)
                            for (String h : hashes.split(","))
                                storedCerts.add(h);

                        // get the thumbprints from the session allowances
                        List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                        if (sessionCerts != null)
                            storedCerts.addAll(sessionCerts);
                    }
                }

                if (!storedCerts.contains(thumbprint)) {
                    switch (verify(chain, message)) {
                    case DO_NOT_TRUST:
                        logger.info("Untrusted certificate", e);
                        throw new CertificateException("The peer provided certificate with Subject <"
                                + chain[0].getSubjectDN() + "> is not trusted", e);
                    case TRUST_ALWAYS:
                        for (String propName : propNames) {
                            String current = config.getString(propName);
                            String newValue = thumbprint;
                            if (current != null)
                                newValue += "," + current;
                            config.setProperty(propName, newValue);
                        }
                        break;
                    case TRUST_THIS_SESSION_ONLY:
                        for (String propName : propNames)
                            getSessionCertEntry(propName).add(thumbprint);
                        break;
                    }
                }
                // ok, we've seen this certificate before
            }
        }

        private X509Certificate[] tryBuildChain(X509Certificate[] chain)
                throws IOException, URISyntaxException, CertificateException {
            // Only try to build chains for servers that send only their
            // own cert, but no issuer. This also matches self signed (will
            // be ignored later) and Root-CA signed certs. In this case we
            // throw the Root-CA away after the lookup
            if (chain.length != 1)
                return chain;

            // ignore self signed certs
            if (chain[0].getIssuerDN().equals(chain[0].getSubjectDN()))
                return chain;

            // prepare for the newly created chain
            List<X509Certificate> newChain = new ArrayList<X509Certificate>(chain.length + 4);
            for (X509Certificate cert : chain) {
                newChain.add(cert);
            }

            // search from the topmost certificate upwards
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate current = chain[chain.length - 1];
            boolean foundParent;
            int chainLookupCount = 0;
            do {
                foundParent = false;
                // extract the url(s) where the parent certificate can be
                // found
                byte[] aiaBytes = current.getExtensionValue(Extension.authorityInfoAccess.getId());
                if (aiaBytes == null)
                    break;

                AuthorityInformationAccess aia = AuthorityInformationAccess
                        .getInstance(X509ExtensionUtil.fromExtensionValue(aiaBytes));

                // the AIA may contain different URLs and types, try all
                // of them
                for (AccessDescription ad : aia.getAccessDescriptions()) {
                    // we are only interested in the issuer certificate,
                    // not in OCSP urls the like
                    if (!ad.getAccessMethod().equals(AccessDescription.id_ad_caIssuers))
                        continue;

                    GeneralName gn = ad.getAccessLocation();
                    if (!(gn.getTagNo() == GeneralName.uniformResourceIdentifier
                            && gn.getName() instanceof DERIA5String))
                        continue;

                    URI uri = new URI(((DERIA5String) gn.getName()).getString());
                    // only http(s) urls; LDAP is taken care of in the
                    // default implementation
                    if (!(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equals("https")))
                        continue;

                    X509Certificate cert = null;

                    // try to get cert from cache first to avoid consecutive
                    // (slow) http lookups
                    AiaCacheEntry cache = aiaCache.get(uri);
                    if (cache != null && cache.cacheDate.after(new Date())) {
                        cert = cache.cert;
                    } else {
                        // download if no cache entry or if it is expired
                        if (logger.isDebugEnabled())
                            logger.debug("Downloading parent certificate for <" + current.getSubjectDN()
                                    + "> from <" + uri + ">");
                        try {
                            InputStream is = HttpUtils.openURLConnection(uri.toString()).getContent();
                            cert = (X509Certificate) certFactory.generateCertificate(is);
                        } catch (Exception e) {
                            logger.debug("Could not download from <" + uri + ">");
                        }
                        // cache for 10mins
                        aiaCache.put(uri,
                                new AiaCacheEntry(new Date(new Date().getTime() + 10 * 60 * 1000), cert));
                    }
                    if (cert != null) {
                        if (!cert.getIssuerDN().equals(cert.getSubjectDN())) {
                            newChain.add(cert);
                            foundParent = true;
                            current = cert;
                            break; // an AD was valid, ignore others
                        } else
                            logger.debug("Parent is self-signed, ignoring");
                    }
                }
                chainLookupCount++;
            } while (foundParent && chainLookupCount < 10);
            chain = newChain.toArray(chain);
            return chain;
        }
    };
}

From source file:org.apache.juddi.webconsole.hub.UddiHub.java

/**
 * converts a UDDI Signature Type element into a base64 string
 * containing the raw data for the signing certificate, if present
 *
 * @param sig//  w  w  w .j a  va2  s . c o  m
 * @return x509 cert
 */
public String SignatureToBase64(SignatureType sig) {
    if (sig == null) {
        return "Error, the signature was nullavailable";
    }
    for (int i = 0; i < sig.getKeyInfo().getContent().size(); i++) {
        JAXBElement get = (JAXBElement) sig.getKeyInfo().getContent().get(i);

        if (get.getValue() instanceof org.w3._2000._09.xmldsig_.X509DataType) {
            X509DataType xd = (X509DataType) get.getValue();
            for (int k = 0; k < xd.getX509IssuerSerialOrX509SKIOrX509SubjectName().size(); k++) {
                if (xd.getX509IssuerSerialOrX509SKIOrX509SubjectName().get(k) instanceof JAXBElement) {
                    JAXBElement element = (JAXBElement) xd.getX509IssuerSerialOrX509SKIOrX509SubjectName()
                            .get(k);
                    if (element.getValue() instanceof byte[]) {
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            InputStream is = new ByteArrayInputStream((byte[]) element.getValue());
                            X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
                            is.close();
                            //this is the most supportable way to do this
                            return org.apache.commons.codec.binary.Base64.encodeBase64String(cert.getEncoded());
                            //BASE64Encoder encoder = new BASE64Encoder();
                            //return encoder.encodeBuffer(cert.getEncoded());

                        } catch (Exception ex) {
                            return HandleException(ex);
                        }
                    } else if (element.getValue() instanceof String) {
                    }
                }
            }
        }
    }
    return ResourceLoader.GetResource(session, "errors.nocertavaiable");
}

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;/*from   w w  w . ja  va2s . co m*/

    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 :)
    }
}

From source file:com.vmware.identity.idm.client.TenantManagementTest.java

private X509Certificate getCertificate(String certAlias) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf
            .generateCertificate(TenantManagementTest.class.getResourceAsStream(certAlias));

    return cert;//  ww  w.j  a v a2s. c  o  m
}