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:cn.ieclipse.pde.signer.util.SignApk.java

License:Apache License

/** Write a .SF file with a digest of the specified manifest. */
private static void writeSignatureFile(Manifest manifest, 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 SignApk)");

    MessageDigest md = MessageDigest.getInstance("SHA1");
    PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8");

    // Digest of the entire manifest
    manifest.write(print);//from   w  w w. j  a v  a2 s .  c  o  m
    print.flush();
    main.putValue("SHA1-Digest-Manifest", new String(Base64.encode(md.digest()), "ASCII"));

    Map<String, Attributes> entries = manifest.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("SHA1-Digest", 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:cn.vlabs.clb.server.utils.BitSetUtil.java

License:Apache License

public static String serialize(BitSet bitSet) {
    if (bitSet != null) {
        byte[] buf = Base64.encode(bitSet.toByteArray());
        return new String(buf);
    }//w ww  .j  av  a 2  s.  co  m
    return null;
}

From source file:com.aelitis.azureus.core.networkmanager.impl.ProtocolDecoderPHE.java

License:Open Source License

protected void process()

        throws IOException {
    try {//from  w w w.j  av  a 2s.  co m
        process_mon.enter();

        if (handshake_complete) {

            Debug.out("Handshake process already completed");

            return;
        }

        boolean loop = true;

        while (loop) {

            //System.err.println( this + ":" + (outbound?"out: ":"in : ") + protocol_state + "/" + protocol_substate + ": r " + bytes_read + " - " + read_buffer + ", w " + bytes_written + " - " + write_buffer );

            // ********************************************************
            /*
             * Major edits, this is basically where all the SSL modifications are
             */
            if (selected_protocol == CRYPTO_SSL) {
                if (sslFilter.isHandshakeCompleted()) {
                    // if it was an outgoing connection
                    // check that we actually connected to the
                    // hosts we intended
                    if (outBoundSSL) {
                        byte[] remoteKey = (byte[]) transport
                                .getUserData(OneSwarmSslTransportHelperFilterStream.REMOTE_SSL_PUBLIC_KEY);
                        if (Arrays.equals(expectedPublicKey,
                                OneSwarmSslTransportHelperFilterStream.ANY_KEY_ACCEPTED_BYTES)) {
                            // this is an auth connection, allow anyway but copy the 
                            // remote public key into the array so the auth manager can see what it is
                            sharedSecrets[1] = remoteKey;
                        } else if (!Arrays.equals(expectedPublicKey, remoteKey)) {
                            throw new IOException("remote friend publickey error, expected to connect to \n'"
                                    + new String(Base64.encode(expectedPublicKey)) + "' got\n'"
                                    + new String(Base64.encode(remoteKey)) + "'");
                        }

                    }
                    handshakeComplete();
                    processing_complete = true;
                    loop = false;
                    write_buffer = null;
                    read_buffer = null;

                } else {

                    if (write_buffer == null) {
                        write_buffer = ByteBuffer
                                .allocate(OneSwarmSslTransportHelperFilterStream.SSL_APP_BUFFER_SIZE);
                        write_buffer.flip();
                    }
                    read(read_buffer);
                    sslFilter.doHandshake(read_buffer, write_buffer);
                    write(write_buffer);
                    transport.resumeReadSelects();
                    transport.resumeWriteSelects();
                    return;
                }
            } else if (outBoundSSL) {
                // If using ssl, and outbound
                read_buffer = ByteBuffer.allocate(OneSwarmSslTransportHelperFilterStream.SSL_NET_BUFFER_SIZE);
                write_buffer = ByteBuffer.allocate(OneSwarmSslTransportHelperFilterStream.SSL_APP_BUFFER_SIZE);
                sslFilter = new OneSwarmSslTransportHelperFilterStream(transport, outbound,
                        OneSwarmSslTransportHelperFilterStream.SslHandShakeMatch.SSL_CLIENT_CERT);
                selected_protocol = CRYPTO_SSL;

                sslFilter.doHandshake(read_buffer, write_buffer);
                transport.resumeReadSelects();
                transport.resumeWriteSelects();

            } else if (protocol_state == PS_OUTBOUND_1) {
                // ************************************************************
                if (write_buffer == null) {

                    // A sends B Ya + Pa

                    byte[] padding_a = getRandomPadding(getPaddingMax() / 2); // note that /2 also used in calculating max initial packet size above                           

                    write_buffer = ByteBuffer.allocate(dh_public_key_bytes.length + padding_a.length);

                    write_buffer.put(dh_public_key_bytes);

                    write_buffer.put(padding_a);

                    write_buffer.flip();
                }

                write(write_buffer);

                if (!write_buffer.hasRemaining()) {

                    write_buffer = null;

                    protocol_state = PS_INBOUND_2;
                }

            } else if (protocol_state == PS_INBOUND_1) {

                // B receives Ya 

                read(read_buffer);

                // *******************************************************
                // check if the incoming connection is a SSL connection
                //System.err.println("ssl matching " + read_buffer.position() + "/" + OneSwarmSslTransportHelperFilterStream.SSL_HEADER_MIN_LENGTH);
                if (read_buffer.position() > OneSwarmSslTransportHelperFilterStream.SSL_HEADER_MIN_LENGTH) {
                    byte[] data = new byte[read_buffer.position()];
                    System.arraycopy(read_buffer.array(), 0, data, 0, data.length);
                    if (sslMatch == null) {
                        sslMatch = OneSwarmSslTransportHelperFilterStream.isSSLClientHello(data);
                    }
                    //System.out.println("ssl match: " + isClientHello.name());
                    if (sslMatch.equals(SslHandShakeMatch.SSL_CLIENT_CERT)
                            || sslMatch.equals(SslHandShakeMatch.SSL_NO_CLIENT_CERT)) {
                        selected_protocol = CRYPTO_SSL;

                        if (write_buffer == null) {
                            write_buffer = ByteBuffer
                                    .allocate(OneSwarmSslTransportHelperFilterStream.SSL_APP_BUFFER_SIZE);
                        }

                        read_buffer = ByteBuffer
                                .allocate(OneSwarmSslTransportHelperFilterStream.SSL_NET_BUFFER_SIZE);
                        read_buffer.put(data);

                        sslFilter = new OneSwarmSslTransportHelperFilterStream(transport, outbound, sslMatch);
                        sslFilter.doHandshake(read_buffer, write_buffer);
                        transport.resumeReadSelects();
                        transport.resumeWriteSelects();

                        continue;
                    }
                }
                if (!read_buffer.hasRemaining()) {
                    // *********************************************************

                    read_buffer.flip();

                    byte[] other_dh_public_key_bytes = new byte[read_buffer.remaining()];

                    read_buffer.get(other_dh_public_key_bytes);

                    completeDH(other_dh_public_key_bytes);

                    read_buffer = null;

                    protocol_state = PS_OUTBOUND_2;
                }

            } else if (protocol_state == PS_OUTBOUND_2) {

                // B->A: Yb PadB

                if (write_buffer == null) {

                    byte[] padding_b = getRandomPadding(getPaddingMax() / 2);

                    write_buffer = ByteBuffer.allocate(dh_public_key_bytes.length + padding_b.length);

                    write_buffer.put(dh_public_key_bytes);

                    write_buffer.put(padding_b);

                    write_buffer.flip();
                }

                write(write_buffer);

                if (!write_buffer.hasRemaining()) {

                    write_buffer = null;

                    protocol_state = PS_INBOUND_3;
                }

            } else if (protocol_state == PS_INBOUND_2) {

                // A receives: Yb

                if (read_buffer == null) {

                    read_buffer = ByteBuffer.allocate(dh_public_key_bytes.length);
                }

                read(read_buffer);

                if (!read_buffer.hasRemaining()) {

                    read_buffer.flip();

                    byte[] other_dh_public_key_bytes = new byte[read_buffer.remaining()];

                    read_buffer.get(other_dh_public_key_bytes);

                    completeDH(other_dh_public_key_bytes);

                    // A initiates SKEY so we can now set up crypto

                    setupCrypto();

                    read_buffer = null;

                    protocol_state = PS_OUTBOUND_3;
                }

            } else if (protocol_state == PS_OUTBOUND_3) {

                // A->B: HASH('req1', S), HASH('req2', SKEY)^HASH('req3', S), ENCRYPT(VC, crypto_provide, len(PadC), PadC, len(IA)), ENCRYPT(IA)

                if (write_buffer == null) {

                    int initial_data_out_len = initial_data_out == null ? 0 : initial_data_out.remaining();

                    // padding_a here is half of the padding from before

                    int pad_max = getPaddingMax();

                    byte[] padding_a = getRandomPadding(pad_max / 2);

                    byte[] padding_c = getZeroPadding(pad_max);

                    write_buffer = ByteBuffer.allocate(padding_a.length + 20 + 20
                            + (VC.length + 4 + 2 + padding_c.length + 2) + initial_data_out_len);

                    write_buffer.put(padding_a);

                    // HASH('req1', S)

                    SHA1Hasher hasher = new SHA1Hasher();

                    hasher.update(REQ1_IV);
                    hasher.update(secret_bytes);

                    byte[] sha1 = hasher.getDigest();

                    write_buffer.put(sha1);

                    // HASH('req2', SKEY)^HASH('req3', S)

                    hasher = new SHA1Hasher();

                    hasher.update(REQ2_IV);
                    hasher.update(shared_secret);

                    byte[] sha1_1 = hasher.getDigest();

                    hasher = new SHA1Hasher();

                    hasher.update(REQ3_IV);
                    hasher.update(secret_bytes);

                    byte[] sha1_2 = hasher.getDigest();

                    for (int i = 0; i < sha1_1.length; i++) {

                        sha1_1[i] ^= sha1_2[i];
                    }

                    write_buffer.put(sha1_1);

                    // ENCRYPT(VC, crypto_provide, len(PadC), PadC, len(IA)

                    write_buffer.put(write_cipher.update(VC));

                    write_buffer.put(write_cipher.update(new byte[] { 0, 0, 0, my_supported_protocols }));

                    write_buffer.put(write_cipher
                            .update(new byte[] { (byte) (padding_c.length >> 8), (byte) padding_c.length }));

                    write_buffer.put(write_cipher.update(padding_c));

                    write_buffer.put(write_cipher.update(
                            new byte[] { (byte) (initial_data_out_len >> 8), (byte) initial_data_out_len }));

                    if (initial_data_out_len > 0) {

                        int save_pos = initial_data_out.position();

                        write_cipher.update(initial_data_out, write_buffer);

                        // reset in case buffer needs to be used again by caller

                        initial_data_out.position(save_pos);

                        initial_data_out = null;
                    }

                    write_buffer.flip();
                }

                write(write_buffer);

                if (!write_buffer.hasRemaining()) {

                    write_buffer = null;

                    protocol_state = PS_INBOUND_4;
                }

            } else if (protocol_state == PS_INBOUND_3) {

                // B receives: HASH('req1', S), HASH('req2', SKEY)^HASH('req3', S), ENCRYPT(VC, crypto_provide, len(PadC), PadC, len(IA)), ENCRYPT(IA)

                if (read_buffer == null) {

                    read_buffer = ByteBuffer.allocate(20 + PADDING_MAX);

                    read_buffer.limit(20);

                    SHA1Hasher hasher = new SHA1Hasher();

                    hasher.update(REQ1_IV);
                    hasher.update(secret_bytes);

                    padding_skip_marker = hasher.getDigest();

                    protocol_substate = 1;
                }

                while (true) {

                    read(read_buffer);

                    if (read_buffer.hasRemaining()) {

                        break;
                    }

                    if (protocol_substate == 1) {

                        //skip up to HASH('req1', S)

                        int limit = read_buffer.limit();

                        read_buffer.position(limit - 20);

                        boolean match = true;

                        for (int i = 0; i < 20; i++) {

                            if (read_buffer.get() != padding_skip_marker[i]) {

                                match = false;

                                break;
                            }
                        }

                        if (match) {

                            read_buffer = ByteBuffer.allocate(20 + VC.length + 4 + 2);

                            protocol_substate = 2;

                            break;

                        } else {

                            if (limit == read_buffer.capacity()) {

                                throw (new IOException("PHE skip to SHA1 marker failed"));
                            }

                            read_buffer.limit(limit + 1);

                            read_buffer.position(limit);
                        }
                    } else if (protocol_substate == 2) {

                        // find SKEY using HASH('req2', SKEY)^HASH('req3', S)  , ENCRYPT(VC, crypto_provide, len(PadC),

                        read_buffer.flip();

                        final byte[] decode = new byte[20];

                        read_buffer.get(decode);

                        SHA1Hasher hasher = new SHA1Hasher();

                        hasher.update(REQ3_IV);
                        hasher.update(secret_bytes);

                        byte[] sha1 = hasher.getDigest();

                        for (int i = 0; i < decode.length; i++) {

                            decode[i] ^= sha1[i];
                        }

                        synchronized (global_shared_secrets) {

                            shared_secret = (byte[]) global_shared_secrets.get(new HashWrapper(decode));
                        }

                        if (shared_secret == null) {

                            throw (new IOException("No matching shared secret"));
                        }

                        // System.out.println( "inbound - using crypto secret " + ByteFormatter.encodeString( shared_secret ));

                        setupCrypto();

                        byte[] crypted = new byte[VC.length + 4 + 2];

                        read_buffer.get(crypted);

                        byte[] plain = read_cipher.update(crypted);

                        byte other_supported_protocols = plain[VC.length + 3];

                        int common_protocols = my_supported_protocols & other_supported_protocols;

                        if ((common_protocols & CRYPTO_PLAIN) != 0) {

                            selected_protocol = CRYPTO_PLAIN;

                        } else if ((common_protocols & CRYPTO_XOR) != 0) {

                            selected_protocol = CRYPTO_XOR;

                        } else if ((common_protocols & CRYPTO_RC4) != 0) {

                            selected_protocol = CRYPTO_RC4;

                        } else if ((common_protocols & CRYPTO_AES) != 0) {

                            selected_protocol = CRYPTO_AES;

                        } else {

                            throw (new IOException("No crypto protocol in common: mine = "
                                    + Integer.toHexString((byte) my_supported_protocols) + ", theirs = "
                                    + Integer.toHexString((byte) other_supported_protocols)));

                        }

                        int padding = ((plain[VC.length + 4] & 0xff) << 8) + (plain[VC.length + 5] & 0xff);

                        if (padding > PADDING_MAX) {

                            throw (new IOException("Invalid padding '" + padding + "'"));
                        }

                        read_buffer = ByteBuffer.allocate(padding + 2);

                        // skip the padding

                        protocol_substate = 3;

                    } else if (protocol_substate == 3) {

                        // ENCRYPT( len(IA)),  { ENCRYPT(IA) }

                        read_buffer.flip();

                        byte[] data = new byte[read_buffer.remaining()];

                        read_buffer.get(data);

                        data = read_cipher.update(data);

                        int ia_len = 0xffff
                                & (((data[data.length - 2] & 0xff) << 8) + (data[data.length - 1] & 0xff));

                        if (ia_len > 65535) {

                            throw (new IOException("Invalid IA length '" + ia_len + "'"));
                        }

                        if (ia_len > 0) {

                            read_buffer = ByteBuffer.allocate(ia_len);

                            // skip the padding

                            protocol_substate = 4;

                        } else {

                            read_buffer = null;

                            protocol_state = PS_OUTBOUND_4;

                            break;
                        }
                    } else if (protocol_substate == 4) {

                        // ENCRYPT(IA)

                        read_buffer.flip();

                        byte[] data = new byte[read_buffer.remaining()];

                        read_buffer.get(data);

                        data = read_cipher.update(data);

                        // hack alert - we can delay the writing of the outbound_4 packet if this is an incoming packet with
                        // a piggybacked bt handshake as we know that we'll be sending our own handshake back out pretty soon
                        // and it'll take the delayed data with it. To be more generic we'd need to add a callback to the pattern
                        // matcher to allow it to decide whether delaying was sensible / or stick a timer on the delayed data

                        delay_outbound_4 = new String(data).indexOf("BitTorrent") != -1;

                        // System.out.println( "Initial Data In: " + new String( data ) + "->delay=" +delay_outbound_4 );

                        initial_data_in = ByteBuffer.wrap(data);

                        read_buffer = null;

                        protocol_state = PS_OUTBOUND_4;

                        break;
                    }
                }
            } else if (protocol_state == PS_OUTBOUND_4) {

                // B->A: ENCRYPT(VC, crypto_select, len(padD), padD, // len(IB)), ENCRYPT(IB)

                if (write_buffer == null) {

                    int pad_max = getPaddingMax();

                    byte[] padding_b = getRandomPadding(pad_max / 2); // half padding b sent here

                    byte[] padding_d = getZeroPadding(pad_max);

                    write_buffer = ByteBuffer.allocate(padding_b.length + VC.length + 4 + 2 + padding_d.length); // + 2 + initial_data_out.length );

                    write_buffer.put(padding_b);

                    write_buffer.put(write_cipher.update(VC));

                    write_buffer.put(write_cipher.update(new byte[] { 0, 0, 0, selected_protocol }));

                    write_buffer.put(write_cipher
                            .update(new byte[] { (byte) (padding_d.length >> 8), (byte) padding_d.length }));

                    write_buffer.put(write_cipher.update(padding_d));

                    //write_buffer.put( write_cipher.update( new byte[]{ (byte)(initial_data_out.length>>8),(byte)initial_data_out.length }));

                    //write_buffer.put( write_cipher.update( initial_data_out ));

                    write_buffer.flip();
                }

                if (delay_outbound_4) {

                    if (transport.delayWrite(write_buffer)) {

                        write_buffer = null;

                        handshakeComplete();

                    } else {

                        delay_outbound_4 = false;
                    }
                }

                if (!delay_outbound_4) {

                    write(write_buffer);

                    if (!write_buffer.hasRemaining()) {

                        write_buffer = null;

                        handshakeComplete();
                    }
                }
            } else if (protocol_state == PS_INBOUND_4) {

                // B->A: ENCRYPT(VC, crypto_select, len(padD), padD // , len(IB)), ENCRYPT(IB)

                if (read_buffer == null) {

                    read_buffer = ByteBuffer.allocate(VC.length + PADDING_MAX);

                    read_buffer.limit(VC.length);

                    padding_skip_marker = new byte[VC.length];

                    padding_skip_marker = read_cipher.update(padding_skip_marker);

                    protocol_substate = 1;
                }

                while (true) {

                    read(read_buffer);

                    if (read_buffer.hasRemaining()) {

                        break;
                    }

                    if (protocol_substate == 1) {

                        //skip up to marker

                        int limit = read_buffer.limit();

                        read_buffer.position(limit - VC.length);

                        boolean match = true;

                        for (int i = 0; i < VC.length; i++) {

                            if (read_buffer.get() != padding_skip_marker[i]) {

                                match = false;

                                break;
                            }
                        }

                        if (match) {

                            read_buffer = ByteBuffer.allocate(4 + 2);

                            protocol_substate = 2;

                            break;

                        } else {

                            if (limit == read_buffer.capacity()) {

                                throw (new IOException("PHE skip to SHA1 marker failed"));
                            }

                            read_buffer.limit(limit + 1);

                            read_buffer.position(limit);
                        }
                    } else if (protocol_substate == 2) {

                        //  ENCRYPT( crypto_select, len(padD))

                        read_buffer.flip();

                        byte[] crypted = new byte[4 + 2];

                        read_buffer.get(crypted);

                        byte[] plain = read_cipher.update(crypted);

                        selected_protocol = plain[3];

                        if ((selected_protocol & my_supported_protocols) == 0) {

                            throw (new IOException("Selected protocol has nothing in common: mine = "
                                    + Integer.toHexString((byte) my_supported_protocols) + ", theirs = "
                                    + Integer.toHexString((byte) selected_protocol)));

                        }

                        int pad_len = 0xffff & (((plain[4] & 0xff) << 8) + (plain[5] & 0xff));

                        if (pad_len > 65535) {

                            throw (new IOException("Invalid pad length '" + pad_len + "'"));
                        }

                        read_buffer = ByteBuffer.allocate(pad_len); // + 2 );

                        protocol_substate = 3;

                    } else if (protocol_substate == 3) {

                        read_buffer.flip();

                        byte[] data = new byte[read_buffer.remaining()];

                        read_buffer.get(data);

                        data = read_cipher.update(data);

                        handshakeComplete();

                        read_buffer = null;

                        break;
                        /*
                        int   ib_len   = 0xffff & ((( data[data.length-2] & 0xff ) << 8 ) + ( data[data.length-1] & 0xff ));
                                
                        if ( ib_len > 65535 ){
                                   
                           throw( new IOException( "Invalid IB length '" + ib_len + "'" ));
                        }
                                
                        read_buffer = ByteBuffer.allocate( ib_len );
                                
                        protocol_substate   = 4;
                                
                        }else{
                                
                        read_buffer.flip();
                                
                        byte[]   data = new byte[read_buffer.remaining()];
                                
                        read_buffer.get( data );
                                
                        initial_data_in = read_cipher.update( data );      
                                
                        handshakeComplete();
                                
                        read_buffer   = null;
                                
                        break;
                        */
                    }
                }
            }

            if (handshake_complete) {

                transport.cancelReadSelects();

                transport.cancelWriteSelects();

                loop = false;

                complete();

            } else {

                if (read_buffer == null) {

                    transport.pauseReadSelects();

                } else {

                    transport.resumeReadSelects();

                    loop = false;

                }

                if (write_buffer == null) {

                    transport.pauseWriteSelects();

                } else {

                    transport.resumeWriteSelects();

                    loop = false;
                }
            }
        }
    } catch (Throwable e) {
        e.printStackTrace();
        failed(e);

        if (e instanceof IOException) {

            throw ((IOException) e);

        } else {

            throw (new IOException(Debug.getNestedExceptionMessage(e)));
        }
    } finally {

        process_mon.exit();
    }
}

From source file:com.aelitis.azureus.core.subs.impl.SubscriptionImpl.java

License:Open Source License

protected static void embedEngines(Map map, Engine engine) {
    Map engines = new HashMap();

    map.put("engines", engines);

    Map engine_map = new HashMap();

    try {/*w w  w.j a v a  2  s.  c o  m*/

        String engine_str = new String(Base64.encode(BEncoder.encode(engine.exportToBencodedMap())), "UTF-8");

        engine_map.put("content", engine_str);

        engines.put(String.valueOf(engine.getId()), engine_map);

    } catch (Throwable e) {

        Debug.out(e);
    }
}

From source file:com.aelitis.azureus.core.subs.impl.SubscriptionManagerImpl.java

License:Open Source License

protected void updatePublicSubscription(SubscriptionImpl subs) {
    if (subs.isSingleton()) {

        // never update singletons

        subs.setServerPublished();/*from w w w .jav  a2  s .  c om*/

    } else {

        Long l_last_pub = (Long) subs.getUserData(SP_LAST_ATTEMPTED);
        Long l_consec_fail = (Long) subs.getUserData(SP_CONSEC_FAIL);

        if (l_last_pub != null && l_consec_fail != null) {

            long delay = SERVER_PUB_CHECK_PERIOD;

            for (int i = 0; i < l_consec_fail.longValue(); i++) {

                delay <<= 1;

                if (delay > 24 * 60 * 60 * 1000) {

                    break;
                }
            }

            if (l_last_pub.longValue() + delay > SystemTime.getMonotonousTime()) {

                return;
            }
        }

        try {
            File vf = getVuzeFile(subs);

            byte[] bytes = FileUtil.readFileAsByteArray(vf);

            byte[] encoded_subs = Base64.encode(bytes);

            PlatformSubscriptionsMessenger.updateSubscription(!subs.getServerPublished(), subs.getName(),
                    subs.getPublicKey(), subs.getPrivateKey(), subs.getShortID(), subs.getVersion(),
                    new String(encoded_subs));

            subs.setUserData(SP_LAST_ATTEMPTED, null);
            subs.setUserData(SP_CONSEC_FAIL, null);

            subs.setServerPublished();

            log("    Updated public subscription " + subs.getString());

        } catch (Throwable e) {

            log("    Failed to update public subscription " + subs.getString(), e);

            subs.setUserData(SP_LAST_ATTEMPTED, new Long(SystemTime.getMonotonousTime()));

            subs.setUserData(SP_CONSEC_FAIL,
                    new Long(l_consec_fail == null ? 1 : (l_consec_fail.longValue() + 1)));

            subs.setServerPublicationOutstanding();
        }
    }
}

From source file:com.aelitis.azureus.core.subs.impl.SubscriptionManagerImpl.java

License:Open Source License

protected void checkSingletonPublish(SubscriptionImpl subs)

        throws SubscriptionException {
    if (subs.getSingletonPublishAttempted()) {

        throw (new SubscriptionException("Singleton publish already attempted"));
    }//from   w  ww  . ja  v a  2s.co  m

    subs.setSingletonPublishAttempted();

    try {
        File vf = getVuzeFile(subs);

        byte[] bytes = FileUtil.readFileAsByteArray(vf);

        byte[] encoded_subs = Base64.encode(bytes);

        // use a transient key-pair as we won't have the private key in general

        KeyPair kp = CryptoECCUtils.createKeys();

        byte[] public_key = CryptoECCUtils.keyToRawdata(kp.getPublic());
        byte[] private_key = CryptoECCUtils.keyToRawdata(kp.getPrivate());

        PlatformSubscriptionsMessenger.updateSubscription(true, subs.getName(), public_key, private_key,
                subs.getShortID(), 1, new String(encoded_subs));

        log("    created singleton public subscription " + subs.getString());

    } catch (Throwable e) {

        throw (new SubscriptionException("Failed to publish singleton", e));
    }
}

From source file:com.aelitis.azureus.ui.swt.browser.listener.publish.PublishTransaction.java

License:Open Source License

private void _chooseThumbnail(BrowserMessage message) {
    final int resize_size[] = { DEFAULT_IMAGE_BOX_SIZE, DEFAULT_IMAGE_BOX_SIZE };
    final float image_quality[] = { DEFAULT_JPEG_QUALITY };
    Map elements = null; //will be used if several thumbnails are required on a single page
    if (message.isParamObject()) {
        Map parameters = message.getDecodedMap();
        try {/*from  w  w  w  .  j a  v a2s.  co m*/
            resize_size[0] = MapUtils.getMapInt(parameters, "width", DEFAULT_IMAGE_BOX_SIZE);
            resize_size[1] = MapUtils.getMapInt(parameters, "height", DEFAULT_IMAGE_BOX_SIZE);
            image_quality[0] = ((Number) MapUtils.getMapObject(parameters, "quality",
                    new Double(DEFAULT_JPEG_QUALITY), Number.class)).floatValue();
            if (parameters.containsKey(ELEMENTS)) {
                elements = (Map) parameters.get(ELEMENTS);
            }
        } catch (Exception e) {
            //Possible bad parameters given, use default values
            e.printStackTrace();
        }
    }
    FileDialog dialog = new FileDialog(shell, SWT.OPEN);
    dialog.setFilterNames(new String[] { "Image Files" });
    dialog.setFilterExtensions(new String[] { "*.jpg;*.jpeg;*.bmp;*.gif;*.png;*.tiff,*.tif" });
    final String fileName = dialog.open();
    if (fileName != null) {
        //Run async not to block the UI
        /*Thread runner = 
        new Thread("Thumbnail Creator") {
        public void run() {*/

        try {
            sendBrowserMessage("thumb", "start", elements);

            File file = new File(fileName);
            ResizedImageInfo info = loadAndResizeImage(file, resize_size[0], resize_size[1], 1);
            if (info == null) {
                debug("User canceled image resizing");
                sendBrowserMessage("thumb", "clear", elements);
            } else {
                final String thumbURL = info.url.toString();
                debug("Size : " + info.data.length);

                final String encoded = new String(Base64.encode(info.data));
                Map params = new HashMap();
                params.put("url", thumbURL);
                params.put("width", new Long(info.width));
                params.put("height", new Long(info.height));
                params.put("data", encoded);
                if (elements != null) {
                    params.put(ELEMENTS, elements);
                }
                sendBrowserMessage("thumb", "done", params);
            }
        } catch (ImageResizeException e) {
            debug("Error resizing image", e);
            sendBrowserMessage("thumb", "clear", elements);

            Map params = new HashMap();
            params.put("message", e.getMessage());
            sendBrowserMessage("page", "error", params);
        } catch (Exception e) {
            debug("Error reading file", e);
            sendBrowserMessage("thumb", "clear", elements);

            Map params = new HashMap();
            String errmsg = e.getMessage();

            params.put("message", "Vuze cannot process this image. "
                    + "Please select another one.\n\nDetailed Error: " + errmsg);
            sendBrowserMessage("page", "error", params);
        } catch (OutOfMemoryError e) {
            debug("Error processing the image", e);

            sendBrowserMessage("thumb", "clear", elements);

            Map params = new HashMap();
            params.put("message",
                    "Vuze cannot process this image (likely reason is that it is too big). Please select another one.");
            sendBrowserMessage("page", "error", params);

        }
        /*}
        };
        runner.setDaemon(true);
        runner.start();       */
    }
}

From source file:com.aelitis.azureus.ui.swt.browser.listener.publish.PublishTransaction.java

License:Open Source License

private void createTorrentFile(String file) {
    if (file != null) {
        dataFile = new File(file);
        try {//from  w ww  .j  av a  2 s  .co m
            PluginInterface pi = PluginInitializer.getDefaultInterface();
            creator = pi.getTorrentManager().createFromDataFileEx(dataFile,
                    new URL("http://xxxxxxxxxxxxxxxxx:6969/announce"), false);

            creatorListener = new TorrentCreatorListener() {

                public void complete(Torrent torrent) {
                    try {

                        torrent.setDefaultEncoding();

                        debug("local torrent creation complete: " + torrent.getName() + " : "
                                + torrent.getMagnetURI());

                        final String tData = new String(Base64.encode(torrent.writeToBEncodedData()));
                        Map params = new HashMap();
                        params.put("data", tData);
                        sendBrowserMessage("torrent", "done", params);
                    } catch (Throwable t) {
                        // TODO: handle exception
                        debug("error encoding torrent", t);
                    }

                }

                public void failed(TorrentException cause) {
                    torrentCreationFailed(cause);
                }

                public void reportActivity(String activity) {
                    //debug("creation status : " + activity);
                }

                public void reportPercentageDone(int percent) {
                    //debug("creation progress : " + percent);
                    Map params = new HashMap();
                    params.put("percent", new Long(percent));
                    sendBrowserMessage("torrent", "progress", params);
                }

            };

            creator.addListener(creatorListener);

            creator.start();

        } catch (MalformedURLException e) {

            torrentCreationFailed(e);

        } catch (TorrentException e) {

            torrentCreationFailed(e);

        }

        Map params = new HashMap();
        params.put("folder", new Boolean(dataFile.isDirectory()));
        params.put("name", dataFile.getName());
        Long[] info = getSizeAndCount(dataFile);
        params.put("size", info[0]);
        params.put("num-files", info[1]);
        params.put("size-text", DisplayFormatters.formatByteCountToKiBEtc(info[0].longValue()));
        sendBrowserMessage("torrent", "chosen", params);
    } else {
        //No file was chosen, cancel the transaction
        cancel();
        stop();
    }
}

From source file:com.all.backend.web.controller.TestUserServerController.java

License:Apache License

@Test
public void shouldSearchUsers() throws Exception {
    String keyword = "keyword";
    String encodedKeyword = new String(Base64.encode(keyword.getBytes()));
    int index = 0;
    List<ContactInfo> list = new ArrayList<ContactInfo>();
    String expectedResult = JsonConverter.toJson(list);
    when(service.searchUsers(keyword, index)).thenReturn(list);

    String result = controller.searchUsers(encodedKeyword);

    verify(service).searchUsers(keyword, index);
    assertEquals(expectedResult, result);
}

From source file:com.all.dht.TestDhtMessageDispatcher.java

License:Apache License

@Test
public void shouldForwardMessagesReceivedThroughMessEngine() throws Exception {
    int tcpPort = 10006;
    when(dhtSettings.getTcpPort()).thenReturn(tcpPort);
    dispatcher.start();//w w  w.j a  v  a2 s .c om
    IoSession session = mock(IoSession.class);
    InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 0);
    when(session.getRemoteAddress()).thenReturn(remoteAddress);
    String sender = "sender node id";
    String body = "body";
    String type = "type";
    AllMessage<String> expectedMessage = new AllMessage<String>(type, body);
    NetworkingMessage networkingMessage = new NetworkingMessage(sender, expectedMessage);

    dispatcher.messageReceived(session,
            new String(Base64.encode(JsonConverter.toJson(networkingMessage).getBytes())));
    Message<?> actualMessage = stubEngine.getMessage(type);
    assertNotNull(actualMessage);
    assertEquals(body, actualMessage.getBody());
    assertEquals(sender, actualMessage.getProperty(MESSAGE_SENDER));
}