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.example.yudiandrean.socioblood.LoginActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    //FacebookSdk.sdkInitialize(this.getApplicationContext());
    setContentView(R.layout.activity_login);

    try {/*from  www . j  a  va 2  s. c  om*/
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 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) {
    }

    TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
    Fabric.with(this, new Twitter(authConfig));
    //instantiate callbacks manager
    //mCallbackManager = CallbackManager.Factory.create();

    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    Btnregister = (Button) findViewById(R.id.registerbtn);
    btnLogin = (Button) findViewById(R.id.login);
    passreset = (Button) findViewById(R.id.passres);
    //        facebookLogin = (LoginButton) findViewById(R.id.facebook_login);
    //facebookLogin.setReadPermissions(permissionNeeds);

    session = new SessionManager(getApplicationContext());

    // Check if user is already logged in or not
    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(LoginActivity.this, FeedActivity.class);
        startActivity(intent);
        finish();
    }

    //        accessTokenTracker = new AccessTokenTracker() {
    //            @Override
    //            protected void onCurrentAccessTokenChanged(
    //                    AccessToken oldAccessToken,
    //                    AccessToken currentAccessToken) {
    //                // App code
    //            }
    //        };
    //
    //        profileTracker = new ProfileTracker() {
    //            @Override
    //            protected void onCurrentProfileChanged(
    //                    Profile oldProfile,
    //                    Profile currentProfile) {
    //                // App code
    //            }
    //        };

    passreset.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), PasswordReset.class);
            startActivityForResult(myIntent, 0);
            finish();
        }
    });

    Btnregister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Register.class);
            startActivityForResult(myIntent, 0);
            finish();
        }
    });

    /**
     * Login button click event
     * A Toast is set to alert when the Email and Password field is empty
     **/
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

            if ((!inputEmail.getText().toString().equals(""))
                    && (!inputPassword.getText().toString().equals(""))) {
                NetAsync(view);
            } else if ((!inputEmail.getText().toString().equals(""))) {
                Toast.makeText(getApplicationContext(), "Password field empty", Toast.LENGTH_SHORT).show();
            } else if ((!inputPassword.getText().toString().equals(""))) {
                Toast.makeText(getApplicationContext(), "Email field empty", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "Email and Password field are empty",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });

    //        //facebook login
    //        facebookLogin.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
    //
    //
    //            @Override
    //            public void onSuccess(LoginResult loginResults) {
    //                //login ok  get access token
    //                AccessToken.getCurrentAccessToken();
    //
    //
    //            }
    //
    //            @Override
    //            public void onCancel() {
    //
    //                Toast.makeText(getApplicationContext(),
    //                        "Login Cancelled", Toast.LENGTH_SHORT).show();
    //            }
    //
    //
    //            @Override
    //            public void onError(FacebookException e) {
    //                Toast.makeText(getApplicationContext(),
    //                        "Login Failed!", Toast.LENGTH_SHORT).show();
    //            }
    //        });

    //Session Manager

    //        TwitterSession session =
    //                Twitter.getSessionManager().getActiveSession();
    //        TwitterAuthToken authToken = session.getAuthToken();
    //        String token = authToken.token;
    //        String secret = authToken.secret;

    //Guest Authentication
    TwitterCore.getInstance().logInGuest(new Callback<AppSession>() {
        @Override
        public void success(Result<AppSession> result) {
            AppSession guestAppSession = result.data;
        }

        @Override
        public void failure(TwitterException exception) {
            // unable to get an AppSession with guest auth
        }
    });

}

From source file:com.megster.cordova.ble.central.Peripheral.java

static JSONObject byteArrayToJSON(byte[] bytes) throws JSONException {
    JSONObject object = new JSONObject();
    object.put("CDVType", "ArrayBuffer");
    object.put("data", Base64.encodeToString(bytes, Base64.NO_WRAP));
    return object;
}

From source file:com.facebook.samples.hellofacebook.MapFriends.java

private void getKeyHash() {
    try {//w w  w. j a v a2 s  .  c o m
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 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 (NameNotFoundException e) {
        Log.d("getKeyHash()", "NameNotFoundException");
    } catch (NoSuchAlgorithmException e) {
        Log.d("getKeyHash()", "NoSuchAlgorithmException");
    }
}

From source file:com.paymaya.sdk.android.checkout.PayMayaCheckoutActivity.java

private void requestCreateCheckout() {
    new AsyncTask<Void, Void, Response>() {
        @Override/*from   ww  w.j  a v a 2  s .  c o m*/
        protected Response doInBackground(Void... voids) {
            try {
                Request request = new Request(Request.Method.POST,
                        PayMayaConfig.getEnvironment() == PayMayaConfig.ENVIRONMENT_PRODUCTION
                                ? BuildConfig.API_CHECKOUT_ENDPOINT_PRODUCTION
                                : BuildConfig.API_CHECKOUT_ENDPOINT_SANDBOX);

                byte[] body = JSONUtils.toJSON(mCheckout).toString().getBytes();
                request.setBody(body);

                String key = mClientKey + ":";
                String authorization = Base64.encodeToString(key.getBytes(), Base64.DEFAULT);

                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("Authorization", "Basic " + authorization);
                headers.put("Content-Length", Integer.toString(body.length));
                request.setHeaders(headers);

                AndroidClient androidClient = new AndroidClient();
                return androidClient.call(request);
            } catch (JSONException e) {
                return new Response(-1, "");
            }
        }

        @Override
        protected void onPostExecute(Response response) {
            if (response.getCode() == 200) {
                try {
                    JSONObject responseBody = new JSONObject(response.getResponse());
                    mSessionRedirectUrl = responseBody.getString("redirectUrl");
                    String[] redirectUrlParts = mSessionRedirectUrl.split("\\?");
                    mSessionCheckoutId = redirectUrlParts[redirectUrlParts.length - 1];
                    if (Build.MANUFACTURER.toLowerCase().contains("samsung")) {
                        mSessionRedirectUrl += "&cssfix=true";
                    }

                    loadUrl(mSessionRedirectUrl);
                } catch (JSONException e) {
                    finishFailure(e.getMessage());
                }
            } else {
                finishFailure(response.getResponse());
            }
        }
    }.execute();
}

From source file:com.example.socketmobile.android.warrantychecker.network.UserRegistration.java

private Object fetchWarranty(String id, String authString, String query) throws IOException {
    InputStream is = null;/*from   w w  w.  java 2s .  com*/
    RegistrationApiResponse result = null;
    RegistrationApiErrorResponse errorResult = null;
    String authHeader = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    try {
        URL url = new URL(baseUrl + id + "/registrations");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(10000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.flush();
        writer.close();
        os.close();

        conn.connect();
        int response = conn.getResponseCode();

        Log.d(TAG, "Warranty query responded: " + response);
        switch (response / 100) {
        case 2:
            is = conn.getInputStream();
            RegistrationApiResponse.Reader reader = new RegistrationApiResponse.Reader();
            result = reader.readJsonStream(is);
            break;
        case 4:
        case 5:
            is = conn.getErrorStream();

            RegistrationApiErrorResponse.Reader errorReader = new RegistrationApiErrorResponse.Reader();
            errorResult = errorReader.readErrorJsonStream(is);

            break;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return (result != null) ? result : errorResult;
}

From source file:com.ericrgon.postmark.BaseFragmentActivity.java

protected void encrypt(SecretKey key, String destinationPreference, String value) {
    byte[] encryptedValue = SecurityUtil.encrypt(key, value);
    SharedPreferences.Editor editor = getSharedPreferences(CREDENTIALS_PREF_FILE, MODE_PRIVATE).edit();
    editor.putString(destinationPreference, Base64.encodeToString(encryptedValue, Base64.DEFAULT));
    editor.apply();/* ww  w  .j av  a  2 s.  c om*/
}

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

@Override
public void open(@NonNull final Callback callback) {
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(mConsumerKey)
            .setOAuthConsumerSecret(mConsumerSecret).build();

    final Twitter instance = new TwitterFactory(configuration).getInstance();
    if (mAccessToken != null) {
        instance.setOAuthAccessToken(mAccessToken);
    }/*from  w  w w  . j  a  va 2s. 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()) {
                SharedPreferences preferences = getActivity().getSharedPreferences("twitter",
                        Activity.MODE_PRIVATE);
                preferences.edit().clear().apply();

                mAccessToken = null;
                instance.setOAuthAccessToken(null);
                return 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();
                                } 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();
                                    callback.onSessionOpened(accessToken);
                                    mAccessToken = accessToken;

                                    return accessToken;
                                }

                                return null;
                            }
                        });
            } else {
                callback.onSessionOpened(mAccessToken);
                return Task.forResult(mAccessToken);
            }
        }
    });
}

From source file:org.akvo.flow.api.FlowApi.java

private String getAuthorization(String query) {
    String authorization = null;/*w ww  . j a  v  a  2s  . c om*/
    try {
        SecretKeySpec signingKey = new SecretKeySpec(API_KEY.getBytes(), "HmacSHA1");

        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        byte[] rawHmac = mac.doFinal(query.getBytes());

        authorization = Base64.encodeToString(rawHmac, Base64.DEFAULT);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, e.getMessage());
    } catch (InvalidKeyException e) {
        Log.e(TAG, e.getMessage());
    }

    return authorization;
}

From source file:com.orange.oidc.secproxy_service.MySecureProxy.java

public String getClientSecretBasic() {

    String bearer = (SECURE_PROXY_client_id + ":" + SECURE_PROXY_secret);
    return Base64.encodeToString(bearer.getBytes(), Base64.DEFAULT);
}