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:azad.hallaji.farzad.com.masirezendegi.PageVirayesh.java

private String encodeImage(Bitmap bm) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String encImage = Base64.encodeToString(b, Base64.DEFAULT);

    return encImage;
}

From source file:com.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java

/**
 * Signs the data using the key pair stored in the Android Key Store.  This signature can be
 * used with the data later to verify it was signed by this application.
 * @return A string encoding of the data signature generated
 *///from ww  w  .j a  v a2  s.com
public String signData(String inputStr) throws KeyStoreException, UnrecoverableEntryException,
        NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException, CertificateException {
    byte[] data = inputStr.getBytes();

    // BEGIN_INCLUDE(sign_load_keystore)
    KeyStore ks = KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);

    // Weird artifact of Java API.  If you don't have an InputStream to load, you still need
    // to call "load", or it'll crash.
    ks.load(null);

    // Load the key pair from the Android Key Store
    KeyStore.Entry entry = ks.getEntry(mAlias, null);

    /* If the entry is null, keys were never stored under this alias.
     * Debug steps in this situation would be:
     * -Check the list of aliases by iterating over Keystore.aliases(), be sure the alias
     *   exists.
     * -If that's empty, verify they were both stored and pulled from the same keystore
     *   "AndroidKeyStore"
     */
    if (entry == null) {
        Log.w(TAG, "No key found under alias: " + mAlias);
        Log.w(TAG, "Exiting signData()...");
        return null;
    }

    /* If entry is not a KeyStore.PrivateKeyEntry, it might have gotten stored in a previous
     * iteration of your application that was using some other mechanism, or been overwritten
     * by something else using the same keystore with the same alias.
     * You can determine the type using entry.getClass() and debug from there.
     */
    if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
        Log.w(TAG, "Not an instance of a PrivateKeyEntry");
        Log.w(TAG, "Exiting signData()...");
        return null;
    }
    // END_INCLUDE(sign_data)

    // BEGIN_INCLUDE(sign_create_signature)
    // This class doesn't actually represent the signature,
    // just the engine for creating/verifying signatures, using
    // the specified algorithm.
    Signature s = Signature.getInstance(SecurityConstants.SIGNATURE_SHA256withRSA);

    // Initialize Signature using specified private key
    s.initSign(((KeyStore.PrivateKeyEntry) entry).getPrivateKey());

    // Sign the data, store the result as a Base64 encoded String.
    s.update(data);
    byte[] signature = s.sign();
    String result = Base64.encodeToString(signature, Base64.DEFAULT);
    // END_INCLUDE(sign_data)

    return result;
}

From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java

@Override
public void tweets(final StatusUpdate latestStatus, @NonNull final ResponseCallback callback) {
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(mConsumerKey)
            .setOAuthConsumerSecret(mConsumerSecret).build();

    final Twitter instance = new TwitterFactory(configuration).getInstance();
    if (mAccessToken != null) {
        instance.setOAuthAccessToken(mAccessToken);
    }/*from www  . j a v  a 2 s.c o  m*/

    doValidate(mAccessToken, instance).continueWithTask(new Continuation<User, Task<AccessToken>>() {
        @Override
        public Task<AccessToken> then(Task<User> task) throws Exception {
            if (task.isFaulted()) {
                final Task<AccessToken>.TaskCompletionSource source = Task.<AccessToken>create();
                SharedPreferences preferences = getActivity().getSharedPreferences("twitter",
                        Activity.MODE_PRIVATE);
                preferences.edit().clear().apply();

                mAccessToken = null;
                instance.setOAuthAccessToken(null);
                doGetAuthenticationURL(instance).onSuccessTask(new Continuation<RequestToken, Task<Bundle>>() {
                    @Override
                    public Task<Bundle> then(Task<RequestToken> task) throws Exception {
                        return doDialogAuthentication(task.getResult());
                    }
                }).onSuccessTask(new Continuation<Bundle, Task<AccessToken>>() {
                    @Override
                    public Task<AccessToken> then(Task<Bundle> task) throws Exception {
                        return doGetAccessToken(instance, task.getResult());
                    }
                }).continueWith(new Continuation<AccessToken, AccessToken>() {
                    @Override
                    public AccessToken then(Task<AccessToken> task) throws Exception {
                        if (task.isFaulted()) {
                            Log.d(BuildConfig.DEBUG_TAG, "Failed", task.getError());
                            // Toast.makeText(getActivity(), task.getError().getMessage(), Toast.LENGTH_LONG).show();
                            // callback.onCancelled(task.getError());
                            source.trySetError(task.getError());
                        } else if (task.isCompleted()) {
                            AccessToken accessToken = task.getResult();
                            String serialized = Base64.encodeToString(SerializationUtils.serialize(accessToken),
                                    Base64.DEFAULT);

                            SharedPreferences preferences = getActivity().getSharedPreferences("twitter",
                                    Activity.MODE_PRIVATE);
                            preferences.edit().putString("access_token_str", serialized).apply();
                            instance.setOAuthAccessToken(accessToken);

                            mAccessToken = accessToken;
                            source.trySetResult(mAccessToken);
                            return accessToken;
                        }

                        return null;
                    }
                });
                return source.getTask();
            } else {
                return Task.forResult(mAccessToken);
            }
            //            }
            //        }).onSuccessTask(new Continuation<AccessToken, Task<Map<String, RateLimitStatus>>>() {
            //            @Override
            //            public Task<Map<String, RateLimitStatus>> then(Task<AccessToken> task) throws Exception {
            //                return doCheckStatus(instance);
        }
    }).onSuccessTask(new Continuation<AccessToken, Task<Status>>() {
        @Override
        public Task<Status> then(Task<AccessToken> task) throws Exception {
            //                Map<String, RateLimitStatus> result = task.getResult();

            return doTweet(instance, latestStatus);
        }
    }).continueWith(new Continuation<Status, Object>() {
        @Override
        public Object then(Task<Status> task) throws Exception {
            if (task.isFaulted()) {
                Log.d(BuildConfig.DEBUG_TAG, "Failed", task.getError());
                String message = task.getError().getMessage();
                if (!TextUtils.isEmpty(message)) {
                    //                        Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
                }
                callback.onCancelled(task.getError());
            } else if (task.isCompleted()) {
                callback.onCompleted(task.getResult());
            }

            return null;
        }
    });
}

From source file:azad.hallaji.farzad.com.masirezendegi.PageVirayesh.java

private String encodeImage(String path) {
    File imagefile = new File(path);
    FileInputStream fis = null;//from w w  w. j av  a  2 s . co m
    try {
        fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Bitmap bm = BitmapFactory.decodeStream(fis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String encImage = Base64.encodeToString(b, Base64.DEFAULT);
    //Base64.de
    return encImage;

}

From source file:com.microsoft.windowsazure.messaging.Connection.java

/**
 * Generates an AuthToken//from  ww w. j ava  2  s  .c  om
 * @param url   The target URL
 * @return   An AuthToken
 * @throws java.security.InvalidKeyException
 */
private String generateAuthToken(String url) throws InvalidKeyException {

    String keyName = mConnectionData.get(SHARED_ACCESS_KEY_NAME);
    if (isNullOrWhiteSpace(keyName)) {
        throw new AssertionError("SharedAccessKeyName");
    }

    String key = mConnectionData.get(SHARED_ACCESS_KEY);
    if (isNullOrWhiteSpace(key)) {
        throw new AssertionError("SharedAccessKey");
    }

    try {
        url = URLEncoder.encode(url, UTF8_ENCODING).toLowerCase(Locale.ENGLISH);
    } catch (UnsupportedEncodingException e) {
        // this shouldn't happen because of the fixed encoding
    }

    // Set expiration in seconds
    Calendar expireDate = Calendar.getInstance(TimeZone.getTimeZone(UTC_TIME_ZONE));
    expireDate.add(Calendar.MINUTE, EXPIRE_MINUTES);

    long expires = expireDate.getTimeInMillis() / 1000;

    String toSign = url + '\n' + expires;

    // sign

    byte[] bytesToSign = toSign.getBytes();
    Mac mac = null;
    try {
        mac = Mac.getInstance("HmacSHA256");
    } catch (NoSuchAlgorithmException e) {
        // This shouldn't happen because of the fixed algorithm
    }

    SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
    mac.init(secret);
    byte[] signedHash = mac.doFinal(bytesToSign);
    String base64Signature = Base64.encodeToString(signedHash, Base64.DEFAULT);
    base64Signature = base64Signature.trim();
    try {
        base64Signature = URLEncoder.encode(base64Signature, UTF8_ENCODING);
    } catch (UnsupportedEncodingException e) {
        // this shouldn't happen because of the fixed encoding
    }

    // construct authorization string
    String token = "SharedAccessSignature sr=" + url + "&sig=" + base64Signature + "&se=" + expires + "&skn="
            + keyName;

    return token;
}

From source file:com.example.httpjson.AppEngineClient.java

public String getTokenFromServer() {
    String s = null;/*from  w w  w . jav a2s  . c o m*/
    try {

        URL uri = new URL("https://rtonames.sprintlabs.io/token");

        Map<String, List<String>> headers = new HashMap<String, List<String>>();

        String key = "Authorization";
        String authStr = "6eece178-9fcf-45b7-ab50-08b8066daabe:e494a4e72b6f7c7672b74d311cbabf2672be8c24c9496554077936097195a5ac69b6acd11eb09a1ae07a40d2e7f0348d";
        String encoding = Base64.encodeToString(authStr.getBytes(), Base64.DEFAULT);
        encoding = encoding.replace("\n", "").replace("\r", "");

        System.out.println(encoding);
        List<String> value = Arrays.asList("Basic " + encoding);

        headers.put(key, value);

        AppEngineClient aec1 = new AppEngineClient();
        Request request = aec1.new GET(uri, headers);

        AsyncTask<Request, Void, Response> obj = new asyncclass().execute(request);

        Response response = obj.get();

        obj.cancel(true);

        obj = null;

        String body = null;
        try {
            body = new String(response.body, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        JSONObject tokenjson = AppEngineClient.getJSONObject(body);

        if (tokenjson.has("token")) {
            try {
                s = tokenjson.getString("token");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return s;
}

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

/**
 * Convert images to the string representation
 * @param pics - pictures to send/*ww  w. j  a  va2 s.  c  o m*/
 * @return arraylist of string representation of pictures
 */
public static ArrayList<String> convertPhotosToStringRepresentation(ArrayList<Picture> pics) {
    ArrayList<String> listPhotos = new ArrayList<>();
    for (int i = 0; i < pics.size(); i++) {
        //            String stringEncodedImage =
        //                    Base64.encodeToString(pics.get(i).getmImageAsByteArray(), Base64.DEFAULT);
        //            listPhotos.add(stringEncodedImage);
        Bitmap bitmap = pics.get(i).getmImage();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        byte[] bitmapByte = outputStream.toByteArray();
        listPhotos.add(Base64.encodeToString(bitmapByte, Base64.DEFAULT));
        //            try {
        //                listPhotos.add(new String(bitmapByte));
        //            }
        //            catch(Exception e){
        //                Log.d(TAG,"The encoding didn't work");
        //            }
    }
    return listPhotos;
}

From source file:com.aknowledge.v1.automation.RemoteActivity.java

private void getDevices() {
    Log.d("RemoteActivity", "Get Devices URL = " + hostname + "/api/devices");
    JsonArrayRequest req = new JsonArrayRequest(hostname + "/api/devices", new Response.Listener<JSONArray>() {
        @Override/* w ww . ja  v  a 2  s  . c  om*/
        public void onResponse(JSONArray response) {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            Log.d("RemoteActivity", "Get Devices " + response.toString());
            parseMyDevices(response.toString());
            if (handler != null) {
                handler.removeCallbacksAndMessages(null);
            }
            handler = new Handler();
            Runnable scheduledUpdate = new Runnable() {
                @Override
                public void run() {
                    getDevices();
                }

            };
            handler.postDelayed(scheduledUpdate, refreshRate);
            // pDialog.hide();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Log.d("RemoteActivity", "Error: " + error.getMessage());
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            showServerAlert();
        }

    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            String authString = user + ":" + pass;
            String encodedPass = null;
            try {
                encodedPass = Base64.encodeToString(authString.getBytes(), Base64.DEFAULT);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d("Remote Activity", pass + " " + encodedPass);
            headers.put("Content-Type", "application/json");
            headers.put("Authorization", "Basic " + encodedPass);
            return headers;
        }
    };
    req.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    PyHomeController.getInstance().addToRequestQueue(req, statusTag);

}

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

private static String calculateMAC(String key, String normalizedString, String algorithm) {
    String macString = "";
    try {// w  w w. j  av a2 s .c  om
        System.out.println("algorithm=" + algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key.getBytes(), algorithm));
        macString = Base64.encodeToString(mac.doFinal(normalizedString.getBytes()), Base64.DEFAULT);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE, null, ex);
    }
    return macString;
}

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 . ja v a2s.  com
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);
}