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:com.gamesalutes.utils.EncryptUtils.java

/**
 * Reads a DER-encoded certificate that uses binary or Base64 encoding from the given input stream.
 * //  w w  w. j a  va2  s.c  o  m
 * @param in the <code>InputStream</code>
 * @param certType
 * @return the read certificate
 * @throws CertificateException
 * @throws IOException
 */
public static java.security.cert.Certificate readCertificate(InputStream in, String certType)
        throws CertificateException, IOException {
    // get the raw certificate bytes so that can trim and format cert properly
    byte[] data = null;
    try {
        data = ByteUtils.readBytes(in);
        // in automatically closed during call to readBytes even in case of exceptions
        in = null;
    } catch (Exception e) {
        in = null;
        throw new ChainedIOException("Error getting stream bytes", e);
    }
    CertificateFactory cf = CertificateFactory.getInstance(certType);
    try {
        byte[] pemData = formatBase64ToPem(getRawBase64Key(data), BEGIN_CERTIFICATE, END_CERTIFICATE);
        in = new ByteArrayInputStream(pemData);
        return cf.generateCertificate(in);
    } catch (Exception e) {
        MiscUtils.closeStream(in);
        // maybe it was in binary DER and couldn't be read when it was assumed to be in Base64
        in = new ByteArrayInputStream(data);
        return cf.generateCertificate(in);
    } finally {
        MiscUtils.closeStream(in);
    }

}

From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java

private static SSLContext sslContext() {
    final String property = SettingsManager.settings().ssl();
    if (property != null && !property.isEmpty() && !"null".equals(property)) {
        if ("trustanything".equals(property)) {
            try {
                return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()),
                        new TrustStrategy() {
                            public boolean isTrusted(X509Certificate[] chain, String authType)
                                    throws CertificateException {
                                return true;
                            }/*from   ww w  .  j  av  a  2  s . c o  m*/
                        }).build();
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        } else {
            try {
                String location = property;
                location = location.equals("compatible")
                        ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt"
                        : location;
                File cachedPemFile = new File("./pemfile_cached");
                boolean remote = location.startsWith("https://") || location.startsWith("http://");
                if (remote && cachedPemFile.exists()
                        && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) {
                    location = cachedPemFile.getAbsolutePath();
                    remote = false;
                }
                String pemBlocks = null;
                if (remote) {
                    HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler
                            .defaultConnection(new URL(location));
                    remotePemFile.setRequestMethod("GET");
                    remotePemFile.connect();
                    pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile));
                    cachedPemFile.delete();
                    Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8"));
                } else {
                    pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())),
                            "utf-8");
                }
                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Matcher matcher = pemBlock.matcher(pemBlocks);
                boolean found = false;
                while (matcher.find()) {
                    String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", "");
                    ByteArrayInputStream byteStream = new ByteArrayInputStream(
                            Base64.getDecoder().decode(pemBlock));
                    java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf
                            .generateCertificate(byteStream);
                    String alias = cert.getSubjectX500Principal().getName("RFC2253");
                    if (alias != null && !keyStore.containsAlias(alias)) {
                        found = true;
                        keyStore.setCertificateEntry(alias, cert);
                    }
                }
                if (found) {
                    KeyManagerFactory keyManager = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManager.init(keyStore, null);
                    TrustManagerFactory trustManager = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    trustManager.init(keyStore);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
                    return context;
                }
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        }
    }
    return SSLContexts.createSystemDefault();
}

From source file:com.vangent.hieos.services.sts.util.STSUtil.java

/**
 *
 * @param base64Text/*from   w w  w .  ja v a2  s. co  m*/
 * @return
 * @throws STSException
 */
public static X509Certificate getCertificate(String base64Text) throws STSException {
    try {
        byte[] base64Bytes = base64Text.getBytes();
        byte[] decodedBytes = Base64.decodeBase64(base64Bytes);
        ByteArrayInputStream bs = new ByteArrayInputStream(decodedBytes);
        CertificateFactory cf;
        cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(bs);
        return cert;
    } catch (CertificateException ex) {
        throw new STSException("Unable to create X509Certificate: " + ex.getMessage());
    }
}

From source file:org.apache.hadoop.hdfsproxy.ProxyFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest rqst = (HttpServletRequest) request;
    HttpServletResponse rsp = (HttpServletResponse) response;

    if (LOG.isDebugEnabled()) {
        StringBuilder b = new StringBuilder("Request from ").append(rqst.getRemoteHost()).append("/")
                .append(rqst.getRemoteAddr()).append(":").append(rqst.getRemotePort());

        @SuppressWarnings("unchecked")
        Enumeration<String> e = rqst.getAttributeNames();
        for (; e.hasMoreElements();) {
            String attribute = e.nextElement();
            b.append("\n  " + attribute + " => " + rqst.getAttribute(attribute));
        }/*  ww w.  ja v  a  2  s.  c o  m*/

        X509Certificate[] userCerts = (X509Certificate[]) rqst
                .getAttribute("javax.servlet.request.X509Certificate");
        if (userCerts != null)
            for (X509Certificate cert : userCerts)
                b.append("\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName());

        b.append("\n The Scheme is " + rqst.getScheme());
        b.append("\n The Auth Type is " + rqst.getAuthType());
        b.append("\n The Path Info is " + rqst.getPathInfo());
        b.append("\n The Translated Path Info is " + rqst.getPathTranslated());
        b.append("\n The Context Path is " + rqst.getContextPath());
        b.append("\n The Query String is " + rqst.getQueryString());
        b.append("\n The Remote User is " + rqst.getRemoteUser());
        b.append("\n The User Principal is " + rqst.getUserPrincipal());
        b.append("\n The Request URI is " + rqst.getRequestURI());
        b.append("\n The Request URL is " + rqst.getRequestURL());
        b.append("\n The Servlet Path is " + rqst.getServletPath());

        LOG.debug(b.toString());
    }

    boolean unitTest = false;
    if (rqst.getScheme().equalsIgnoreCase("http") && rqst.getParameter("UnitTest") != null)
        unitTest = true;

    if (rqst.getScheme().equalsIgnoreCase("https") || unitTest) {
        boolean isAuthorized = false;
        X509Certificate[] certs = (X509Certificate[]) rqst
                .getAttribute("javax.servlet.request.X509Certificate");

        if (unitTest) {
            try {
                LOG.debug("==> Entering https unit test");
                String SslPath = rqst.getParameter("SslPath");
                InputStream inStream = new FileInputStream(SslPath);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
                inStream.close();
                certs = new X509Certificate[] { cert };
            } catch (Exception e) {
                // do nothing here
            }
        }

        if (certs == null || certs.length == 0) {
            rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received");
            LOG.info("No Client SSL certificate received");
            return;
        }
        for (X509Certificate cert : certs) {
            try {
                cert.checkValidity();
            } catch (CertificateExpiredException e) {
                LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired");
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired");
                return;
            } catch (CertificateNotYetValidException e) {
                LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " is not yet valid");
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid");
                return;
            }
        }

        String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*");
        String userID = null;
        for (String s : tokens) {
            if (s.startsWith("CN=")) {
                userID = s;
                break;
            }
        }
        if (userID == null || userID.length() < 4) {
            LOG.info("Can't retrieve user ID from SSL certificate");
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate");
            return;
        }
        userID = userID.substring(3);

        String servletPath = rqst.getServletPath();
        if (unitTest) {
            servletPath = rqst.getParameter("TestSevletPathInfo");
            LOG.info("this is for unit test purpose only");
        }

        if (HFTP_PATTERN.matcher(servletPath).matches()) {
            // request is an HSFTP request
            if (FILEPATH_PATTERN.matcher(servletPath).matches()) {
                // file path as part of the URL
                isAuthorized = checkPath(userID, certs[0],
                        rqst.getPathInfo() != null ? rqst.getPathInfo() : "/");
            } else {
                // file path is stored in "filename" parameter
                isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename"));
            }
        } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) {
            Configuration conf = new Configuration(false);
            conf.addResource("hdfsproxy-default.xml");
            Map<String, Set<Path>> permsMap = getPermMap(conf);
            Map<String, Set<BigInteger>> certsMap = getCertsMap(conf);
            if (permsMap == null || certsMap == null) {
                LOG.warn("Permission files reloading failed");
                rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Permission files reloading failed");
                return;
            }
            ProxyFilter.permsMap = permsMap;
            ProxyFilter.certsMap = certsMap;
            LOG.info("User permissions and user certs files reloaded");
            rsp.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        if (!isAuthorized) {
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access");
            return;
        }

        // request is authorized, set ugi for servlets
        UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userID);
        rqst.setAttribute("authorized.ugi", ugi);
        rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", userID);
    } else if (rqst.getScheme().equalsIgnoreCase("http")) { // http request, set ugi for servlets, only for testing purposes
        String ugi = rqst.getParameter("ugi");
        if (ugi != null) {
            rqst.setAttribute("authorized.ugi", UserGroupInformation.createRemoteUser(ugi));
            rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", ugi.split(",")[0]);
        }
    }
    chain.doFilter(request, response);
}

From source file:org.opensaml.xml.security.x509.X509Util.java

/**
 * Decodes CRLS in DER or PKCS#7 format. If in PKCS#7 format only the CRLs are decode, the rest of the content is
 * ignored.//  w  w w . j av  a2 s  .  c om
 * 
 * @param crls encoded CRLs
 * 
 * @return decoded CRLs
 * 
 * @throws CRLException thrown if the CRLs can not be decoded
 */
@SuppressWarnings("unchecked")
public static Collection<X509CRL> decodeCRLs(byte[] crls) throws CRLException {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        return (Collection<X509CRL>) cf.generateCRLs(new ByteArrayInputStream(crls));
    } catch (GeneralSecurityException e) {
        throw new CRLException("Unable to decode X.509 certificates");
    }
}

From source file:org.bitrepository.protocol.security.PermissionStore.java

private X509Certificate makeCertificate(byte[] certificateData) throws CertificateException {
    ByteArrayInputStream bs = new ByteArrayInputStream(certificateData);
    X509Certificate certificate = (X509Certificate) CertificateFactory
            .getInstance(SecurityModuleConstants.CertificateType).generateCertificate(bs);
    try {// ww  w.  ja va 2s  .  c  o  m
        bs.close();
    } catch (IOException e) {
        log.debug("Failed to close ByteArrayInputStream", e);
    }
    return certificate;
}

From source file:com.microsoft.windowsazure.services.media.samples.contentprotection.playreadywidevine.Program.java

public static ContentKeyInfo createCommonTypeContentKey(AssetInfo asset) {
    try {/*from w  w  w  .  ja  v a 2 s .c  o  m*/
        // Get the protection key id for ContentKey
        String protectionKeyId = mediaService
                .action(ProtectionKey.getProtectionKeyId(ContentKeyType.CommonEncryption));

        // Download and create the X509 certificate
        String protectionKey = mediaService.action(ProtectionKey.getProtectionKey(protectionKeyId));
        X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(Base64.decode(protectionKey)));

        // Create a new ContentKey (secure random)
        byte[] contentKeyData = new byte[16];
        EncryptionUtils.eraseKey(contentKeyData);

        // Encrypt ContentKey
        byte[] encryptedContentKey = EncryptionUtils.encryptSymmetricKeyData(certificate, contentKeyData);
        String encryptedContentKeyString = Base64.encode(encryptedContentKey);

        // Create the ContentKey Id
        UUID contentKeyIdUuid = UUID.randomUUID();
        String contentKeyId = String.format("nb:kid:UUID:%s", contentKeyIdUuid.toString());

        // Calculate the checksum
        String checksum = EncryptionUtils.calculateChecksum(contentKeyData, contentKeyIdUuid);

        // Create the ContentKey entity
        ContentKeyInfo contentKey = mediaService.create(
                ContentKey.create(contentKeyId, ContentKeyType.CommonEncryption, encryptedContentKeyString)
                        .setChecksum(checksum).setProtectionKeyType(ProtectionKeyType.X509CertificateThumbprint)
                        .setName("Common Encryption Content Key")
                        .setProtectionKeyId(EncryptionUtils.getThumbPrint(certificate)));

        // Associate the ContentKey with the Asset
        mediaService.action(Asset.linkContentKey(asset.getId(), contentKeyId));

        return contentKey;

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    return null;
}

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

/**
 * @param request// w w w . j a v a 2s.co m
 * @throws DAOException
 * @throws IOException
 */
private void updatePartnership(Hashtable ht, HttpServletRequest request, PropertyTree dom)
        throws DAOException, IOException {

    // get the parameters
    String requestAction = (String) ht.get("request_action");

    String partnershipId = (String) ht.get("partnership_id");
    String cpaId = (String) ht.get("cpa_id");
    String service = (String) ht.get("service");
    String action = (String) ht.get("action_id");

    String transportEndpoint = (String) ht.get("transport_endpoint");
    String isHostnameVerified = (String) ht.get("is_hostname_verified");
    String syncReplyMode = (String) ht.get("sync_reply_mode");
    String ackRequested = (String) ht.get("ack_requested");
    String ackSignRequested = (String) ht.get("ack_sign_requested");
    String dupElimination = (String) ht.get("dup_elimination");
    String messageOrder = (String) ht.get("message_order");

    String disabled = (String) ht.get("disabled");
    String retries = (String) ht.get("retries");
    String retryInterval = (String) ht.get("retry_interval");

    String signRequested = (String) ht.get("sign_requested");
    String encryptRequested = (String) ht.get("encrypt_requested");

    boolean hasEncryptCert = ht.get("encrypt_cert") != null;
    InputStream encryptCertInputStream = null;
    if (hasEncryptCert) {
        encryptCertInputStream = (InputStream) ht.get("encrypt_cert");
    }
    boolean hasRemoveEncryptCert = false;
    if (ht.get("encrypt_cert_remove") != null) {
        if (((String) ht.get("encrypt_cert_remove")).equalsIgnoreCase("on")) {
            hasRemoveEncryptCert = true;
        }
    }
    boolean hasVerifyCert = ht.get("verify_cert") != null;
    InputStream verifyCertInputStream = null;
    if (hasVerifyCert) {
        verifyCertInputStream = (InputStream) ht.get("verify_cert");
    }
    boolean hasRemoveVerifyCert = false;
    if (ht.get("verify_cert_remove") != null) {
        if (((String) ht.get("verify_cert_remove")).equalsIgnoreCase("on")) {
            hasRemoveVerifyCert = true;
        }
    }

    if ("add".equalsIgnoreCase(requestAction) || "update".equalsIgnoreCase(requestAction)
            || "delete".equalsIgnoreCase(requestAction)) {

        // validate and set to dao
        PartnershipDAO partnershipDAO = (PartnershipDAO) EbmsProcessor.core.dao.createDAO(PartnershipDAO.class);
        PartnershipDVO partnershipDVO = (PartnershipDVO) partnershipDAO.createDVO();

        partnershipDVO.setPartnershipId(partnershipId);

        if ("update".equalsIgnoreCase(requestAction)) {
            partnershipDAO.retrieve(partnershipDVO);
        }

        partnershipDVO.setCpaId(cpaId);
        partnershipDVO.setService(service);
        partnershipDVO.setAction(action);
        partnershipDVO.setTransportEndpoint(transportEndpoint);
        partnershipDVO.setIsHostnameVerified(isHostnameVerified);
        partnershipDVO.setSyncReplyMode(syncReplyMode);
        partnershipDVO.setAckRequested(ackRequested);
        partnershipDVO.setAckSignRequested(ackSignRequested);
        partnershipDVO.setDupElimination(dupElimination);
        partnershipDVO.setActor(null);
        partnershipDVO.setDisabled(disabled);
        partnershipDVO.setRetries(StringUtilities.parseInt(retries));
        partnershipDVO.setRetryInterval(StringUtilities.parseInt(retryInterval));
        partnershipDVO.setPersistDuration(null);
        partnershipDVO.setMessageOrder(messageOrder);
        partnershipDVO.setSignRequested(signRequested);
        partnershipDVO.setDsAlgorithm(null);
        partnershipDVO.setMdAlgorithm(null);
        partnershipDVO.setEncryptRequested(encryptRequested);
        partnershipDVO.setEncryptAlgorithm(null);

        if ("add".equalsIgnoreCase(requestAction)) {
            getPartnership(partnershipDVO, dom, "add_partnership/");
        }

        if (!cpaId.equals("")) {
            partnershipDVO.setCpaId(cpaId);
        } else {
            request.setAttribute(ATTR_MESSAGE, "CPA ID cannot be empty");
            return;
        }

        if (!service.equals("")) {
            partnershipDVO.setService(service);
        } else {
            request.setAttribute(ATTR_MESSAGE, "Service cannot be empty");
            return;
        }

        if (!action.equals("")) {
            partnershipDVO.setAction(action);
        } else {
            request.setAttribute(ATTR_MESSAGE, "Action cannot be empty");
            return;
        }

        URL transportEndpointURL = null;
        try {
            transportEndpointURL = new URL(transportEndpoint);
        } catch (Exception e) {
            request.setAttribute(ATTR_MESSAGE, "Transport Endpoint is invalid");
            return;
        }
        if (transportEndpointURL.getProtocol().equalsIgnoreCase("mailto")) {
            partnershipDVO.setTransportProtocol("smtp");
        } else if (transportEndpointURL.getProtocol().equalsIgnoreCase("http")
                || transportEndpointURL.getProtocol().equalsIgnoreCase("https")) {
            partnershipDVO.setTransportProtocol(transportEndpointURL.getProtocol());
        } else {
            request.setAttribute(ATTR_MESSAGE, "The endpoint protocol does not support");
            return;
        }

        if (partnershipDVO.getRetries() == Integer.MIN_VALUE) {
            request.setAttribute(ATTR_MESSAGE, "Retries must be integer");
            return;
        }
        if (partnershipDVO.getRetryInterval() == Integer.MIN_VALUE) {
            request.setAttribute(ATTR_MESSAGE, "Retry Interval must be integer");
            return;
        }

        // encrypt cert
        if (hasRemoveEncryptCert) {
            partnershipDVO.setEncryptCert(null);
        }
        if (hasEncryptCert) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOHandler.pipe(encryptCertInputStream, baos);
                CertificateFactory.getInstance("X.509")
                        .generateCertificate(new ByteArrayInputStream(baos.toByteArray()));
                partnershipDVO.setEncryptCert(baos.toByteArray());
            } catch (Exception e) {
                request.setAttribute(ATTR_MESSAGE, "Uploaded encrypt cert is not an X.509 cert");
                return;
            }
        }

        // verify cert
        if (hasRemoveVerifyCert) {
            partnershipDVO.setSignCert(null);
        }
        if (hasVerifyCert) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOHandler.pipe(verifyCertInputStream, baos);
                CertificateFactory.getInstance("X.509")
                        .generateCertificate(new ByteArrayInputStream(baos.toByteArray()));
                partnershipDVO.setSignCert(baos.toByteArray());
            } catch (Exception e) {
                request.setAttribute(ATTR_MESSAGE, "Uploaded verify cert is not an X.509 cert");
                return;
            }
        }

        // check partnership conflict
        if (!Boolean.valueOf(partnershipDVO.getDisabled()).booleanValue()) {
            Iterator allConflictDAOData = partnershipDAO.findPartnershipsByCPA(partnershipDVO).iterator();
            while (allConflictDAOData.hasNext()) {
                PartnershipDVO conflictDAOData = (PartnershipDVO) allConflictDAOData.next();
                if (conflictDAOData != null
                        && !conflictDAOData.getPartnershipId().equals(partnershipDVO.getPartnershipId())
                        && !Boolean.valueOf(conflictDAOData.getDisabled()).booleanValue()) {
                    request.setAttribute(ATTR_MESSAGE, "Partnership '" + conflictDAOData.getPartnershipId()
                            + "' with same combination of CPA ID, Service and Action has already been enabled");
                    return;
                }
            }
        }

        // dao action
        if ("add".equalsIgnoreCase(requestAction)) {
            partnershipDAO.create(partnershipDVO);
            request.setAttribute(ATTR_MESSAGE, "Partnership added successfully");
            dom.removeProperty("/partnerships/add_partnership");
            dom.setProperty("/partnerships/add_partnership", "");
        }
        if ("update".equalsIgnoreCase(requestAction)) {
            partnershipDAO.persist(partnershipDVO);
            request.setAttribute(ATTR_MESSAGE, "Partnership updated successfully");
        }
        if ("delete".equalsIgnoreCase(requestAction)) {

            partnershipDAO.remove(partnershipDVO);
            request.setAttribute(ATTR_MESSAGE, "Partnership deleted successfully");
        }

    }
}

From source file:com.blackducksoftware.integration.hub.jenkins.site.BlackDuckHubUpdateSite.java

/**
 * Verifies the signature in the update center data file.
 *//*  www . j ava 2s . c  o  m*/
private FormValidation verifySignature(final JSONObject o) throws IOException {
    try {
        FormValidation warning = null;

        final JSONObject signature = o.getJSONObject("signature");
        if (signature.isNullObject()) {
            return FormValidation.error("No signature block found in update center '" + getId() + "'");
        }
        o.remove("signature");

        final List<X509Certificate> certs = new ArrayList<X509Certificate>();
        {// load and verify certificates
            final CertificateFactory cf = CertificateFactory.getInstance("X509");
            for (final Object cert : signature.getJSONArray("certificates")) {
                final X509Certificate c = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
                try {
                    c.checkValidity();
                } catch (final CertificateExpiredException e) { // even if the certificate isn't valid yet,
                    // we'll proceed it anyway
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s has expired in update center '%s'", cert.toString(), getId()));
                } catch (final CertificateNotYetValidException e) {
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId()));
                }
                certs.add(c);
            }

            // all default root CAs in JVM are trusted, plus certs bundled in Jenkins
            final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
            final ServletContext context = Jenkins.getInstance().servletContext;
            anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null));
            for (final String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
                if (cert.endsWith(".txt")) {
                    continue; // skip text files that are meant to be documentation
                }
                final InputStream stream = context.getResourceAsStream(cert);
                if (stream != null) {
                    try {
                        anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
                    } finally {
                        IOUtils.closeQuietly(stream);
                    }
                }
            }
            CertificateUtil.validatePath(certs, anchors);
        }

        // this is for computing a digest to check sanity
        final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        final DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

        // this is for computing a signature
        final Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(certs.get(0));
        final SignatureOutputStream sos = new SignatureOutputStream(sig);

        // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature)
        // that only covers the earlier portion of the file. This was caused by the lack of close() call
        // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to
        // the digest output stream. This affects Jenkins [1.424,1,431].
        // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it
        // compute the correct digest, but it breaks all the existing UC json metadata out there. We then
        // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature,
        // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*).
        //
        // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature"
        // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated
        // correctly.
        //
        // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows
        // the attacker to inject a fragment at the end of the json.
        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close();

        // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
        // (which is more likely than someone tampering with update center), we can tell
        final String computedDigest = new String(Base64.encode(sha1.digest()));
        final String providedDigest = signature.optString("correct_digest");
        if (providedDigest == null) {
            return FormValidation.error("No correct_digest parameter in update center '" + getId()
                    + "'. This metadata appears to be old.");
        }
        if (!computedDigest.equalsIgnoreCase(providedDigest)) {
            return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest
                    + " in update center '" + getId() + "'");
        }

        final String providedSignature = signature.getString("correct_signature");
        if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) {
            return FormValidation.error(
                    "Signature in the update center doesn't match with the certificate in update center '"
                            + getId() + "'");
        }

        if (warning != null) {
            return warning;
        }
        return FormValidation.ok();
    } catch (final GeneralSecurityException e) {
        return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'");
    }
}

From source file:com.google.appengine.tck.appidentity.AppIdentityServiceTest.java

private boolean verifySignatureWithAllCertsForApp(byte[] blob, byte[] signedBlob,
        Collection<PublicCertificate> certsForApp) {

    if (certsForApp.isEmpty()) {
        throw new IllegalStateException("No certificates to validate.  Must have at least 1.");
    }//ww w  .j a  v  a 2 s. co m
    int currentCertNum = 0;
    int totalValid = 0;
    int totalInvalid = 0;
    List<Exception> allExceptions = new ArrayList<>();

    for (PublicCertificate publicCert : certsForApp) {
        Signature signature;
        Certificate cert = null;
        currentCertNum++;

        log.info("Processing certNum:" + currentCertNum);
        try {
            byte[] certBytes = publicCert.getX509CertificateInPemFormat().getBytes("UTF-8");
            InputStream stream = new ByteArrayInputStream(certBytes);
            signature = Signature.getInstance("SHA256withRSA"); // Make this configurable?
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            cert = cf.generateCertificate(stream);
            log.info(cert.toString());

            PublicKey pk = cert.getPublicKey();
            signature.initVerify(pk);
            signature.update(blob);
            boolean isValidSignature = signature.verify(signedBlob);

            if (isValidSignature) {
                totalValid++;
            } else {
                totalInvalid++;
            }
            log.info("certNum:" + currentCertNum + ": is valid:" + isValidSignature);

            // These can be thrown:
            // UnsupportedEncodingException, NoSuchAlgorithmException, CertificateException,
            // SignatureException, InvalidKeyException
        } catch (Exception e) {
            Exception logException = createExceptionForLog(e, currentCertNum, cert);
            allExceptions.add(logException);
            log.info(e.toString());
        }
    }
    String summary = "totalCerts:" + certsForApp.size() + ": totalValid:" + totalValid + " totalInvalid:"
            + totalInvalid + " totalExceptions:" + allExceptions.size();
    log.info(summary);

    // At least one certificate caused an exception so make test Error.
    if (allExceptions.size() > 0) {
        throw new IllegalStateException(summary + "\n\n" + exceptionListToString(allExceptions));
    }

    // At least one signature was valid and no exceptions thrown.
    return (totalValid > 0);
}