Example usage for org.bouncycastle.util.encoders Base64 encode

List of usage examples for org.bouncycastle.util.encoders Base64 encode

Introduction

In this page you can find the example usage for org.bouncycastle.util.encoders Base64 encode.

Prototype

public static byte[] encode(byte[] data) 

Source Link

Document

encode the input data producing a base 64 encoded byte array.

Usage

From source file:org.signserver.client.cli.defaultimpl.HTTPDocumentSigner.java

License:Open Source License

private Response sendRequest(final URL processServlet, final byte[] data,
        final Map<String, Object> requestContext) throws IOException {

    OutputStream out = null;//from  w w w  . ja va2 s. c  o  m
    InputStream in = null;
    try {
        final HttpURLConnection conn = (HttpURLConnection) processServlet.openConnection();
        conn.setDoOutput(true);
        conn.setAllowUserInteraction(false);

        if (username != null && password != null) {
            conn.setRequestProperty(BASICAUTH_AUTHORIZATION,
                    BASICAUTH_BASIC + " " + new String(Base64.encode((username + ":" + password).getBytes())));
        }

        final StringBuilder sb = new StringBuilder();
        sb.append("--" + BOUNDARY);
        sb.append(CRLF);

        if (workerName == null) {
            sb.append("Content-Disposition: form-data; name=\"workerId\"");
            sb.append(CRLF);
            sb.append(CRLF);
            sb.append(workerId);
        } else {
            sb.append("Content-Disposition: form-data; name=\"workerName\"");
            sb.append(CRLF);
            sb.append(CRLF);
            sb.append(workerName);
        }
        sb.append(CRLF);

        if (pdfPassword != null) {
            sb.append("--" + BOUNDARY).append(CRLF)
                    .append("Content-Disposition: form-data; name=\"pdfPassword\"").append(CRLF).append(CRLF)
                    .append(pdfPassword).append(CRLF);
        }

        if (metadata != null) {
            for (final String key : metadata.keySet()) {
                final String value = metadata.get(key);

                sb.append("--" + BOUNDARY).append(CRLF)
                        .append("Content-Disposition: form-data; name=\"REQUEST_METADATA." + key + "\"")
                        .append(CRLF).append(CRLF).append(value).append(CRLF);
            }
        }

        sb.append("--" + BOUNDARY);
        sb.append(CRLF);
        sb.append("Content-Disposition: form-data; name=\"datafile\"");
        sb.append("; filename=\"");
        if (requestContext.get("FILENAME") == null) {
            sb.append("noname.dat");
        } else {
            sb.append(requestContext.get("FILENAME"));
        }
        sb.append("\"");
        sb.append(CRLF);
        sb.append("Content-Type: application/octet-stream");
        sb.append(CRLF);
        sb.append("Content-Transfer-Encoding: binary");
        sb.append(CRLF);
        sb.append(CRLF);

        conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        out = conn.getOutputStream();

        out.write(sb.toString().getBytes());
        out.write(data);

        out.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes());
        out.flush();

        // Get the response
        final int responseCode = conn.getResponseCode();
        if (responseCode >= 400) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        int len;
        final byte[] buf = new byte[1024];
        while ((len = in.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        os.close();

        if (responseCode >= 400) {
            throw new HTTPException(processServlet, responseCode, conn.getResponseMessage(), os.toByteArray());
        }

        return new Response(os.toByteArray());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

}

From source file:org.signserver.client.cli.defaultimpl.HTTPDocumentValidator.java

License:Open Source License

@Override
protected void doValidate(byte[] data, String encoding, final OutputStream out,
        final Map<String, Object> requestContext)
        throws IllegalRequestException, CryptoTokenOfflineException, SignServerException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Sending validation request " + " containing data of length " + data.length + " bytes"
                + " to worker " + workerName);
    }//w w  w. j  av a  2  s.c  om

    InputStream in = null;
    OutputStream outStream = null;

    try {
        final URLConnection conn = processServlet.openConnection();

        conn.setDoOutput(true);
        conn.setAllowUserInteraction(false);

        if (username != null && password != null) {
            conn.setRequestProperty(BASICAUTH_AUTHORIZATION,
                    BASICAUTH_BASIC + " " + new String(Base64.encode((username + ":" + password).getBytes())));
        }

        final StringBuilder sb = new StringBuilder();
        sb.append("--" + BOUNDARY);
        sb.append(CRLF);

        if (workerName == null) {
            sb.append("Content-Disposition: form-data; name=\"workerId\"");
            sb.append(CRLF);
            sb.append(CRLF);
            sb.append(workerId);
        } else {
            sb.append("Content-Disposition: form-data; name=\"workerName\"");
            sb.append(CRLF);
            sb.append(CRLF);
            sb.append(workerName);
        }
        sb.append(CRLF);
        sb.append("--" + BOUNDARY);
        sb.append(CRLF);

        if (metadata != null) {
            for (final String key : metadata.keySet()) {
                final String value = metadata.get(key);

                sb.append("Content-Disposition: form-data; name=\"REQUEST_METADATA." + key + "\"").append(CRLF);
                sb.append(CRLF);
                sb.append(value);
                sb.append(CRLF);
                sb.append("--" + BOUNDARY);
                sb.append(CRLF);
            }
        }

        sb.append("Content-Disposition: form-data; name=\"processType\"");
        sb.append(CRLF);
        sb.append(CRLF);
        sb.append("validateDocument");
        sb.append(CRLF);
        sb.append("--" + BOUNDARY);
        sb.append(CRLF);
        sb.append("Content-Disposition: form-data; name=\"datafile\"");
        sb.append("; filename=\"");
        if (requestContext.get("FILENAME") == null) {
            sb.append("noname.dat");
        } else {
            sb.append(requestContext.get("FILENAME"));
        }
        sb.append("\"");
        sb.append(CRLF);

        sb.append("Content-Type: application/octet-stream");
        sb.append(CRLF);
        sb.append("Content-Transfer-Encoding: binary");
        sb.append(CRLF);
        sb.append(CRLF);

        conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        outStream = conn.getOutputStream();

        outStream.write(sb.toString().getBytes());
        outStream.write(data);

        outStream.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes());
        outStream.flush();

        // Get the response
        in = conn.getInputStream();
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        int len;
        final byte[] buf = new byte[1024];
        while ((len = in.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        os.close();

        // read string from response
        final String response = os.toString();

        if ("VALID".equals(response)) {
            out.write(("Valid: " + Boolean.TRUE.booleanValue()).getBytes());
        } else {
            out.write(("Valid: " + Boolean.FALSE.booleanValue()).getBytes());
        }
        out.write("\n".getBytes());

    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (out != null) {
            try {
                outStream.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

From source file:org.signserver.client.cli.defaultimpl.HTTPSODSigner.java

License:Open Source License

private Response sendRequest(final URL processServlet, final String workerName, final Map<Integer, byte[]> data,
        final String encoding) {

    OutputStream out = null;//ww w .  ja  va  2s  . c o m
    InputStream in = null;
    try {
        final URLConnection conn = processServlet.openConnection();
        conn.setDoOutput(true);
        conn.setAllowUserInteraction(false);

        if (username != null && password != null) {
            conn.setRequestProperty(BASICAUTH_AUTHORIZATION, BASICAUTH_BASIC + " " + new String(Base64.encode(
                    new StringBuilder().append(username).append(":").append(password).toString().getBytes())));
        }

        final StringBuilder sb = new StringBuilder();
        if (workerId == 0) {
            sb.append("workerName=").append(workerName).append("&");
        } else {
            sb.append("workerId=").append(workerId).append("&");
        }
        sb.append("encoding=").append(encoding).append("&");
        for (Map.Entry<Integer, byte[]> entry : data.entrySet()) {
            sb.append("dataGroup").append(entry.getKey()).append("=")
                    .append(URLEncoder.encode(new String(entry.getValue()), "UTF-8")).append("&");
        }

        if (metadata != null) {
            for (final String key : metadata.keySet()) {
                final String value = metadata.get(key);

                sb.append("REQUEST_METADATA.").append(key).append("=").append(URLEncoder.encode(value, "UTF-8"))
                        .append("&");
            }
        }

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.addRequestProperty("Content-Length", String.valueOf(sb.toString().length()));

        out = conn.getOutputStream();

        out.write(sb.toString().getBytes());
        out.flush();

        // Get the response
        in = conn.getInputStream();
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        int len;
        final byte[] buf = new byte[1024];
        while ((len = in.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        os.close();

        return new Response(os.toByteArray());
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

}

From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java

License:Open Source License

@SuppressWarnings("SleepWhileInLoop") // We are just using the sleep for rate limiting
private void tsaRequest() throws Exception {
    final Random rand = new Random();
    final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    boolean doRun = true;
    do {/*w  w  w .  j  av  a2  s . c  o  m*/

        final int nonce = rand.nextInt();

        byte[] digest = new byte[20];
        if (instring != null) {
            final byte[] digestBytes = instring.getBytes("UTF-8");
            final MessageDigest dig = MessageDigest.getInstance(TSPAlgorithms.SHA1.getId(), "BC");
            dig.update(digestBytes);
            digest = dig.digest();
            // When we have given input, we don't want to loop
            doRun = false;
        }
        if (infilestring != null) {
            // TSPAlgorithms constants changed from Strings to ASN1Encoded objects
            digest = digestFile(infilestring, TSPAlgorithms.SHA1.getId());
            doRun = false;
        }
        final byte[] hexDigest = Hex.encode(digest);

        if (LOG.isDebugEnabled()) {
            LOG.debug("MessageDigest=" + new String(hexDigest));
        }

        final TimeStampRequest timeStampRequest;
        if (inreqstring == null) {
            LOG.debug("Generating a new request");
            timeStampRequestGenerator.setCertReq(certReq);
            if (reqPolicy != null) {
                timeStampRequestGenerator.setReqPolicy(new ASN1ObjectIdentifier(reqPolicy));
            }
            timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest,
                    BigInteger.valueOf(nonce));
        } else {
            LOG.debug("Reading request from file");
            timeStampRequest = new TimeStampRequest(readFiletoBuffer(inreqstring));
        }
        final byte[] requestBytes = timeStampRequest.getEncoded();

        if (outreqstring != null) {
            // Store request
            byte[] outBytes;
            if (base64) {
                outBytes = Base64.encode(requestBytes);
            } else {
                outBytes = requestBytes;
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outreqstring);
                fos.write(outBytes);
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }

        keyStoreOptions.setupHTTPS();

        URL url;
        URLConnection urlConn;
        DataOutputStream printout;
        DataInputStream input;

        url = new URL(urlstring);

        // Take start time
        final long startMillis = System.currentTimeMillis();
        final long startTime = System.nanoTime();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending request at: " + startMillis);
        }

        urlConn = url.openConnection();

        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/timestamp-query");

        // Send POST output.
        printout = new DataOutputStream(urlConn.getOutputStream());
        printout.write(requestBytes);
        printout.flush();
        printout.close();

        // Get response data.
        input = new DataInputStream(urlConn.getInputStream());

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int b;
        while ((b = input.read()) != -1) {
            baos.write(b);
        }

        // Take stop time
        final long estimatedTime = System.nanoTime() - startTime;

        LOG.info("Got reply after " + TimeUnit.NANOSECONDS.toMillis(estimatedTime) + " ms");

        final byte[] replyBytes = baos.toByteArray();
        if (outrepstring != null) {
            // Store request
            byte[] outBytes;
            if (base64) {
                outBytes = Base64.encode(replyBytes);
            } else {
                outBytes = replyBytes;
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outrepstring);
                fos.write(outBytes);
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }

        final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes);
        timeStampResponse.validate(timeStampRequest);

        LOG.info("TimeStampRequest validated");

        if (LOG.isDebugEnabled()) {
            final Date genTime;
            if (timeStampResponse.getTimeStampToken() != null
                    && timeStampResponse.getTimeStampToken().getTimeStampInfo() != null) {
                genTime = timeStampResponse.getTimeStampToken().getTimeStampInfo().getGenTime();
            } else {
                genTime = null;
            }
            LOG.debug("(Status: " + timeStampResponse.getStatus() + ", " + timeStampResponse.getFailInfo()
                    + "): " + timeStampResponse.getStatusString()
                    + (genTime != null ? (", genTime: " + genTime.getTime()) : "") + "\n");

        }

        if (doRun) {
            Thread.sleep(sleep);
        }
    } while (doRun);
}

From source file:org.signserver.common.ArchiveData.java

License:Open Source License

/**
 * Constructor that should be used to create an archive data.
 * @param archiveData//from w  w  w.j  av a2 s. com
 */
public ArchiveData(byte[] archiveData) {
    final String b64 = new String(Base64.encode(archiveData));
    data.put(ARCHIVEDATA, b64);
}

From source file:org.signserver.common.ProcessableConfig.java

License:Open Source License

/**
 * Set the keystore data used by the KeystoreInConfigCryptoToken.
 * //from  w  ww .  j av  a2s.com
 * @param keystoreData 
 */
public void setKeystoreData(final byte[] keystoreData) {
    workerConfig.getData().put(KEYSTORE_DATA, new String(Base64.encode(keystoreData)));
}

From source file:org.signserver.module.cmssigner.PlainSignerTest.java

License:Open Source License

/**
 * Tests logging of the response.//from www  .  ja v a 2 s .  c  om
 * @throws Exception 
 */
@Test
public void testLogResponseEncoded() throws Exception {
    LOG.info("testLogResponseEncoded");
    final RequestContext context = new RequestContext();
    final byte[] plainText = "some-data".getBytes("ASCII");
    final GenericSignResponse resp = sign(plainText, tokenRSA, createConfig(null), context);

    final String expected = new String(Base64.encode(resp.getProcessedData()), "ASCII");
    assertEquals("responseEncoded", expected, LogMap.getInstance(context).get("RESPONSE_ENCODED"));
}

From source file:org.signserver.module.renewal.worker.MockEjbcaWS.java

License:Open Source License

public CertificateResponse pkcs10Request(String username, String password, String pkcs10, String hardTokenSN,
        String responseType) throws AuthorizationDeniedException_Exception, CADoesntExistsException_Exception,
        EjbcaException_Exception, NotFoundException_Exception {
    checkAuth();//www . j a v  a2 s  .c o m
    System.out.println(">certificateRequest");
    pkcs10RequestCalled = true;
    final CertificateResponse result = new CertificateResponse();
    LOG.debug("PKCS10 from user '" + username + "'.");
    result.setResponseType(responseType);
    result.setData(Base64.encode(processCertReq(username, password, pkcs10, 0, hardTokenSN, responseType)));
    return result;
}

From source file:org.signserver.module.renewal.worker.RenewalWorkerTest.java

License:Open Source License

private void addRenewalWorkerWithInlineJKS(final int signerId, final String signerName) throws Exception {

    setupRenewalWorker(signerId, signerName);

    // TODO: Just any certificate for now as the test does not use HTTPS.
    // In the future replace with properer trust anchor
    final String trustChain = "-----BEGIN CERTIFICATE-----\n" + SIGN_CERT + "\n" + "-----END CERTIFICATE-----";
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(null, null);//from www.  j  a v  a  2 s.  c o  m
    final Collection certs = CertTools.getCertsFromPEM(new ByteArrayInputStream(trustChain.getBytes("UTF-8")));
    int i = 0;
    for (Object o : certs) {
        if (o instanceof Certificate) {
            keystore.setCertificateEntry("cert-" + i, (Certificate) o);
            i++;
        }
    }
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    keystore.store(bout, "foo123".toCharArray());
    final String value = new String(Base64.encode(bout.toByteArray()));

    getWorkerSession().setWorkerProperty(signerId, "TRUSTSTOREVALUE", value);
    getWorkerSession().setWorkerProperty(signerId, "TRUSTSTORETYPE", "JKS");
    getWorkerSession().setWorkerProperty(signerId, "TRUSTSTOREPASSWORD", "foo123");
    getWorkerSession().setWorkerProperty(signerId, "EJBCAWSURL", EJBCAWSURL_PREFIX);

    getWorkerSession().reloadConfiguration(signerId);
}

From source file:org.signserver.server.archive.base64dbarchiver.Base64DatabaseArchiver.java

License:Open Source License

@Override
public boolean archive(Archivable archivable, RequestContext requestContext) throws ArchiveException {
    final boolean archived;

    // Get the type of this request
    int archiveType = -1;
    if (Archivable.TYPE_RESPONSE.equals(archivable.getType())) {
        archiveType = ArchiveDataVO.TYPE_RESPONSE;
    } else if (Archivable.TYPE_REQUEST.equals(archivable.getType())) {
        archiveType = ArchiveDataVO.TYPE_REQUEST;
    }/* ww w.  j a v a 2 s. c  o  m*/

    // Only archive if the type of this request is the type configured for this Archiver
    if ((archiveOfTypes == ArchiveOfTypes.REQUEST && archiveType == ArchiveDataVO.TYPE_REQUEST)
            || (archiveOfTypes == ArchiveOfTypes.RESPONSE && archiveType == ArchiveDataVO.TYPE_RESPONSE)
            || (archiveOfTypes == ArchiveOfTypes.REQUEST_AND_RESPONSE
                    && (archiveType == ArchiveDataVO.TYPE_RESPONSE
                            || archiveType == ArchiveDataVO.TYPE_REQUEST))) {
        final EntityManager em = requestContext.getEntityManager();
        if (em == null) {
            throw new ArchiveException("Could not archive as archiver was not successfully initialized");
        }
        final ArchiveDataService dataService = new ArchiveDataService(em);
        final Integer workerId = (Integer) requestContext.get(RequestContext.WORKER_ID);
        final X509Certificate certificate = (X509Certificate) requestContext
                .get(RequestContext.CLIENT_CERTIFICATE);
        String remoteIp = (String) requestContext.get(RequestContext.REMOTE_IP);

        final String uniqueId;

        if (useXForwardedFor) {
            final List<String> ips = new LinkedList<String>();
            final String[] forwardedIps = XForwardedForUtils.getXForwardedForIPs(requestContext,
                    maxForwardedAddresses);

            if (includeDirectAddress) {
                ips.add(remoteIp);
            }

            if (forwardedIps != null) {
                ips.addAll(Arrays.asList(forwardedIps));
            }

            Collections.reverse(ips);

            if (!ips.isEmpty()) {
                remoteIp = StringUtils.join(ips, ", ");
            }
        }

        uniqueId = dataService.create(archiveType, workerId, archivable.getArchiveId(), certificate, remoteIp,
                new String(Base64.encode(archivable.getContentEncoded())));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Archived with uniqueId: " + uniqueId);
        }
        LogMap logMap = LogMap.getInstance(requestContext);
        String ids = logMap.get(IWorkerLogger.LOG_ARCHIVE_IDS);
        if (ids == null) {
            ids = uniqueId;
        } else {
            ids = ids + ", " + uniqueId;
        }
        logMap.put(IWorkerLogger.LOG_ARCHIVE_IDS, ids);

        archived = true;
    } else {
        archived = false;
    }
    return archived;
}