Example usage for android.util Base64 encodeToString

List of usage examples for android.util Base64 encodeToString

Introduction

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

Prototype

public static String encodeToString(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated String with the result.

Usage

From source file:com.google.wireless.speed.speedometer.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off */
@Override/* w ww .j av  a2  s . co  m*/
public MeasurementResult call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    boolean success = false;
    String errorMsg = "";
    InputStream inputStream = null;

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent));
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            success = (statusCode == 200);
        }

        /* For HttpClient to work properly, we still want to consume the entire response even if
         * the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
                this.progress = (int) (100 * totalBodyLen / expectedResponseLen);
                this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress);
                broadcastProgressForUser(this.progress);
            }
            duration = System.currentTimeMillis() - startTime;
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, success,
                this.measurementDesc);

        result.addResult("code", statusCode);

        if (success) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Log.i(SpeedometerApp.TAG, MeasurementJsonConvertor.toJsonString(result));
        return result;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Log.e(SpeedometerApp.TAG, e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Log.e(SpeedometerApp.TAG, e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.e(SpeedometerApp.TAG, "Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:uk.ac.ucl.excites.sapelli.relay.BackgroundService.java

/**
 * Register an SMS Data (Binary) Receiver
 *///w w w  .  java 2  s.com
private void registerSmsReceiver() {
    smsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Debug.i("Received Binary SMS");

            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs = null;

            if (null != bundle) {
                // In telecommunications the term (PDU) means protocol data
                // unit.
                // There are two ways of sending and receiving SMS messages:
                // by text mode and by PDU (protocol description unit) mode.
                // The PDU string contains not only the message, but also a
                // lot of meta-information about the sender, his SMS service
                // center, the time stamp etc
                // It is all in the form of hexa-decimal octets or decimal
                // semi-octets.
                Object[] pdus = (Object[]) bundle.get("pdus");
                msgs = new SmsMessage[pdus.length];

                for (int i = 0; i < msgs.length; i++) {
                    // Create the Message
                    msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    // Get Message Parameters
                    SmsObject receivedSms = new SmsObject();
                    receivedSms.setTelephoneNumber(msgs[i].getOriginatingAddress());
                    receivedSms.setMessageTimestamp(msgs[i].getTimestampMillis());
                    receivedSms.setMessageData(Base64.encodeToString(msgs[i].getUserData(), Base64.CRLF));

                    Debug.d("Received SMS and it's content hash is: " + BinaryHelpers
                            .toHexadecimealString(Hashing.getMD5Hash(msgs[i].getUserData()).toByteArray()));

                    // Store the SmsObject to the db
                    dao.storeSms(receivedSms);
                }
            }

            // This will stop the Broadcast and not allow the message to
            // be interpreted by the default Android app or other apps
            abortBroadcast();
        }
    };

    // Set up the Receiver Parameters
    IntentFilter mIntentFilter = new IntentFilter();
    mIntentFilter.setPriority(999);
    mIntentFilter.addAction("android.intent.action.DATA_SMS_RECEIVED");
    mIntentFilter.addDataScheme("sms");
    // Set the Port that is listening to
    mIntentFilter.addDataAuthority("*", "2013");
    // mIntentFilter.addDataType(type)
    registerReceiver(smsReceiver, mIntentFilter);
    Debug.d("Set up BinarySMS receiver.");
}

From source file:com.letsgood.sampleapp.SignInActivity.java

private void printFacebookKeyHash() {
    // Add code to print out the key hash
    try {/*w w  w. j a v  a  2  s  .  c o m*/
        PackageInfo info = getPackageManager().getPackageInfo("com.letsgood.sampleapp",
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (PackageManager.NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }
}

From source file:com.adjust.sdk.PackageBuilder.java

private void addMapBase64(Map<String, String> parameters, String key, Map<String, String> map) {
    if (null == map) {
        return;/*from w  w  w.  ja  v a  2 s  .  com*/
    }

    JSONObject jsonObject = new JSONObject(map);
    byte[] jsonBytes = jsonObject.toString().getBytes();
    String encodedMap = Base64.encodeToString(jsonBytes, Base64.NO_WRAP);

    addString(parameters, key, encodedMap);
}

From source file:br.com.vpsa.oauth2android.token.MacTokenTypeDefinition.java

private String calculateBodyHash(String body, String algorithm) throws InvalidTokenTypeException {
    try {/*from   w  w  w  .j a  v  a2s . c  om*/
        MessageDigest md = MessageDigest.getInstance(algorithm);
        String bodyhash = Base64.encodeToString(md.digest(body.getBytes()), Base64.DEFAULT);
        return bodyhash;
    } catch (NoSuchAlgorithmException ex) {
        throw new InvalidTokenTypeException(
                "This token contains no or an invalid algorithm to calculate the bodyhash");
    }
}

From source file:com.ritul.truckshare.RegisterActivity.DriverLicenseActivity.java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Utility.GALLERY_PICTURE && data != null) {
        isImage = true;//from   w  w  w.j  a v a  2  s  .co m
        // data contains result
        // Do some task
        Image_Selecting_Task(data);
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = DriverLicenseActivity.this.getContentResolver().query(selectedImage, filePathColumn,
                null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        selectedpath = cursor.getString(columnIndex);
        cursor.close();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 8;
        final Bitmap bitmap = BitmapFactory.decodeFile(selectedpath, options);
        convertimagetobyte();
        imagedata = Base64.encodeToString(imageByte, Base64.DEFAULT);
    } else if (requestCode == Utility.CAMERA_PICTURE && data != null) {
        isImage = true;
        // Do some task
        //Image_Selecting_Task(data);
        if (requestCode == Utility.CAMERA_PICTURE && resultCode == RESULT_OK && data != null) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            preview.setImageBitmap(photo);

            Bitmap bitmap = ((BitmapDrawable) preview.getDrawable()).getBitmap();
            imagedata = Base64.encodeToString(getBytesFromBitmap(bitmap), Base64.DEFAULT);

        }
    }
}

From source file:app.sunstreak.yourpisd.LoginActivity.java

/**
 * Attempts to sign in or register the account specified by the login form.
 * If there are form errors (invalid email, missing fields, etc.), the
 * errors are presented and no actual login attempt is made.
 *///  ww  w.ja  v a  2s.co m
public void attemptLogin() {
    if (mAuthTask != null) {
        return;
    }

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    mEmail = mEmailView.getText().toString();
    encryptedPass = Base64.encodeToString(mPasswordView.getText().toString().getBytes(), Base64.DEFAULT);
    mPassword = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password.
    if (TextUtils.isEmpty(mPassword)) {
        mPasswordView.setError(getString(R.string.error_field_required));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid username.
    if (TextUtils.isEmpty(mEmail)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt login and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // Show a progress spinner, and kick off a background task to
        // perform the user login attempt.
        SharedPreferences sharedPrefs = this.getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPrefs.edit();
        editor.putString("email", mEmail);
        editor.putString("e_password", mRememberPassword ? encryptedPass : "");
        editor.putBoolean("remember_password", mRememberPassword);
        editor.putBoolean("auto_login", mAutoLogin);
        editor.commit();

        // Modified from default.

        showProgress(true);
        mAuthTask = new UserLoginTask();
        mAuthTask.execute((Void) null);
    }
}

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

/**
 * Compute a truncated digest on the salt
 * We only take the three first letters (not chars!) of the Base64 encoded digest, because
 * this truncated digest must be transmitted with the group password (only letters)
 * @param salt the salt from on we want to compute the digest 
 * @return the three first letters of the Base64 encoded digest
 *///from  ww w  .j av a2s .c  om
public String getSaltShortDigest(byte[] salt) {
    if (salt == null)
        return "";

    //Compute the digest
    MessageDigest md;
    String saltHash;
    Log.d(TAG, "Computing salt digest");
    try {
        md = MessageDigest.getInstance("SHA-1");
        md.update(salt, 0, salt.length);
        saltHash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Digest of salt could not be computed");
        e.printStackTrace();
        return null;
    }

    //Truncate the digest
    String shortDigest = "";
    int i = 0;
    while (shortDigest.length() < 3) {
        char c = saltHash.charAt(i);
        if (Character.isLetter(c)) {
            shortDigest = shortDigest.concat(String.valueOf(Character.toLowerCase(c)));
        }
        i++;
        if (i >= saltHash.length()) {
            break;
        }
    }
    Log.d(TAG, "Short digest is " + shortDigest);

    return shortDigest;
}

From source file:com.mobiperf.measurements.HttpTask.java

/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off */
@Override//  ww  w .j a  va  2  s  .  co m
public MeasurementResult call() throws MeasurementError {

    int statusCode = HttpTask.DEFAULT_STATUS_CODE;
    long duration = 0;
    long originalHeadersLen = 0;
    long originalBodyLen;
    String headers = null;
    ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD);
    boolean success = false;
    String errorMsg = "";
    InputStream inputStream = null;

    // This is not the ideal way of doing things, as we can pick up data
    // from other processes and be overly cautious in running measurements.
    // However, taking the packet sizes is completely inaccurate, and it's hard to
    // come up with a consistent expected value, unlike with DNS
    RRCTask.PacketMonitor packetmonitor = new RRCTask.PacketMonitor();
    packetmonitor.setBySize();
    packetmonitor.readCurrentPacketValues();

    try {
        // set the download URL, a URL that points to a file on the Internet
        // this is the file to be downloaded
        HttpDesc task = (HttpDesc) this.measurementDesc;
        String urlStr = task.url;

        // TODO(Wenjie): Need to set timeout for the HTTP methods
        httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent));
        HttpRequestBase request = null;
        if (task.method.compareToIgnoreCase("head") == 0) {
            request = new HttpHead(urlStr);
        } else if (task.method.compareToIgnoreCase("get") == 0) {
            request = new HttpGet(urlStr);
        } else if (task.method.compareToIgnoreCase("post") == 0) {
            request = new HttpPost(urlStr);
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(new StringEntity(task.body));
        } else {
            // Use GET by default
            request = new HttpGet(urlStr);
        }

        if (task.headers != null && task.headers.trim().length() > 0) {
            for (String headerLine : task.headers.split("\r\n")) {
                String tokens[] = headerLine.split(":");
                if (tokens.length == 2) {
                    request.addHeader(tokens[0], tokens[1]);
                } else {
                    throw new MeasurementError("Incorrect header line: " + headerLine);
                }
            }
        }

        byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE];
        int readLen;
        int totalBodyLen = 0;

        long startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(request);

        /* TODO(Wenjie): HttpClient does not automatically handle the following codes
         * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
         * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
         * 303 See Other. HttpStatus.SC_SEE_OTHER
         * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT
         * 
         * We may want to fetch instead from the redirected page. 
         */
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null) {
            statusCode = statusLine.getStatusCode();
            success = (statusCode == 200);
        }

        /* For HttpClient to work properly, we still want to consume the entire response even if
         * the status code is not 200 
         */
        HttpEntity responseEntity = response.getEntity();
        originalBodyLen = responseEntity.getContentLength();
        long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE;
        // getContentLength() returns negative number if body length is unknown
        if (originalBodyLen > 0) {
            expectedResponseLen = originalBodyLen;
        }

        if (responseEntity != null) {
            inputStream = responseEntity.getContent();
            while ((readLen = inputStream.read(readBuffer)) > 0
                    && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) {
                totalBodyLen += readLen;
                // Fill in the body to report up to MAX_BODY_SIZE
                if (body.remaining() > 0) {
                    int putLen = body.remaining() < readLen ? body.remaining() : readLen;
                    body.put(readBuffer, 0, putLen);
                }
                this.progress = (int) (100 * totalBodyLen / expectedResponseLen);
                this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress);
                broadcastProgressForUser(this.progress);
            }
            duration = System.currentTimeMillis() - startTime;
        }

        Header[] responseHeaders = response.getAllHeaders();
        if (responseHeaders != null) {
            headers = "";
            for (Header hdr : responseHeaders) {
                /*
                 * TODO(Wenjie): There can be preceding and trailing white spaces in
                 * each header field. I cannot find internal methods that return the
                 * number of bytes in a header. The solution here assumes the encoding
                 * is one byte per character.
                 */
                originalHeadersLen += hdr.toString().length();
                headers += hdr.toString() + "\r\n";
            }
        }

        PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

        MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
                phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, success,
                this.measurementDesc);

        result.addResult("code", statusCode);

        dataConsumed = packetmonitor.getPacketsSentDiff();

        if (success) {
            result.addResult("time_ms", duration);
            result.addResult("headers_len", originalHeadersLen);
            result.addResult("body_len", totalBodyLen);
            result.addResult("headers", headers);
            result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT));
        }

        Logger.i(MeasurementJsonConvertor.toJsonString(result));
        return result;
    } catch (MalformedURLException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } catch (IOException e) {
        errorMsg += e.getMessage() + "\n";
        Logger.e(e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Logger.e("Fails to close the input stream from the HTTP response");
            }
        }
        if (httpClient != null) {
            httpClient.close();
        }

    }
    throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg);
}

From source file:jog.my.memory.gcm.ServerUtilities.java

/**
 * Convert images to the string representation
 * @param pics - pictures to send/*from ww  w.  ja  va2 s  .  c om*/
 * @return arraylist of string representation of pictures
 */
public static byte[] convertPhotosToByteRepresentation(ArrayList<Picture> pics) {
    ArrayList<byte[]> listPhotos = new ArrayList<>();
    for (int i = 0; i < pics.size(); i++) {
        String stringEncodedImage = Base64.encodeToString(pics.get(i).getmImageAsByteArray(), Base64.DEFAULT);
        listPhotos.add(pics.get(i).getmImageAsByteArray());
    }
    return listPhotos.get(0);
}