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.gnut3ll4.android.basicandroidkeystore.MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText = (EditText) findViewById(R.id.edittext);
    button = (Button) findViewById(R.id.button);

    mKeyStoreHelper = new KeyStoreHelper();
    mKeyStoreHelper.setAlias(ALIAS);/*from  w ww .j av a  2 s . c o  m*/
    initializeLogging();

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            try {

                //Encrypt
                KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
                ks.load(null);
                Key key = ks.getKey(ALIAS, null);

                if (key instanceof PrivateKey) {

                    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
                    cipher.init(Cipher.ENCRYPT_MODE, ks.getCertificate(ALIAS).getPublicKey());
                    encryptedBytes = cipher.doFinal(editText.getText().toString().getBytes());

                    Log.d(TAG, "Encrypted bytes : " + Base64.encodeToString(encryptedBytes, Base64.DEFAULT));
                }

                //Decrypt
                PrivateKey privateKey = loadPrivateKey(ALIAS);
                Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
                cipher.init(Cipher.DECRYPT_MODE, privateKey);
                byte[] bytes = cipher.doFinal(encryptedBytes);

                Log.d(TAG, "Decrypted string : " + new String(bytes, "UTF-8"));

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });

}

From source file:com.igames2go.t4f.Activities.LoginPage.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mApplication = ((T4FApplication) getApplication());
    mApplication.setPlay_mode(T4FApplication.PLAY_MODE_LOGIN);
    try {//from w  ww. j  a v  a2 s  .c o  m
        PackageInfo info = getPackageManager().getPackageInfo("com.igames2go.t4f",
                PackageManager.GET_SIGNATURES);
        for (android.content.pm.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) {

    } catch (NoSuchAlgorithmException e) {

    }

    setContentView(R.layout.main);

    pref = getSharedPreferences("user_info", MODE_PRIVATE);

    mApplication = (T4FApplication) getApplication();
    app_id = getResources().getString(R.string.appid);

    inputEmail = (EditText) findViewById(R.id.emailText);
    inputPassword = (EditText) findViewById(R.id.passwordText);
    btnLogin = (ImageButton) findViewById(R.id.loginButton);
    btnSignUp = (ImageButton) findViewById(R.id.signupButton);
    btnForgot = (ImageButton) findViewById(R.id.forgotButton);
    btnNoLoginPlay = (ImageButton) findViewById(R.id.noLoginPlayButton);
    btnHowToPlay = (ImageButton) findViewById(R.id.howToPlayButton);
    btnHelp = (ImageButton) findViewById(R.id.helpButton);
    //loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);

    inputEmail.setText(pref.getString("user_email", ""));
    inputPassword.setText(pref.getString("user_password", ""));

    btnLogin.setOnClickListener(this);
    btnSignUp.setOnClickListener(this);
    btnForgot.setOnClickListener(this);
    btnNoLoginPlay.setOnClickListener(this);
    btnHowToPlay.setOnClickListener(this);
    btnHelp.setOnClickListener(this);
}

From source file:com.nextgis.maplib.map.RemoteTMSLayer.java

@Override
public Bitmap getBitmap(TileItem tile) {
    Bitmap ret;/*from   w ww  .  j  a  v  a2s.co  m*/
    // try to get tile from local cache
    File tilePath = new File(mPath, tile.toString("{z}/{x}/{y}" + TILE_EXT));
    if (tilePath.exists()
            && System.currentTimeMillis() - tilePath.lastModified() < DEFAULT_MAXIMUM_CACHED_FILE_AGE) {
        ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
        if (ret != null) {
            return ret;
        }
    }

    if (!mNet.isNetworkAvailable()) { //return tile from cache
        ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
        return ret;
    }
    // try to get tile from remote
    String url = tile.toString(getURLSubdomain());
    Log.d(TAG, "url: " + url);
    try {

        final HttpGet get = new HttpGet(url);

        //basic auth
        if (null != mLogin && mLogin.length() > 0 && null != mPassword && mPassword.length() > 0) {
            get.setHeader("Accept", "*/*");
            final String basicAuth = "Basic "
                    + Base64.encodeToString((mLogin + ":" + mPassword).getBytes(), Base64.NO_WRAP);
            get.setHeader("Authorization", basicAuth);
        }

        final DefaultHttpClient HTTPClient = mNet.getHttpClient();
        final HttpResponse response = HTTPClient.execute(get);

        // Check to see if we got success
        final org.apache.http.StatusLine line = response.getStatusLine();
        if (line.getStatusCode() != 200) {
            Log.d(TAG, "Problem downloading MapTile: " + url + " HTTP response: " + line);
            ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
            return ret;
        }

        final HttpEntity entity = response.getEntity();
        if (entity == null) {
            Log.d(TAG, "No content downloading MapTile: " + url);
            ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
            return ret;
        }

        FileUtil.createDir(tilePath.getParentFile());

        InputStream input = entity.getContent();
        OutputStream output = new FileOutputStream(tilePath.getAbsolutePath());
        byte data[] = new byte[IO_BUFFER_SIZE];

        FileUtil.copyStream(input, output, data, IO_BUFFER_SIZE);

        output.close();
        input.close();
        ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
        return ret;

    } catch (IOException e) {
        Log.d(TAG, "Problem downloading MapTile: " + url + " Error: " + e.getLocalizedMessage());
    }

    ret = BitmapFactory.decodeFile(tilePath.getAbsolutePath());
    return ret;
}

From source file:eu.codeplumbers.cosi.services.CosiCallService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiCallService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    allCalls = new ArrayList<>();

    Device device = Device.registeredDevice();

    // cozy register device url
    designUrl = device.getUrl() + "/ds-api/request/call/all/";
    syncUrl = device.getUrl() + "/ds-api/data/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();//from   w w  w . j a  v  a 2s  .com

    if (isNetworkAvailable()) {
        try {
            // read local sms log first
            readCallLog();
            EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE, "Getting remote calls from Cozy..."));
            getRemoteCalls();

            mBuilder.setContentText(getString(R.string.lbl_sms_sync_done));
            mBuilder.setProgress(0, 0, false);
            mNotifyManager.notify(notification_id, mBuilder.build());

            if (!allCalls.isEmpty()) {
                mNotifyManager.cancel(notification_id);
                sendChangesToCozy();
                EventBus.getDefault().post(new CallSyncEvent(REFRESH, "Sync OK"));
            } else {
                EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, "Sync failed"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            mSyncRunning = false;
            EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.Post.java

@Override
public BufferedReader execute() {
    String jSon = null;/*  w w  w  .ja  v a 2s  . c  om*/
    String uri = null;

    //init check
    if (!Synergykit.isInit()) {
        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);

        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_ACCEPT, ACCEPT_APPLICATION_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        httpURLConnection.connect();

        //write data
        if (object != null) {
            jSon = GsonWrapper.getGson().toJson(object);
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(jSon.getBytes(CHARSET));
            dataOutputStream.flush();
            dataOutputStream.close();
        }

        statusCode = httpURLConnection.getResponseCode(); //get status code

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return readStream(httpURLConnection.getInputStream());
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.Patch.java

@Override
public BufferedReader execute() {
    String jSon = null;/*from   www  . j  a  v  a2  s .  c  om*/
    String uri = null;

    //init check
    if (!Synergykit.isInit()) {
        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);

        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_ACCEPT, ACCEPT_APPLICATION_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        httpURLConnection.connect();

        //write data
        if (object != null) {
            jSon = GsonWrapper.getGson().toJson(object);
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(jSon.getBytes(CHARSET));
            dataOutputStream.flush();
            dataOutputStream.close();

        }

        statusCode = httpURLConnection.getResponseCode(); //get status code

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return readStream(httpURLConnection.getInputStream());
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}

From source file:eu.codeplumbers.cosi.services.CosiSmsService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiSmsService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    allSms = new ArrayList<>();

    Device device = Device.registeredDevice();

    // cozy register device url
    designUrl = device.getUrl() + "/ds-api/request/sms/all/";
    syncUrl = device.getUrl() + "/ds-api/data/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();// w  w  w .  j av  a 2 s  .  com

    if (isNetworkAvailable()) {
        try {
            // read local sms log first
            readSmsDatabase();
            EventBus.getDefault().post(new SmsSyncEvent(SYNC_MESSAGE, "Getting remote messages from Cozy..."));
            getRemoteMessages();

            mBuilder.setContentText(getString(R.string.lbl_sms_sync_done));
            mBuilder.setProgress(0, 0, false);
            mNotifyManager.notify(notification_id, mBuilder.build());

            if (!allSms.isEmpty()) {
                mNotifyManager.cancel(notification_id);
                sendChangesToCozy();
                EventBus.getDefault().post(new SmsSyncEvent(REFRESH, "Sync OK"));
            } else {
                EventBus.getDefault().post(new MessageEvent(SERVICE_ERROR, "Sync failed"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            mSyncRunning = false;
            EventBus.getDefault().post(new MessageEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new MessageEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}

From source file:com.mojio.mojiosdk.networking.MojioRequest.java

public MojioRequest(Context appContext, int method, String url, Class<T> clazz, Bitmap contentBody,
        Response.Listener<T> listener, Response.ErrorListener errorListener) {

    super(method, url, errorListener);
    commonInit(appContext, method, url, clazz, listener, errorListener);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    contentBody.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

    this.imageByteArray = b;
    this.contentBody = imageEncoded;
}

From source file:com.socialapp.eventmanager.LoginActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        userSkippedLogin = savedInstanceState.getBoolean(USER_SKIPPED_LOGIN_KEY);
    }/*  www. j  av  a 2 s. co  m*/

    try {
        PackageInfo info = getPackageManager().getPackageInfo("com.socialapp.eventmanager",
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            String keyHash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
            Log.d("************* KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (PackageManager.NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }

    FacebookSdk.sdkInitialize(getApplicationContext());

    callbackManager = CallbackManager.Factory.create();

    accessTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {

            checkAndRedirectOnFBLogin();

            if (isResumed) {
                FragmentManager manager = getSupportFragmentManager();
                int backStackSize = manager.getBackStackEntryCount();
                for (int i = 0; i < backStackSize; i++) {
                    manager.popBackStack();
                }
                if (currentAccessToken != null) {
                    // showFragment(SELECTION, false);
                } else {
                    showFragment(SPLASH, true);
                }
            }
        }
    };

    setContentView(R.layout.activity_login);

    FragmentManager fm = getSupportFragmentManager();
    SplashFragment splashFragment = (SplashFragment) fm.findFragmentById(R.id.splashFragment);
    fragments[SPLASH] = splashFragment;

    FragmentTransaction transaction = fm.beginTransaction();
    // for(int i = 0; i < fragments.length; i++) {
    transaction.hide(fragments[0]);
    // }
    transaction.commit();

    splashFragment.setSkipLoginCallback(new SplashFragment.SkipLoginCallback() {
        @Override
        public void onSkipLoginPressed() {
            userSkippedLogin = true;
            //showFragment(SELECTION, false);
        }
    });

    accessTokenTracker.startTracking();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String userLoggedIn = prefs.getString("email", null);
    if (userLoggedIn != null) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }
}