Search in sources :

Example 1 with PemWriter

use of org.bouncycastle.util.io.pem.PemWriter in project Openfire by igniterealtime.

the class CertificateManager method createSigningRequest.

/**
     * Creates and returns the content of a new singing request for the specified certificate. Signing
     * requests are required by Certificate Authorities as part of their signing process. The signing request
     * contains information about the certificate issuer, subject DN, subject alternative names and public key.
     * Private keys are not included. After the Certificate Authority verified and signed the certificate a new
     * certificate is going to be returned. Use {@link #installReply(java.security.KeyStore, java.security.KeyStore, char[], String, java.io.InputStream)}
     * to import the CA reply.
     *
     * @param cert the certificate to create a signing request.
     * @param privKey the private key of the certificate.
     * @return the content of a new singing request for the specified certificate.
     */
public static String createSigningRequest(X509Certificate cert, PrivateKey privKey) throws OperatorCreationException, IOException {
    JcaPKCS10CertificationRequestBuilder csrBuilder = new //
    JcaPKCS10CertificationRequestBuilder(//
    cert.getSubjectX500Principal(), //
    cert.getPublicKey());
    String signatureAlgorithm = "SHA256WITH" + cert.getPublicKey().getAlgorithm();
    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privKey);
    PKCS10CertificationRequest csr = csrBuilder.build(signer);
    StringWriter string = new StringWriter();
    PemWriter pemWriter = new PemWriter(string);
    PemObjectGenerator objGen = new MiscPEMGenerator(csr);
    pemWriter.writeObject(objGen);
    pemWriter.close();
    return string.toString();
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) MiscPEMGenerator(org.bouncycastle.openssl.MiscPEMGenerator) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PemObjectGenerator(org.bouncycastle.util.io.pem.PemObjectGenerator) StringWriter(java.io.StringWriter) PemWriter(org.bouncycastle.util.io.pem.PemWriter) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner)

Example 2 with PemWriter

use of org.bouncycastle.util.io.pem.PemWriter in project neo4j by neo4j.

the class Certificates method writePem.

private void writePem(String type, byte[] encodedContent, File path) throws IOException {
    path.getParentFile().mkdirs();
    try (PemWriter writer = new PemWriter(new FileWriter(path))) {
        writer.writeObject(new PemObject(type, encodedContent));
        writer.flush();
    }
    path.setReadable(false, false);
    path.setWritable(false, false);
    path.setReadable(true);
    path.setWritable(true);
}
Also used : PemObject(org.bouncycastle.util.io.pem.PemObject) PemWriter(org.bouncycastle.util.io.pem.PemWriter) FileWriter(java.io.FileWriter)

Example 3 with PemWriter

use of org.bouncycastle.util.io.pem.PemWriter in project gocd by gocd.

the class RegistrationJSONizer method serialize.

private static String serialize(String type, byte[] data) {
    PemObject obj = new PemObject(type, data);
    StringWriter out = new StringWriter();
    PemWriter writer = new PemWriter(out);
    try {
        writer.writeObject(obj);
    } catch (IOException e) {
        throw bomb(e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
    return out.toString();
}
Also used : PemObject(org.bouncycastle.util.io.pem.PemObject) StringWriter(java.io.StringWriter) PemWriter(org.bouncycastle.util.io.pem.PemWriter) IOException(java.io.IOException)

Example 4 with PemWriter

use of org.bouncycastle.util.io.pem.PemWriter in project zaproxy by zaproxy.

the class CoreAPI method handleApiOther.

@Override
public HttpMessage handleApiOther(HttpMessage msg, String name, JSONObject params) throws ApiException {
    if (OTHER_PROXY_PAC.equals(name)) {
        final ProxyParam proxyParam = Model.getSingleton().getOptionsParam().getProxyParam();
        final int port = proxyParam.getProxyPort();
        try {
            String domain = null;
            if (proxyParam.isProxyIpAnyLocalAddress()) {
                String localDomain = msg.getRequestHeader().getHostName();
                if (!API.API_DOMAIN.equals(localDomain)) {
                    domain = localDomain;
                }
            }
            if (domain == null) {
                domain = proxyParam.getProxyIp();
            }
            String response = this.getPacFile(domain, port);
            msg.setResponseHeader(API.getDefaultResponseHeader("text/html", response.length()));
            msg.setResponseBody(response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return msg;
    } else if (OTHER_SET_PROXY.equals(name)) {
        /* JSON string:
			 *  {"type":1,
			 *  "http":	{"host":"proxy.corp.com","port":80},
			 *  "ssl":	{"host":"proxy.corp.com","port":80},
			 *  "ftp":{"host":"proxy.corp.com","port":80},
			 *  "socks":{"host":"proxy.corp.com","port":80},
			 *  "shareSettings":true,"socksVersion":5,
			 *  "proxyExcludes":"localhost, 127.0.0.1"}
			 */
        String proxyDetails = params.getString(PARAM_PROXY_DETAILS);
        String response = "OK";
        try {
            try {
                JSONObject json = JSONObject.fromObject(proxyDetails);
                if (json.getInt("type") == 1) {
                    JSONObject httpJson = JSONObject.fromObject(json.get("http"));
                    String proxyHost = httpJson.getString("host");
                    int proxyPort = httpJson.getInt("port");
                    if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
                        Model.getSingleton().getOptionsParam().getConnectionParam().setProxyChainName(proxyHost);
                        Model.getSingleton().getOptionsParam().getConnectionParam().setProxyChainPort(proxyPort);
                    }
                }
            } catch (JSONException e) {
                throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_PROXY_DETAILS);
            }
            msg.setResponseHeader(API.getDefaultResponseHeader("text/html", response.length()));
            msg.setResponseBody(response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return msg;
    } else if (OTHER_ROOT_CERT.equals(name)) {
        ExtensionDynSSL extDynSSL = (ExtensionDynSSL) Control.getSingleton().getExtensionLoader().getExtension(ExtensionDynSSL.EXTENSION_ID);
        if (extDynSSL != null) {
            try {
                Certificate rootCA = extDynSSL.getRootCA();
                if (rootCA == null) {
                    throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
                }
                final StringWriter sw = new StringWriter();
                try (final PemWriter pw = new PemWriter(sw)) {
                    pw.writeObject(new JcaMiscPEMGenerator(rootCA));
                    pw.flush();
                }
                String response = sw.toString();
                msg.setResponseHeader(API.getDefaultResponseHeader("application/pkix-cert;", response.length()));
                msg.setResponseBody(response);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new ApiException(ApiException.Type.INTERNAL_ERROR);
            }
        } else {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
        }
        return msg;
    } else if (OTHER_XML_REPORT.equals(name)) {
        try {
            writeReportLastScanTo(msg, ScanReportType.XML);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ApiException(ApiException.Type.INTERNAL_ERROR);
        }
    } else if (OTHER_HTML_REPORT.equals(name)) {
        try {
            writeReportLastScanTo(msg, ScanReportType.HTML);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ApiException(ApiException.Type.INTERNAL_ERROR);
        }
    } else if (OTHER_MD_REPORT.equals(name)) {
        try {
            writeReportLastScanTo(msg, ScanReportType.MD);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ApiException(ApiException.Type.INTERNAL_ERROR);
        }
    } else if (OTHER_MESSAGE_HAR.equals(name)) {
        byte[] responseBody;
        try {
            final HarEntries entries = new HarEntries();
            TableHistory tableHistory = Model.getSingleton().getDb().getTableHistory();
            RecordHistory recordHistory;
            try {
                recordHistory = tableHistory.read(this.getParam(params, PARAM_ID, -1));
            } catch (HttpMalformedHeaderException | DatabaseException e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR);
            }
            if (recordHistory == null || recordHistory.getHistoryType() == HistoryReference.TYPE_TEMPORARY) {
                throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
            }
            entries.addEntry(HarUtils.createHarEntry(recordHistory.getHttpMessage()));
            HarLog harLog = HarUtils.createZapHarLog();
            harLog.setEntries(entries);
            responseBody = HarUtils.harLogToByteArray(harLog);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ApiException apiException = new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
        }
        try {
            msg.setResponseHeader(API.getDefaultResponseHeader("application/json; charset=UTF-8", responseBody.length));
        } catch (HttpMalformedHeaderException e) {
            logger.error("Failed to create response header: " + e.getMessage(), e);
        }
        msg.setResponseBody(responseBody);
        return msg;
    } else if (OTHER_MESSAGES_HAR.equals(name)) {
        byte[] responseBody;
        try {
            final HarEntries entries = new HarEntries();
            processHttpMessages(this.getParam(params, PARAM_BASE_URL, (String) null), this.getParam(params, PARAM_START, -1), this.getParam(params, PARAM_COUNT, -1), new Processor<RecordHistory>() {

                @Override
                public void process(RecordHistory recordHistory) {
                    entries.addEntry(HarUtils.createHarEntry(recordHistory.getHttpMessage()));
                }
            });
            HarLog harLog = HarUtils.createZapHarLog();
            harLog.setEntries(entries);
            responseBody = HarUtils.harLogToByteArray(harLog);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ApiException apiException = new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
        }
        try {
            msg.setResponseHeader(API.getDefaultResponseHeader("application/json; charset=UTF-8", responseBody.length));
        } catch (HttpMalformedHeaderException e) {
            logger.error("Failed to create response header: " + e.getMessage(), e);
        }
        msg.setResponseBody(responseBody);
        return msg;
    } else if (OTHER_SEND_HAR_REQUEST.equals(name)) {
        byte[] responseBody = {};
        HttpMessage request = null;
        try {
            request = HarUtils.createHttpMessage(params.getString(PARAM_REQUEST));
        } catch (IOException e) {
            ApiException apiException = new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_REQUEST, e);
            responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
        }
        if (request != null) {
            if (!isValidForCurrentMode(request.getRequestHeader().getURI())) {
                ApiException apiException = new ApiException(ApiException.Type.MODE_VIOLATION);
                responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
            } else {
                boolean followRedirects = getParam(params, PARAM_FOLLOW_REDIRECTS, false);
                try {
                    final HarEntries entries = new HarEntries();
                    sendRequest(request, followRedirects, new Processor<HttpMessage>() {

                        @Override
                        public void process(HttpMessage msg) {
                            entries.addEntry(HarUtils.createHarEntry(msg));
                        }
                    });
                    HarLog harLog = HarUtils.createZapHarLog();
                    harLog.setEntries(entries);
                    responseBody = HarUtils.harLogToByteArray(harLog);
                } catch (ApiException e) {
                    responseBody = e.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    ApiException apiException = new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
                    responseBody = apiException.toString(API.Format.JSON, incErrorDetails()).getBytes(StandardCharsets.UTF_8);
                }
            }
        }
        try {
            msg.setResponseHeader(API.getDefaultResponseHeader("application/json; charset=UTF-8", responseBody.length));
        } catch (HttpMalformedHeaderException e) {
            logger.error("Failed to create response header: " + e.getMessage(), e);
        }
        msg.setResponseBody(responseBody);
        return msg;
    } else if (OTHER_SCRIPT_JS.equals(name)) {
        try {
            msg.setResponseBody(API_SCRIPT);
            // Allow caching
            msg.setResponseHeader(API.getDefaultResponseHeader("text/javascript", API_SCRIPT.length(), true));
            msg.getResponseHeader().addHeader(HttpResponseHeader.CACHE_CONTROL, API_SCRIPT_CACHE_CONTROL);
        } catch (HttpMalformedHeaderException e) {
            logger.error("Failed to create response header: " + e.getMessage(), e);
        }
        return msg;
    } else {
        throw new ApiException(ApiException.Type.BAD_OTHER);
    }
}
Also used : ExtensionDynSSL(org.zaproxy.zap.extension.dynssl.ExtensionDynSSL) JcaMiscPEMGenerator(org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator) StringWriter(java.io.StringWriter) ProxyParam(org.parosproxy.paros.core.proxy.ProxyParam) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) RecordHistory(org.parosproxy.paros.db.RecordHistory) HarEntries(edu.umass.cs.benchlab.har.HarEntries) HarLog(edu.umass.cs.benchlab.har.HarLog) PemWriter(org.bouncycastle.util.io.pem.PemWriter) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) URIException(org.apache.commons.httpclient.URIException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) PatternSyntaxException(java.util.regex.PatternSyntaxException) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) DatabaseException(org.parosproxy.paros.db.DatabaseException) JSONObject(net.sf.json.JSONObject) TableHistory(org.parosproxy.paros.db.TableHistory) HttpMessage(org.parosproxy.paros.network.HttpMessage) DatabaseException(org.parosproxy.paros.db.DatabaseException) Certificate(java.security.cert.Certificate)

Example 5 with PemWriter

use of org.bouncycastle.util.io.pem.PemWriter in project zaproxy by zaproxy.

the class DynamicSSLPanel method setRootca.

private void setRootca(KeyStore rootca) {
    this.rootca = rootca;
    final StringWriter sw = new StringWriter();
    if (rootca != null) {
        try {
            final Certificate cert = rootca.getCertificate(SslCertificateService.ZAPROXY_JKS_ALIAS);
            try (final PemWriter pw = new PemWriter(sw)) {
                pw.writeObject(new JcaMiscPEMGenerator(cert));
                pw.flush();
            }
        } catch (final Exception e) {
            logger.error("Error while extracting public part from generated Root CA certificate.", e);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Certificate defined.\n" + sw.toString());
    }
    txt_PubCert.setText(sw.toString());
}
Also used : JcaMiscPEMGenerator(org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator) StringWriter(java.io.StringWriter) PemWriter(org.bouncycastle.util.io.pem.PemWriter) IOException(java.io.IOException) Certificate(java.security.cert.Certificate)

Aggregations

PemWriter (org.bouncycastle.util.io.pem.PemWriter)8 StringWriter (java.io.StringWriter)7 IOException (java.io.IOException)5 PemObject (org.bouncycastle.util.io.pem.PemObject)5 Certificate (java.security.cert.Certificate)4 JcaMiscPEMGenerator (org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator)2 com.citrix.netscaler.nitro.resource.config.basic.server_service_binding (com.citrix.netscaler.nitro.resource.config.basic.server_service_binding)1 com.citrix.netscaler.nitro.resource.config.gslb.gslbservice (com.citrix.netscaler.nitro.resource.config.gslb.gslbservice)1 com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver (com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver)1 com.citrix.netscaler.nitro.resource.config.lb.lbvserver (com.citrix.netscaler.nitro.resource.config.lb.lbvserver)1 com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding)1 com.citrix.netscaler.nitro.resource.config.ns.nsconfig (com.citrix.netscaler.nitro.resource.config.ns.nsconfig)1 com.citrix.netscaler.nitro.service.nitro_service (com.citrix.netscaler.nitro.service.nitro_service)1 Answer (com.cloud.agent.api.Answer)1 ExternalNetworkResourceUsageAnswer (com.cloud.agent.api.ExternalNetworkResourceUsageAnswer)1 MaintainAnswer (com.cloud.agent.api.MaintainAnswer)1 ReadyAnswer (com.cloud.agent.api.ReadyAnswer)1 GlobalLoadBalancerConfigAnswer (com.cloud.agent.api.routing.GlobalLoadBalancerConfigAnswer)1 HealthCheckLBConfigAnswer (com.cloud.agent.api.routing.HealthCheckLBConfigAnswer)1 IpAssocAnswer (com.cloud.agent.api.routing.IpAssocAnswer)1