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:de.duenndns.ssl.MemorizingTrustManager.java

private static String getBase64Hash(X509Certificate certificate, String digest)
        throws CertificateEncodingException {
    MessageDigest md;//from ww w  . j a va 2 s.  c  o m
    try {
        md = MessageDigest.getInstance(digest);
    } catch (NoSuchAlgorithmException e) {
        return null;
    }
    md.update(certificate.getEncoded());
    return Base64.encodeToString(md.digest(), Base64.NO_WRAP);
}

From source file:com.goodhustle.ouyaunitybridge.OuyaUnityActivity.java

public void requestPurchase(final String productId)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());
    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", productId);
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();
    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);//w ww . j  a v a2 s.c o m
    SecretKey key = new SecretKeySpec(keyBytes, "AES");
    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));
    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);
    Purchasable purchasable = new Purchasable(productId, Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
            Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP));
    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, productId);
    }
    ouyaFacade.requestPurchase(purchasable, new PurchaseListener(productId));
}

From source file:at.florian_lentsch.expirysync.net.ServerProxy.java

private JSONObject entryToJson(ProductEntry entry, ArrayList<ArticleImage> imageList) {
    JSONObject paramObj = new JSONObject();

    try {// ww  w  .  jav a  2  s  .com
        Article article = entry.article;

        JSONArray imagesArr = new JSONArray();
        for (ArticleImage image : imageList) {
            if (image.serverId != 0) { // for now only post new images
                continue;
            }

            JSONObject imageObj = new JSONObject();
            imageObj.put("image_data", Base64.encodeToString(image.imageData, Base64.NO_WRAP)); //TODO: fix this warning!
            imageObj.put("mime_type", "image/jpeg");
            imageObj.put("original_extname", ".jpg");

            imagesArr.put(imageObj);
        }

        JSONObject articleObj = new JSONObject();
        articleObj.put("barcode", article.barcode);
        articleObj.put("name", article.name);
        articleObj.put("images", imagesArr);

        JSONObject entryObj = new JSONObject();
        if (entry.serverId > 0) {
            entryObj.put("id", entry.serverId);
        }
        entryObj.put("description", entry.description);
        entryObj.put("expiration_date", entry.expiration_date);
        entryObj.put("amount", entry.amount);
        entryObj.put("location_id", entry.location.serverId);
        entryObj.put("article", articleObj);
        paramObj.put("product_entry", entryObj);
    } catch (JSONException e) {
        // just leave param obj empty - the request will then fail anyway
    }

    return paramObj;
}

From source file:com.appunite.websocket.WebSocket.java

/**
 * Verify if header Sec-WebSocket-Accept value is correct with sent key
 * value (thread safe)//w ww  .ja  v  a2  s. c o  m
 * 
 * @param key key that was sent to server
 * @param acceptValue accept value received from server
 * @return true if accept value match key
 */
private static boolean verifyHandshakeAcceptValue(String key, String acceptValue) {
    String base = key + MAGIC_STRING;
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] baseBytes = EncodingUtils.getAsciiBytes(base);
        md.update(baseBytes);
        byte[] sha1hash = md.digest();
        String expectedValue = Base64.encodeToString(sha1hash, Base64.NO_WRAP);
        return expectedValue.equals(acceptValue);
    } catch (NoSuchAlgorithmException e) {
        // if not found sha1 assume that response
        // value is OK
        return true;
    }
}

From source file:com.facebook.FacebookSdk.java

/**
 * Internal call please don't use directly.
 * @param context The application context.
 * @return The application signature.//from   w ww . ja v a2s. c  o m
 */
public static String getApplicationSignature(Context context) {
    Validate.sdkInitialized();
    if (context == null) {
        return null;
    }
    PackageManager packageManager = context.getPackageManager();
    if (packageManager == null) {
        return null;
    }

    String packageName = context.getPackageName();
    PackageInfo pInfo;
    try {
        pInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
    } catch (PackageManager.NameNotFoundException e) {
        return null;
    }

    Signature[] signatures = pInfo.signatures;
    if (signatures == null || signatures.length == 0) {
        return null;
    }

    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        return null;
    }

    md.update(pInfo.signatures[0].toByteArray());
    return Base64.encodeToString(md.digest(), Base64.URL_SAFE | Base64.NO_PADDING);
}

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

private boolean validCertificate(String cert_string) {
    boolean result = false;
    if (!ConfigHelper.checkErroneousDownload(cert_string)) {
        X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(cert_string);
        try {/*from ww  w.  j av a2 s .  co m*/
            if (certificate != null) {
                JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, ""));
                String fingerprint = provider_json.getString(Provider.CA_CERT_FINGERPRINT);
                String encoding = fingerprint.split(":")[0];
                String expected_fingerprint = fingerprint.split(":")[1];
                String real_fingerprint = base64toHex(Base64.encodeToString(
                        MessageDigest.getInstance(encoding).digest(certificate.getEncoded()), Base64.DEFAULT));

                result = real_fingerprint.trim().equalsIgnoreCase(expected_fingerprint.trim());
            } else
                result = false;
        } catch (JSONException e) {
            result = false;
        } catch (NoSuchAlgorithmException e) {
            result = false;
        } catch (CertificateEncodingException e) {
            result = false;
        }
    }

    return result;
}

From source file:com.appunite.websocket.WebSocket.java

/**
 * This method will create 16 bity random key encoded to base64 for header.
 * If mSecureRandom generator is not accessible it will generate empty array
 * encoded with base64 (thread safe)/*from   ww w  .j  a va2 s  . c o m*/
 * 
 * @return random handshake key
 */
private String generateHandshakeSecret() {
    synchronized (mSecureRandom) {
        byte[] nonce = new byte[16];
        if (mSecureRandom.isPresent()) {
            mSecureRandom.get().nextBytes(nonce);
        } else {
            Arrays.fill(nonce, (byte) 0);
        }
        return Base64.encodeToString(nonce, Base64.NO_WRAP);
    }
}

From source file:com.chaosinmotion.securechat.messages.SCMessageQueue.java

/************************************************************************/

private void encodeMessages(byte[] cdata, final String sender, final int senderID,
        List<SCDeviceCache.Device> sarray, List<SCDeviceCache.Device> marray, final SenderCompletion callback)
        throws UnsupportedEncodingException {
    /*//from   w ww  . ja  v a2  s .  c  o  m
     *  Calculate message checksum
     */

    String checksum = SCSHA256.sha256(cdata);

    /*
     *  Build the encoding list to encode all sent messages.
     */

    JSONArray messages = new JSONArray();

    // Devices we're sending to
    for (SCDeviceCache.Device d : sarray) {
        SCRSAEncoder encoder = d.getPublicKey();
        byte[] encoded = new byte[0];
        try {
            encoded = encoder.encodeData(cdata);
            String message = Base64.encodeToString(encoded, Base64.DEFAULT);
            JSONObject ds = new JSONObject();
            ds.put("checksum", checksum);
            ds.put("message", message);
            ds.put("deviceid", d.getDeviceID());
            messages.put(ds);
        } catch (Exception e) {
            Log.d("SecureChat", "Exception", e);
            // Should not happen; only if there is a constant error above
        }
    }

    // My devices
    for (SCDeviceCache.Device d : marray) {
        if (d.getDeviceID().equals(SCRSAManager.shared().getDeviceUUID())) {
            // Skip me; we put me last
            continue;
        }

        SCRSAEncoder encoder = d.getPublicKey();
        byte[] encoded = new byte[0];
        try {
            encoded = encoder.encodeData(cdata);
            String message = Base64.encodeToString(encoded, Base64.DEFAULT);
            JSONObject ds = new JSONObject();
            ds.put("checksum", checksum);
            ds.put("message", message);
            ds.put("deviceid", d.getDeviceID());
            ds.put("destuser", senderID);
            messages.put(ds);
        } catch (Exception e) {
            Log.d("SecureChat", "Exception", e);
            // Should not happen; only if there is a constant error above
        }
    }

    // Encode for myself. This is kind of a kludge; we need
    // the message ID from the back end to assure proper sorting.
    // But we only get that if this is the last message in the
    // array of messages. (See SendMessages.java.)
    SCRSAEncoder encoder = new SCRSAEncoder(SCRSAManager.shared().getPublicKey());
    byte[] encoded = new byte[0];
    try {
        encoded = encoder.encodeData(cdata);
        String message = Base64.encodeToString(encoded, Base64.DEFAULT);
        JSONObject ds = new JSONObject();
        ds.put("checksum", checksum);
        ds.put("message", message);
        ds.put("deviceid", SCRSAManager.shared().getDeviceUUID());
        ds.put("destuser", senderID);
        messages.put(ds);
    } catch (Exception e) {
        Log.d("SecureChat", "Exception", e);
        // Should not happen; only if there is a constant error above
    }

    /*
     *  Send all messages to the back end.
     */

    JSONObject params = new JSONObject();
    try {
        params.put("messages", messages);
    } catch (JSONException ex) {
        // Should never happen
    }

    final byte[] encodedData = encoded;
    SCNetwork.get().request("messages/sendmessages", params, false, this, new SCNetwork.ResponseInterface() {
        @Override
        public void responseResult(SCNetwork.Response response) {
            if (response.isSuccess()) {
                int messageID = response.getData().optInt("messageid");

                // Insert sent message into myself. This is so we
                // immediately see the sent message right away.
                // Note we may have a race condition but we don't
                // care; the messageID will screen out duplicates.
                insertMessage(senderID, sender, true, messageID, new Date(), encodedData);
            }

            callback.senderCallback(response.isSuccess());
        }
    });
}

From source file:mobile.tiis.appv2.LoginActivity.java

/**
 * This method will take the url built to use the webservice
 * and will try to parse JSON from the webservice stream to get
 * the user and password if they are correct or not. In case correct, fills
 * the Android Account Manager./*from  www  .  j  a v  a  2 s  . c  o m*/
 *
 * <p>This method will throw a Toast message when user and password
 * are not valid
 *
 */

protected void startWebService(final CharSequence loginURL, final String username, final String password) {
    client.setBasicAuth(username, password, true);

    //new handler in case of login error in the thread
    handler = new Handler();

    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                int balanceCounter = 0;
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(loginURL.toString());
                Utils.writeNetworkLogFileOnSD(
                        Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + loginURL.toString());
                httpGet.setHeader("Authorization", "Basic "
                        + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
                HttpResponse httpResponse = httpClient.execute(httpGet);
                InputStream inputStream = httpResponse.getEntity().getContent();
                Log.d("", loginURL.toString());

                ByteArrayInputStream bais = Utils.getMultiReadInputStream(inputStream);
                Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext())
                        + Utils.getStringFromInputStreamAndLeaveStreamOpen(bais));
                bais.reset();
                JsonFactory factory = new JsonFactory();
                JsonParser jsonParser = factory.createJsonParser(bais);
                JsonToken token = jsonParser.nextToken();

                if (token == JsonToken.START_OBJECT) {
                    balanceCounter++;
                    boolean idNextToHfId = false;
                    while (!(balanceCounter == 0)) {
                        token = jsonParser.nextToken();

                        if (token == JsonToken.START_OBJECT) {
                            balanceCounter++;
                        } else if (token == JsonToken.END_OBJECT) {
                            balanceCounter--;
                        } else if (token == JsonToken.FIELD_NAME) {
                            String object = jsonParser.getCurrentName();
                            switch (object) {
                            case "HealthFacilityId":
                                token = jsonParser.nextToken();
                                app.setLoggedInUserHealthFacilityId(jsonParser.getText());
                                Log.d("", "healthFacilityId is: " + jsonParser.getText());
                                idNextToHfId = true;
                                break;
                            case "Firstname":
                                token = jsonParser.nextToken();
                                app.setLoggedInFirstname(jsonParser.getText());
                                Log.d("", "firstname is: " + jsonParser.getText());
                                break;
                            case "Lastname":
                                token = jsonParser.nextToken();
                                app.setLoggedInLastname(jsonParser.getText());
                                Log.d("", "lastname is: " + jsonParser.getText());
                                break;
                            case "Username":
                                token = jsonParser.nextToken();
                                app.setLoggedInUsername(jsonParser.getText());
                                Log.d("", "username is: " + jsonParser.getText());
                                break;
                            case "Lastlogin":
                                token = jsonParser.nextToken();
                                Log.d("", "lastlogin is: " + jsonParser.getText());
                                break;
                            case "Id":
                                if (idNextToHfId) {
                                    token = jsonParser.nextToken();
                                    app.setLoggedInUserId(jsonParser.getText());
                                    Log.d("", "Id is: " + jsonParser.getText());
                                }
                                break;
                            default:
                                break;
                            }
                        }
                    }

                    Account account = new Account(username, ACCOUNT_TYPE);
                    AccountManager accountManager = AccountManager.get(LoginActivity.this);
                    //                        boolean accountCreated = accountManager.addAccountExplicitly(account, LoginActivity.this.password, null);
                    boolean accountCreated = accountManager.addAccountExplicitly(account, password, null);

                    Bundle extras = LoginActivity.this.getIntent().getExtras();
                    if (extras != null) {
                        if (accountCreated) { //Pass the new account back to the account manager
                            AccountAuthenticatorResponse response = extras
                                    .getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
                            Bundle res = new Bundle();
                            res.putString(AccountManager.KEY_ACCOUNT_NAME, username);
                            res.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
                            res.putString(AccountManager.KEY_PASSWORD, password);
                            response.onResult(res);
                        }
                    }

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putBoolean("secondSyncNeeded", true);
                    editor.commit();

                    ContentValues values = new ContentValues();
                    values.put(SQLHandler.SyncColumns.UPDATED, 1);
                    values.put(SQLHandler.UserColumns.FIRSTNAME, app.getLOGGED_IN_FIRSTNAME());
                    values.put(SQLHandler.UserColumns.LASTNAME, app.getLOGGED_IN_LASTNAME());
                    values.put(SQLHandler.UserColumns.HEALTH_FACILITY_ID, app.getLOGGED_IN_USER_HF_ID());
                    values.put(SQLHandler.UserColumns.ID, app.getLOGGED_IN_USER_ID());
                    values.put(SQLHandler.UserColumns.USERNAME, app.getLOGGED_IN_USERNAME());
                    values.put(SQLHandler.UserColumns.PASSWORD, password);
                    databaseHandler.addUser(values);

                    Log.d(TAG, "initiating offline for " + username + " password = " + password);
                    app.initializeOffline(username, password);

                    Intent intent;
                    if (prefs.getBoolean("synchronization_needed", true)) {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                    } else {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        evaluateIfFirstLogin(app.getLOGGED_IN_USER_ID());
                    }
                    app.setUsername(username);

                    startActivity(intent);
                }
                //if login failed show error
                else {
                    handler.post(new Runnable() {
                        public void run() {
                            progressDialog.show();
                            progressDialog.dismiss();
                            toastMessage("Login failed.\nPlease check your details!");
                            loginButton.setEnabled(true);
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    public void run() {
                        progressDialog.show();
                        progressDialog.dismiss();
                        toastMessage("Login failed Login failed.\n"
                                + "Please check your details or your web connectivity");
                        loginButton.setEnabled(true);

                    }
                });
                e.printStackTrace();
            }
        }
    });
    thread.start();

}

From source file:com.company.millenium.iwannask.MainActivity.java

public void encodeImagetoString() {
    new AsyncTask<Void, Void, String>() {
        protected void onPreExecute() {

        };/*from   w w  w. j av a 2s .  co m*/

        @Override
        protected String doInBackground(Void... params) {
            BitmapFactory.Options options = null;
            options = new BitmapFactory.Options();
            options.inSampleSize = 3;
            Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
            byte[] byte_arr = stream.toByteArray();
            encodedString = Base64.encodeToString(byte_arr, 0);
            return "";

        }

        @Override
        protected void onPostExecute(String msg) {

            params.put("image", encodedString);
            // Trigger Image upload

            triggerImageUpload();
        }

    }.execute(null, null, null);
}