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.test.performance.impl.DocumentSigner.java

License:Open Source License

/**
 * Issue a request to a documt signer as configured for the Task.
 * //from w ww. j a va 2 s .  c  o m
 * @return Run time (in ms).
 * @throws IOException
 */
private long documentRequest() throws IOException {
    URL url;
    URLConnection urlConn;

    final String requestUrl;

    if (useWorkerServlet) {
        requestUrl = this.url + "/" + workerNameOrId;
    } else {
        requestUrl = this.url;
    }

    url = new URL(requestUrl);

    // 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.setDoOutput(true);
    urlConn.setAllowUserInteraction(false);

    // Send with username
    if (userPrefix != null) {
        final String username;
        final String password = "";
        if (userSuffixMin == null) {
            username = userPrefix;
        } else {
            username = userPrefix + (userSuffixMin + random.nextInt(userSuffixMax - userSuffixMin + 1));
        }
        urlConn.setRequestProperty("Authorization",
                "Basic " + new String(Base64.encode((username + ":" + password).getBytes())));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Username: " + username);
        }
    }

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

    OutputStream out = null;

    if (!useWorkerServlet) {
        String workerName = null;
        int workerId = 0;

        try {
            workerId = Integer.parseInt(workerNameOrId);
        } catch (NumberFormatException e) {
            workerName = workerNameOrId;
        }

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

    sb.append("Content-Disposition: form-data; name=\"datafile\"");
    sb.append("; filename=\"");
    // don't care about the actual file name for now...
    sb.append("noname.dat");

    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);

    urlConn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
    urlConn.addRequestProperty("Content-Length",
            String.valueOf(sb.toString().length() + BOUNDARY.length() + 8 - 1));

    out = urlConn.getOutputStream();

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

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

    // Get the response
    final InputStream in = urlConn.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();
    out.close();
    in.close();

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

    return timeInMillis;
}

From source file:org.signserver.test.signserverws.v31.SignServerWSServiceTest.java

License:Open Source License

public void test03ProcessOk() {
    try {/* www  . j av  a 2s .com*/
        final List<ProcessRequestWS> requests = new ArrayList<ProcessRequestWS>();
        final ProcessRequestWS request = new ProcessRequestWS();
        request.setRequestDataBase64(new String(Base64.encode(RequestAndResponseManager
                .serializeProcessRequest(new GenericSignRequest(4711, "<root/>".getBytes())))));
        requests.add(request);
        final List<ProcessResponseWS> responses = ws.process(WORKERID, requests);
        assertEquals("Number of results", 1, responses.size());
        final GenericSignResponse response = (GenericSignResponse) RequestAndResponseManager
                .parseProcessResponse(Base64.decode(responses.get(0).getResponseDataBase64()));
        LOG.trace("Response: " + new String(response.getProcessedData()));
        assertEquals("requestID", 4711, response.getRequestID());
        final Certificate certificate = response.getSignerCertificate();
        assertNotNull("Certificate", certificate);
    } catch (IOException ex) {
        LOG.error(ex, ex);
        fail(ex.getMessage());
    } catch (CryptoTokenOfflineException_Exception ex) {
        LOG.error(ex, ex);
        fail(ex.getMessage());
    } catch (IllegalRequestException_Exception ex) {
        LOG.error(ex, ex);
        fail(ex.getMessage());
    } catch (InvalidWorkerIdException_Exception ex) {
        fail("Worker not found: " + WORKERID + " Hasn't test-configuration.properties been applied?");
    } catch (SignServerException_Exception ex) {
        LOG.error(ex, ex);
        fail(ex.getMessage());
    }
}

From source file:org.signserver.test.signserverws.v31.SignServerWSServiceTest.java

License:Open Source License

public void test04ProcessNonExisting() {
    try {/*from  w ww.ja v a2 s .com*/
        final List<ProcessRequestWS> requests = new ArrayList<ProcessRequestWS>();
        final ProcessRequestWS request = new ProcessRequestWS();
        request.setRequestDataBase64(new String(Base64.encode(RequestAndResponseManager
                .serializeProcessRequest(new GenericSignRequest(4711, "<root/>".getBytes())))));
        requests.add(request);
        ws.process(NONEXISTING_WORKERID, requests);
        fail("Should have thrown InvalidWorkerIdException_Exception");
    } catch (IOException ex) {
        LOG.error(ex, ex);
        fail(ex.getMessage());
    } catch (CryptoTokenOfflineException_Exception ex) {
        LOG.error(ex, ex);
        fail(ex.getMessage());
    } catch (IllegalRequestException_Exception ex) {
        LOG.error(ex, ex);
        fail(ex.getMessage());
    } catch (InvalidWorkerIdException_Exception ok) {
        // OK
    } catch (SignServerException_Exception ex) {
        LOG.error(ex, ex);
        fail(ex.getMessage());
    }
}

From source file:org.signserver.test.signserverws.v31.SignServerWSServiceTest.java

License:Open Source License

public void test05ProcessIllegalRequest() {
    try {// w ww  .j  a v  a2 s .  co  m
        final List<ProcessRequestWS> requests = new ArrayList<ProcessRequestWS>();
        final ProcessRequestWS request = new ProcessRequestWS();
        request.setRequestDataBase64(new String(Base64.encode(RequestAndResponseManager.serializeProcessRequest(
                new GenericSignRequest(4711, "< not-an-well-formed-xml-doc".getBytes())))));
        requests.add(request);
        final List<ProcessResponseWS> responses = ws.process(WORKERID, requests);
        fail("Should have thrown IllegalRequest or SignServerException but got: " + responses);
    } catch (IOException ex) {
        LOG.error(ex, ex);
        fail(ex.getMessage());
    } catch (CryptoTokenOfflineException_Exception ex) {
        LOG.error(ex, ex);
        fail(ex.getMessage());
    } catch (IllegalRequestException_Exception ex) {
        // OK
    } catch (InvalidWorkerIdException_Exception ex) {
        fail("Worker not found: " + WORKERID + " Hasn't test-configuration.properties been applied?");
    } catch (SignServerException_Exception ex) {
        // OK (sort of, better would have been an illegalrequest)
    }
}

From source file:org.silvertunnel.netlib.layer.tor.util.Encryption.java

License:Open Source License

/**
 * converts a JCERSAPublicKey into PEM/PKCS1-encoding
 * //from w w  w .j  a v a  2s.  co m
 * @param rsaPublicKey
 * @see RSAPublicKeyStructure
 * @return PEM-encoded RSA PUBLIC KEY
 */
public static String getPEMStringFromRSAPublicKey(RSAPublicKey rsaPublicKey) {

    // mrk: this was awful to program. Remeber: There are two entirely
    // different
    // standard formats for rsa public keys. Bouncy castle does only support
    // the
    // one we can't use for TOR directories.

    StringBuffer tmpDirSigningKey = new StringBuffer();

    try {

        tmpDirSigningKey.append("-----BEGIN RSA PUBLIC KEY-----\n");

        byte[] base64Encoding = Base64.encode(getPKCS1EncodingFromRSAPublicKey(rsaPublicKey));
        for (int i = 0; i < base64Encoding.length; i++) {
            tmpDirSigningKey.append((char) base64Encoding[i]);
            if (((i + 1) % 64) == 0)
                tmpDirSigningKey.append("\n");
        }
        tmpDirSigningKey.append("\n");

        tmpDirSigningKey.append("-----END RSA PUBLIC KEY-----\n");
    } catch (Exception e) {
        return null;
    }

    return tmpDirSigningKey.toString();
}

From source file:org.structr.function.CreateJarFileFunction.java

License:Open Source License

@Override
public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources)
        throws FrameworkException {

    if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) {

        if (sources[0] instanceof OutputStream) {

            try {

                final String algorithm = "SHA1";
                final String signAlgorithm = "SHA1withRSA";
                final String keygenAlgorithm = "RSA";
                final String srngAlgorithm = "SHA1PRNG";

                final JarOutputStream jos = new JarOutputStream((OutputStream) sources[0]);
                final MessageDigest md = MessageDigest.getInstance(algorithm);
                final Manifest manifest = new Manifest();
                final Attributes mainAttributes = manifest.getMainAttributes();

                final PrivateKey privateKey = getOrCreatePrivateKey(keygenAlgorithm, srngAlgorithm,
                        signAlgorithm);/*from w  w w. j  a v a2s.  co  m*/
                final X509Certificate cert = getOrCreateCertificate(keygenAlgorithm, srngAlgorithm,
                        signAlgorithm);

                System.out.println("This is the fingerprint of the keystore: " + hex(cert));

                //                     if (false) {
                //
                //                        // this code loads an existing keystore
                //                        final String keystorePath     = StructrApp.getConfigurationValue("application.keystore.path", null);
                //                        final String keystorePassword = StructrApp.getConfigurationValue("application.keystore.password", null);
                //
                //                        X509Certificate cert       = null;
                //                        PrivateKey privateKey      = null;
                //
                //                        if (StringUtils.isNoneBlank(keystorePath, keystorePassword)) {
                //
                //                           try (final FileInputStream fis = new FileInputStream(keystorePath)) {
                //
                //                              final KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
                //
                //                              keystore.load(fis, keystorePassword.toCharArray());
                //
                //                              for (final Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
                //
                //                                 final String alias = aliases.nextElement();
                //
                //                                 if (keystore.isCertificateEntry(alias)) {
                //
                //                                    System.out.println("Using certificate entry " + alias);
                //                                    cert = (X509Certificate)keystore.getCertificate(alias);
                //
                //                                 } else if (keystore.isKeyEntry(alias)) {
                //
                //                                    System.out.println("Using private key entry " + alias);
                //                                    privateKey = (PrivateKey)keystore.getKey(alias, keystorePassword.toCharArray());
                //
                //                                 }
                //                              }
                //
                //
                //                           } catch (Throwable t) {
                //
                //                              t.printStackTrace();
                //                           }
                //                        }
                //                     }
                // maximum compression
                jos.setLevel(9);

                // initialize manifest
                mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");

                // add entries from scripting context
                for (final Object source : sources) {

                    if (source != null && source instanceof NameAndContent) {

                        final NameAndContent content = (NameAndContent) source;
                        final JarEntry entry = new JarEntry(content.getName());
                        final byte[] data = content.getContent().getBytes("utf-8");

                        entry.setTime(System.currentTimeMillis());

                        // write JarEntry
                        jos.putNextEntry(entry);
                        jos.write(data);
                        jos.closeEntry();
                        jos.flush();

                        // update message digest with data
                        md.update(data);

                        // create new attribute with the entry's name
                        Attributes attr = manifest.getAttributes(entry.getName());
                        if (attr == null) {

                            attr = new Attributes();
                            manifest.getEntries().put(entry.getName(), attr);
                        }

                        // store SHA1-Digest for the new entry
                        attr.putValue(algorithm + "-Digest", new String(Base64.encode(md.digest()), "ASCII"));
                    }
                }

                // add manifest entry
                jos.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
                manifest.write(jos);

                // add signature entry
                final byte[] signedData = getSignatureForManifest(manifest, algorithm);
                jos.putNextEntry(new JarEntry("META-INF/CERT.SF"));
                jos.write(signedData);

                if (privateKey != null && cert != null) {

                    // add certificate entry
                    jos.putNextEntry(new JarEntry("META-INF/CERT." + privateKey.getAlgorithm()));
                    writeSignatureBlock(jos, algorithm, new CMSProcessableByteArray(signedData), cert,
                            privateKey);

                } else {

                    System.out.println("No certificate / key found, signinig disabled.");
                }

                // use finish() here to avoid an "already closed" exception later
                jos.flush();
                jos.finish();

            } catch (Throwable t) {
                t.printStackTrace();
            }

        } else {

            return "First parameter of create_jar_file() must be an output stream.";
        }
    }

    return "";
}

From source file:org.structr.function.CreateJarFileFunction.java

License:Open Source License

private byte[] getSignatureForManifest(final Manifest forManifest, final String algorithm)
        throws IOException, GeneralSecurityException {

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final Manifest signatureFile = new Manifest();
    final Attributes main = signatureFile.getMainAttributes();
    final MessageDigest md = MessageDigest.getInstance(algorithm);
    final PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true,
            "UTF-8");

    main.putValue("Signature-Version", "1.0");

    forManifest.write(print);/* w w w.  ja v  a 2  s. co  m*/
    print.flush();

    main.putValue(algorithm + "-Digest-Manifest", new String(Base64.encode(md.digest()), "ASCII"));

    final Map<String, Attributes> entries = forManifest.getEntries();

    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {

        // Digest of the manifest stanza for this entry.
        print.print("Name: " + entry.getKey() + "\r\n");

        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }

        print.print("\r\n");
        print.flush();

        final Attributes sfAttr = new Attributes();
        sfAttr.putValue(algorithm + "-Digest", new String(Base64.encode(md.digest()), "ASCII"));

        signatureFile.getEntries().put(entry.getKey(), sfAttr);
    }

    signatureFile.write(bos);

    return bos.toByteArray();
}

From source file:org.structr.jar.CreateJarFileFunction.java

License:Open Source License

@Override
public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources)
        throws FrameworkException {

    if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) {

        if (sources[0] instanceof OutputStream) {

            try {

                final String algorithm = "SHA1";
                final String signAlgorithm = "SHA1withRSA";
                final String keygenAlgorithm = "RSA";
                final String srngAlgorithm = "SHA1PRNG";

                final JarOutputStream jos = new JarOutputStream((OutputStream) sources[0]);
                final MessageDigest md = MessageDigest.getInstance(algorithm);
                final Manifest manifest = new Manifest();
                final Attributes mainAttributes = manifest.getMainAttributes();

                final PrivateKey privateKey = getOrCreatePrivateKey(keygenAlgorithm, srngAlgorithm,
                        signAlgorithm);//www .  j a  va 2s.  c  om
                final X509Certificate cert = getOrCreateCertificate(keygenAlgorithm, srngAlgorithm,
                        signAlgorithm);

                System.out.println("This is the fingerprint of the keystore: " + hex(cert));

                //                     if (false) {
                //
                //                        // this code loads an existing keystore
                //                        final String keystorePath     = StructrApp.getConfigurationValue("application.keystore.path", null);
                //                        final String keystorePassword = StructrApp.getConfigurationValue("application.keystore.password", null);
                //
                //                        X509Certificate cert       = null;
                //                        PrivateKey privateKey      = null;
                //
                //                        if (StringUtils.isNoneBlank(keystorePath, keystorePassword)) {
                //
                //                           try (final FileInputStream fis = new FileInputStream(keystorePath)) {
                //
                //                              final KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
                //
                //                              keystore.load(fis, keystorePassword.toCharArray());
                //
                //                              for (final Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
                //
                //                                 final String alias = aliases.nextElement();
                //
                //                                 if (keystore.isCertificateEntry(alias)) {
                //
                //                                    System.out.println("Using certificate entry " + alias);
                //                                    cert = (X509Certificate)keystore.getCertificate(alias);
                //
                //                                 } else if (keystore.isKeyEntry(alias)) {
                //
                //                                    System.out.println("Using private key entry " + alias);
                //                                    privateKey = (PrivateKey)keystore.getKey(alias, keystorePassword.toCharArray());
                //
                //                                 }
                //                              }
                //
                //
                //                           } catch (Throwable t) {
                //
                //                              logger.log(Level.WARNING, "", t);
                //                           }
                //                        }
                //                     }
                // maximum compression
                jos.setLevel(9);

                // initialize manifest
                mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");

                // add entries from scripting context
                for (final Object source : sources) {

                    if (source != null && source instanceof NameAndContent) {

                        final NameAndContent content = (NameAndContent) source;
                        final JarEntry entry = new JarEntry(content.getName());
                        final byte[] data = content.getContent().getBytes("utf-8");

                        entry.setTime(System.currentTimeMillis());

                        // write JarEntry
                        jos.putNextEntry(entry);
                        jos.write(data);
                        jos.closeEntry();
                        jos.flush();

                        // update message digest with data
                        md.update(data);

                        // create new attribute with the entry's name
                        Attributes attr = manifest.getAttributes(entry.getName());
                        if (attr == null) {

                            attr = new Attributes();
                            manifest.getEntries().put(entry.getName(), attr);
                        }

                        // store SHA1-Digest for the new entry
                        attr.putValue(algorithm + "-Digest", new String(Base64.encode(md.digest()), "ASCII"));
                    }
                }

                // add manifest entry
                jos.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
                manifest.write(jos);

                // add signature entry
                final byte[] signedData = getSignatureForManifest(manifest, algorithm);
                jos.putNextEntry(new JarEntry("META-INF/CERT.SF"));
                jos.write(signedData);

                if (privateKey != null && cert != null) {

                    // add certificate entry
                    jos.putNextEntry(new JarEntry("META-INF/CERT." + privateKey.getAlgorithm()));
                    writeSignatureBlock(jos, algorithm, new CMSProcessableByteArray(signedData), cert,
                            privateKey);

                } else {

                    System.out.println("No certificate / key found, signinig disabled.");
                }

                // use finish() here to avoid an "already closed" exception later
                jos.flush();
                jos.finish();

            } catch (Throwable t) {

                logException(entity, t, sources);

            }

        } else {

            logger.log(Level.WARNING,
                    "First parameter of create_jar_file() must be an output stream. Parameters: {0}",
                    getParametersAsString(sources));
            return "First parameter of create_jar_file() must be an output stream.";
        }

    } else {

        logParameterError(entity, sources, ctx.isJavaScriptContext());

    }

    return "";
}

From source file:org.structr.jar.SignedJarBuilder.java

License:Open Source License

/**
 * Adds an entry to the output jar, and write its content from the {@link InputStream}
 *
 * @param input The input stream from where to write the entry content.
 * @param entry the entry to write in the jar.
 * @throws IOException/*w  w  w  .java  2s.  c o m*/
 */
private void writeEntry(final InputStream input, final JarEntry entry) throws IOException {

    // add the entry to the jar archive
    jarOutputStream.putNextEntry(entry);

    // read the content of the entry from the input stream, and write it into the archive.
    int count;

    while ((count = input.read(buffer)) != -1) {

        jarOutputStream.write(buffer, 0, count);

        if (messageDigest != null) {
            messageDigest.update(buffer, 0, count);
        }
    }

    jarOutputStream.closeEntry();

    if (manifest != null) {

        Attributes attr = manifest.getAttributes(entry.getName());
        if (attr == null) {

            attr = new Attributes();
            manifest.getEntries().put(entry.getName(), attr);
        }

        attr.putValue("SHA1-Digest", new String(Base64.encode(messageDigest.digest()), "ASCII"));
    }
}

From source file:org.structr.jar.SignedJarBuilder.java

License:Open Source License

/**
 * Writes a .SF file with a digest to the manifest.
 *//*from www  . ja v a2  s  . co  m*/
private byte[] getSignature(final Manifest forManifest) throws IOException, GeneralSecurityException {

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final Manifest signatureFile = new Manifest();
    final Attributes main = signatureFile.getMainAttributes();
    final MessageDigest md = MessageDigest.getInstance("SHA1");
    final PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true,
            "UTF-8");

    main.putValue("Signature-Version", "1.0");

    // Digest of the entire manifest
    forManifest.write(print);
    print.flush();

    main.putValue("SHA1-Digest-Manifest", new String(Base64.encode(md.digest()), "ASCII"));

    final Map<String, Attributes> entries = forManifest.getEntries();

    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {

        // Digest of the manifest stanza for this entry.
        print.print("Name: " + entry.getKey() + "\r\n");

        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }

        print.print("\r\n");
        print.flush();

        final Attributes sfAttr = new Attributes();
        sfAttr.putValue("SHA1-Digest", new String(Base64.encode(md.digest()), "ASCII"));

        signatureFile.getEntries().put(entry.getKey(), sfAttr);
    }

    signatureFile.write(bos);

    return bos.toByteArray();
}