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:com.all.landownloader.LanNetworkingService.java

License:Apache License

private boolean sendTo(LanDownloaderMessage message, INonBlockingConnection connection) {
    if (connection != null) {
        message.setSourceAddress(connection.getLocalAddress().getHostAddress());
        byte[] bytes = Base64.encode(JsonConverter.toJson(message).getBytes());
        StringBuilder sb = new StringBuilder();
        sb.append(new String(bytes));
        sb.append(MESSAGE_DELIMITER);//from ww  w .  jav a  2s . c o  m
        synchronized (connection) {
            try {
                connection.write(sb.toString());
                return true;
            } catch (IOException e) {
                log.error(e, e);
            }
        }
    }
    return false;
}

From source file:com.all.networking.AbstractNetworkingService.java

License:Apache License

private boolean write(IoSession session, NetworkingMessage networkingMessage) throws InterruptedException {
    String json = JsonConverter.toJson(networkingMessage);
    String encodedMessage = null;
    try {// w w w  . java 2 s.com
        ByteBuffer byteBuffer = UTF_ENCODER.encode(CharBuffer.wrap(json));
        encodedMessage = new String(Base64.encode(byteBuffer.array()));
    } catch (CharacterCodingException e) {
        LOG.warn("Could not encode message with UTF-8.");
        encodedMessage = new String(Base64.encode(json.getBytes()));
    }
    WriteFuture future = session.write(encodedMessage);
    future.await();
    if (!future.isWritten()) {
        LOG.error("Could not send message through the network.", future.getException());
    }
    return future.isWritten();
}

From source file:com.all.networking.TestPeerNetworkingService.java

License:Apache License

@SuppressWarnings("unchecked")
@Test/*from w  w w . java2  s  .co  m*/
public void shouldReceiveAnOversizedMessageUsingChunks() throws Exception {
    StringBuilder expectedBody = new StringBuilder();
    for (int i = 0; i < (200 * 1024); i++) {
        expectedBody.append("abcd");
    }
    String expectedType = "expectedType";
    String expectedSender = "sender@all.com";
    AllMessage<String> oversizedMessage = new AllMessage<String>(expectedType, expectedBody.toString());

    for (NetworkingMessage message : PeerNetworkingService.split(expectedSender, oversizedMessage)) {
        service.messageReceived(someSession,
                new String(Base64.encode(JsonConverter.toJson(message).getBytes())));
    }

    AllMessage actualMessage = (AllMessage) stubEngine.getCurrentMessage();
    assertNotNull(actualMessage);
    assertEquals(expectedBody.toString(), actualMessage.getBody().toString());
}

From source file:com.all.shared.util.SyncUtils.java

License:Apache License

public static String encodeAndZip(List<SyncEventEntity> events) {
    String json = JsonConverter.toJson(events);
    byte[] encodedBytes = null;
    try {/*from   ww w .j  a v  a 2  s.co  m*/
        ByteBuffer byteBuffer = UTF_ENCODER.encode(CharBuffer.wrap(json));
        encodedBytes = byteBuffer.array();
    } catch (CharacterCodingException e) {
        LOGGER.warn("Could not encode message with UTF-8.");
        encodedBytes = json.getBytes();
    }
    return new String(Base64.encode(zip(encodedBytes)));
}

From source file:com.all.ultrapeer.TestUltraPeerService.java

License:Apache License

@Test
public void shouldHandleMessageReceivedAndIncludeNetworkingPropertiesToTheActualMessage() throws Exception {
    String sender = "email";
    AllMessage<?> message = new AllMessage<String>("some peer request", "test");
    NetworkingMessage networkingMessage = new NetworkingMessage(sender, message);

    Message<?> currentMessage = stubEngine.getCurrentMessage();
    assertNull(currentMessage);/*from w w  w .  ja  va2  s.  c o  m*/

    service.messageReceived(session,
            new String(Base64.encode(JsonConverter.toJson(networkingMessage).getBytes())));
    currentMessage = stubEngine.getCurrentMessage();
    assertNotNull(currentMessage);
    assertEquals(message.getType(), currentMessage.getType());
    assertEquals(sender, currentMessage.getProperty(NetworkingConstants.MESSAGE_SENDER));
    assertEquals(remoteAddress.getAddress().getHostAddress(),
            currentMessage.getProperty(NetworkingConstants.MESSAGE_SENDER_PUBLIC_ADDRESS));
    assertEquals(sender, currentMessage.getProperty(NetworkingConstants.MESSAGE_SENDER));
    assertNotNull(currentMessage.getProperty(NetworkingConstants.MESSAGE_SENDER));
}

From source file:com.all.ultrapeer.TestUltraPeerService.java

License:Apache License

@Test
public void shouldAddAliasWhenAMessageIsReceivedAndContainsSenderData() throws Exception {
    String senderData = "senderData";
    AllMessage<?> message = new AllMessage<String>("some peer request", "test");
    NetworkingMessage networkingMessage = new NetworkingMessage(senderData, message);

    service.messageReceived(session,//  ww w.  j  av a  2 s . c  om
            new String(Base64.encode(JsonConverter.toJson(networkingMessage).getBytes())));
    assertEquals(session, service.getSession(senderData));
}

From source file:com.android.builder.signing.SignedJarApkCreator.java

License:Apache 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/*from  ww  w. j a va 2s.  c o  m*/
 */
private void writeEntry(InputStream input, JarEntry entry) throws IOException {
    // add the entry to the jar archive
    mOutputJar.putNextEntry(entry);

    // read the content of the entry from the input stream, and write it into the archive.
    int count;
    while ((count = input.read(mBuffer)) != -1) {
        mOutputJar.write(mBuffer, 0, count);

        // update the digest
        if (mMessageDigest != null) {
            mMessageDigest.update(mBuffer, 0, count);
        }
    }

    // close the entry for this file
    mOutputJar.closeEntry();

    if (mManifest != null) {
        // update the manifest for this entry.
        Attributes attr = mManifest.getAttributes(entry.getName());
        if (attr == null) {
            attr = new Attributes();
            mManifest.getEntries().put(entry.getName(), attr);
        }
        attr.putValue(mDigestAlgorithm.entryAttributeName,
                new String(Base64.encode(mMessageDigest.digest()), "ASCII"));
    }
}

From source file:com.android.builder.signing.SignedJarApkCreator.java

License:Apache License

/** Writes a .SF file with a digest to the manifest. */
private void writeSignatureFile(OutputStream out) throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", "1.0 (Android)");

    MessageDigest md = MessageDigest.getInstance(mDigestAlgorithm.messageDigestName);
    PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true,
            SdkConstants.UTF_8);//from  w w w .  j  av  a  2s  .c om

    // Digest of the entire manifest
    mManifest.write(print);
    print.flush();
    main.putValue(mDigestAlgorithm.manifestAttributeName, new String(Base64.encode(md.digest()), "ASCII"));

    Map<String, Attributes> entries = mManifest.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();

        Attributes sfAttr = new Attributes();
        sfAttr.putValue(mDigestAlgorithm.entryAttributeName, new String(Base64.encode(md.digest()), "ASCII"));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }
    CountOutputStream cout = new CountOutputStream(out);
    sf.write(cout);

    // A bug in the java.util.jar implementation of Android platforms
    // up to version 1.6 will cause a spurious IOException to be thrown
    // if the length of the signature file is a multiple of 1024 bytes.
    // As a workaround, add an extra CRLF in this case.
    if ((cout.size() % 1024) == 0) {
        cout.write('\r');
        cout.write('\n');
    }
}

From source file:com.android.builder.signing.SignedJarBuilder.java

License:Apache 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  ww  . j  a v  a  2s .com
 */
private void writeEntry(InputStream input, JarEntry entry) throws IOException {
    // add the entry to the jar archive
    mOutputJar.putNextEntry(entry);

    // read the content of the entry from the input stream, and write it into the archive.
    int count;
    while ((count = input.read(mBuffer)) != -1) {
        mOutputJar.write(mBuffer, 0, count);

        // update the digest
        if (mMessageDigest != null) {
            mMessageDigest.update(mBuffer, 0, count);
        }
    }

    // close the entry for this file
    mOutputJar.closeEntry();

    if (mManifest != null) {
        // update the manifest for this entry.
        Attributes attr = mManifest.getAttributes(entry.getName());
        if (attr == null) {
            attr = new Attributes();
            mManifest.getEntries().put(entry.getName(), attr);
        }
        attr.putValue(DIGEST_ATTR, new String(Base64.encode(mMessageDigest.digest()), "ASCII"));
    }
}

From source file:com.android.builder.signing.SignedJarBuilder.java

License:Apache License

/** Writes a .SF file with a digest to the manifest. */
private void writeSignatureFile(OutputStream out) throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", "1.0 (Android)");

    MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM);
    PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true,
            SdkConstants.UTF_8);/*ww w . j  av a  2 s.c o m*/

    // Digest of the entire manifest
    mManifest.write(print);
    print.flush();
    main.putValue(DIGEST_MANIFEST_ATTR, new String(Base64.encode(md.digest()), "ASCII"));

    Map<String, Attributes> entries = mManifest.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();

        Attributes sfAttr = new Attributes();
        sfAttr.putValue(DIGEST_ATTR, new String(Base64.encode(md.digest()), "ASCII"));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }
    CountOutputStream cout = new CountOutputStream(out);
    sf.write(cout);

    // A bug in the java.util.jar implementation of Android platforms
    // up to version 1.6 will cause a spurious IOException to be thrown
    // if the length of the signature file is a multiple of 1024 bytes.
    // As a workaround, add an extra CRLF in this case.
    if ((cout.size() % 1024) == 0) {
        cout.write('\r');
        cout.write('\n');
    }
}