Example usage for android.util Base64 DEFAULT

List of usage examples for android.util Base64 DEFAULT

Introduction

In this page you can find the example usage for android.util Base64 DEFAULT.

Prototype

int DEFAULT

To view the source code for android.util Base64 DEFAULT.

Click Source Link

Document

Default values for encoder/decoder flags.

Usage

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

private JSONObject getJSONFromXml(File xml) {
    try {/*from w ww. j  a v  a 2 s  . c  o m*/

        JSONObject jsonObj = new JSONObject();
        FileInputStream xmlStream = null;
        try {
            xmlStream = new FileInputStream(xml);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;
            while ((length = xmlStream.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }
            byte[] b = bos.toByteArray();
            String xmlString = Base64.encodeToString(b, Base64.DEFAULT);
            jsonObj.put(HtmlPage.COL_HTML, xmlString);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (xmlStream != null) {
                try {
                    xmlStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        jsonObj.put(TYPE, MESSAGE_TYPE_HTML);
        return jsonObj;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        Log.d(TAG, "exception:" + e.getMessage());
        return null;
    }
}

From source file:ch.bfh.evoting.alljoyn.BusHandler.java

/**
 * Helper method send my identity to the other peers
 *//*w w  w. j a  va2  s .c o  m*/
private void sendMyIdentity() {
    Log.d(TAG, "Sending my identity");

    String myName = userDetails.getString("identification", "");

    //save my own identity in identityMap
    Identity myIdentity = new Identity(myName, messageAuthenticater.getMyPublicKey());
    identityMap.put(this.getIdentification(), myIdentity);

    byte[] publicKeyBytes = messageAuthenticater.getMyPublicKey().getEncoded();
    if (publicKeyBytes == null) {
        Log.e(TAG, "Key encoding not supported");
    }
    String myKey = Base64.encodeToString(publicKeyBytes, Base64.DEFAULT);
    String identity = myName + MESSAGE_PARTS_SEPARATOR + myKey;
    Log.d(TAG, "Send my identity");

    //send my identity
    Message msg = obtainMessage(BusHandler.PING);
    Bundle data = new Bundle();
    data.putString("groupName", lastJoinedNetwork);
    data.putString("pingString", identity);
    data.putSerializable("type", Type.IDENTITY);
    msg.setData(data);
    sendMessage(msg);
}

From source file:uk.ac.horizon.ubihelper.service.PeerManager.java

/** called from checkMessage(pi) to handle message in state STATE_PEER_REQ */
private boolean handlePeerReqResponse(PeerRequestInfo pi, Message m) {
    if (m.type != Message.Type.MANAGEMENT) {
        failPeer(pi, "Received init_peer_req response of type " + m.type);
        return false;
    }//from   www.  j  a v a2 s . c o  m
    String pinGuess = null;
    try {
        JSONObject msg = new JSONObject(m.body);
        String type = msg.getString(MessageUtils.KEY_TYPE);
        if (!MessageUtils.MSG_RESP_PEER_PIN.equals(type)) {
            if (MessageUtils.MSG_RESP_PEER_NOPIN.equals(type)) {
                return handlePeerNopin(pi, msg);
            }
            failPeer(pi, "Received init_peer_req response " + type);
            // TODO resp_peer_known
            return false;
        }
        // id, name, port, pin
        pinGuess = msg.getString(MessageUtils.KEY_PIN);
        pi.id = msg.getString(MessageUtils.KEY_ID);
        // TODO known IDs?
        int port = msg.getInt(MessageUtils.KEY_PORT);
        if (port != pi.port)
            Log.w(TAG, "resp_peer_pin has different port: " + port + " vs " + pi.port);
        String name = msg.getString(MessageUtils.KEY_NAME);
        if (pi.instanceName == null)
            pi.instanceName = name;
        else if (!name.equals(pi.instanceName))
            Log.w(TAG, "resp_peer_pin has different name: " + name + " vs " + pi.instanceName);
    } catch (JSONException e) {
        failPeer(pi, "Error in resp_peer_pin message: " + e);
        return false;
    }
    Log.i(TAG, "Received resp_peer_pin in state peer_req with pin=" + pinGuess);
    // pin?
    if (!pi.pin.equals(pinGuess)) {
        failPeer(pi, "Incorrect pin: " + pinGuess);
        return false;
    }
    // done
    try {
        JSONObject resp = new JSONObject();
        resp.put(MessageUtils.KEY_TYPE, MessageUtils.MSG_INIT_PEER_DONE);
        byte sbuf[] = new byte[8];
        protocol.getRandom(sbuf);
        pi.secret1 = Base64.encodeToString(sbuf, Base64.DEFAULT);
        resp.put(MessageUtils.KEY_SECRET, pi.secret1);
        resp.put(MessageUtils.KEY_PINNONCE, pi.pinnonce);
        JSONObject info = getInfo();
        if (info != null)
            resp.put(MessageUtils.KEY_INFO, info);

        Message r = new Message(Message.Type.MANAGEMENT, null, null, resp.toString());
        pi.pc.sendMessage(r);

        pi.state = PeerRequestState.STATE_PEER_DONE;
        pi.detail = null;

        broadcastPeerState(pi);

        return true;

    } catch (JSONException e) {
        // shouldn't happen!
        Log.e(TAG, "JSON error (shoulnd't be): " + e);
    }
    return false;
}

From source file:com.pheromone.plugins.FileUtils.java

/**
 * Read content of text file and return as base64 encoded data url.
 *
 * @param filename         The name of the file.
 * @return               Contents of file = data:<media type>;base64,<data>
 * @throws FileNotFoundException, IOException
 *//* w  ww  .j  a  v  a  2 s . co  m*/
public String readAsDataURL(String filename) throws FileNotFoundException, IOException {
    byte[] bytes = new byte[1000];
    BufferedInputStream bis = new BufferedInputStream(getPathFromUri(filename), 1024);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int numRead = 0;
    while ((numRead = bis.read(bytes, 0, 1000)) >= 0) {
        bos.write(bytes, 0, numRead);
    }

    // Determine content type from file name
    String contentType = null;
    if (filename.startsWith("content:")) {
        Uri fileUri = Uri.parse(filename);
        contentType = this.ctx.getContentResolver().getType(fileUri);
    } else {
        contentType = getMimeType(filename);
    }

    byte[] base64 = Base64.encode(bos.toByteArray(), Base64.DEFAULT);
    String data = "data:" + contentType + ";base64," + new String(base64);
    return data;
}

From source file:com.orange.oidc.tim.service.SIMStorage.java

public String getClientSecretBasic() {
    String bearer = (getClientId() + ":" + getTimSecret());
    return Base64.encodeToString(bearer.getBytes(), Base64.DEFAULT);
}

From source file:com.vkassin.mtrade.Common.java

public static void delOrder(final Context ctx, History hist) {

    JSONObject msg = new JSONObject();
    try {// w  ww.ja  va2s  . c om

        msg.put("objType", Common.CREATE_REMOVE_ORDER);
        msg.put("time", Calendar.getInstance().getTimeInMillis());
        msg.put("version", Common.PROTOCOL_VERSION);
        msg.put("orderNum", ++ordernum);
        msg.put("action", "REMOVE");
        msg.put("transSerial", hist.getSerial());

        if (isSSL) {
            //          ? ?:    reject-orderNum-transitSerial
            //         :                  reject-50249-107683
            String forsign = "reject-" + msg.getString("orderNum") + "-" + msg.getString("transSerial");
            byte[] signed = Common.signText(Common.signProfile, forsign.getBytes(), true);
            String gsign = Base64.encodeToString(signed, Base64.DEFAULT);
            msg.put("gostSign", gsign);
        }
        mainActivity.writeJSONMsg(msg);

    } catch (Exception e) {

        e.printStackTrace();
        Log.e(TAG, "Error! Cannot create JSON order object (delOrder)", e);
    }
}

From source file:com.creativtrendz.folio.ui.FolioWebViewScroll.java

protected static String decodeBase64(final String base64)
        throws IllegalArgumentException, UnsupportedEncodingException {
    final byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
    return new String(bytes, CHARSET_DEFAULT);
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

/**
 * Creates a JSON Object from a Tweet TODO: Move this where it belongs!
 * //w  ww  . ja va 2 s . com
 * @param c
 * @return
 * @throws JSONException
 */
protected JSONObject getJSON(Cursor c) throws JSONException {
    JSONObject o = new JSONObject();
    if (c.getColumnIndex(Tweets.COL_USER_TID) < 0 || c.getColumnIndex(TwitterUsers.COL_SCREEN_NAME) < 0) {
        Log.i(TAG, "missing user data");
        return null;
    }

    else {

        o.put(Tweets.COL_USER_TID, c.getLong(c.getColumnIndex(Tweets.COL_USER_TID)));
        o.put(TYPE, MESSAGE_TYPE_TWEET);
        o.put(TwitterUsers.COL_SCREEN_NAME, c.getString(c.getColumnIndex(TwitterUsers.COL_SCREEN_NAME)));
        if (c.getColumnIndex(Tweets.COL_CREATED_AT) >= 0)
            o.put(Tweets.COL_CREATED_AT, c.getLong(c.getColumnIndex(Tweets.COL_CREATED_AT)));
        if (c.getColumnIndex(Tweets.COL_CERTIFICATE) >= 0)
            o.put(Tweets.COL_CERTIFICATE, c.getString(c.getColumnIndex(Tweets.COL_CERTIFICATE)));
        if (c.getColumnIndex(Tweets.COL_SIGNATURE) >= 0)
            o.put(Tweets.COL_SIGNATURE, c.getString(c.getColumnIndex(Tweets.COL_SIGNATURE)));

        if (c.getColumnIndex(Tweets.COL_TEXT) >= 0)
            o.put(Tweets.COL_TEXT, c.getString(c.getColumnIndex(Tweets.COL_TEXT)));
        if (c.getColumnIndex(Tweets.COL_REPLY_TO_TWEET_TID) >= 0)
            o.put(Tweets.COL_REPLY_TO_TWEET_TID, c.getLong(c.getColumnIndex(Tweets.COL_REPLY_TO_TWEET_TID)));
        if (c.getColumnIndex(Tweets.COL_LAT) >= 0)
            o.put(Tweets.COL_LAT, c.getDouble(c.getColumnIndex(Tweets.COL_LAT)));
        if (c.getColumnIndex(Tweets.COL_LNG) >= 0)
            o.put(Tweets.COL_LNG, c.getDouble(c.getColumnIndex(Tweets.COL_LNG)));
        if (!c.isNull(c.getColumnIndex(Tweets.COL_MEDIA_URIS))) {
            String photoUri = c.getString(c.getColumnIndex(Tweets.COL_MEDIA_URIS));
            Uri uri = Uri.parse(photoUri);
            o.put(Tweets.COL_MEDIA_URIS, uri.getLastPathSegment());
        }
        if (c.getColumnIndex(Tweets.COL_HTML_PAGES) >= 0)
            o.put(Tweets.COL_HTML_PAGES, c.getString(c.getColumnIndex(Tweets.COL_HTML_PAGES)));
        if (c.getColumnIndex(Tweets.COL_SOURCE) >= 0)
            o.put(Tweets.COL_SOURCE, c.getString(c.getColumnIndex(Tweets.COL_SOURCE)));

        if (c.getColumnIndex(Tweets.COL_TID) >= 0 && !c.isNull(c.getColumnIndex(Tweets.COL_TID)))
            o.put(Tweets.COL_TID, c.getLong(c.getColumnIndex(Tweets.COL_TID)));

        if (c.getColumnIndex(TwitterUsers.COL_PROFILE_IMAGE_URI) >= 0
                && c.getColumnIndex(TweetsContentProvider.COL_USER_ROW_ID) >= 0) {

            String imageUri = c.getString(c.getColumnIndex(TwitterUsers.COL_PROFILE_IMAGE_URI));
            Bitmap profileImage = ImageLoader.getInstance().loadImageSync(imageUri);
            if (profileImage != null) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                profileImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                String profileImageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
                o.put(TwitterUsers.JSON_FIELD_PROFILE_IMAGE, profileImageBase64);
            }
        }

        return o;
    }
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private boolean loadCertificate(String cert_string) {
    try {//from w w  w . j a va2 s. c om
        // API returns concatenated cert & key.  Split them for OpenVPN options
        String certificateString = null, keyString = null;
        String[] certAndKey = cert_string.split("(?<=-\n)");
        for (int i = 0; i < certAndKey.length - 1; i++) {
            if (certAndKey[i].contains("KEY")) {
                keyString = certAndKey[i++] + certAndKey[i];
            } else if (certAndKey[i].contains("CERTIFICATE")) {
                certificateString = certAndKey[i++] + certAndKey[i];
            }
        }

        RSAPrivateKey key = ConfigHelper.parseRsaKeyFromString(keyString);
        keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
        preferences.edit()
                .putString(Constants.PRIVATE_KEY,
                        "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----")
                .commit();

        X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString);
        certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT);
        preferences.edit()
                .putString(Constants.CERTIFICATE,
                        "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----")
                .commit();
        return true;
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
}