Example usage for android.util Base64 NO_WRAP

List of usage examples for android.util Base64 NO_WRAP

Introduction

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

Prototype

int NO_WRAP

To view the source code for android.util Base64 NO_WRAP.

Click Source Link

Document

Encoder flag bit to omit all line terminators (i.e., the output will be on one long line).

Usage

From source file:piuk.blockchain.android.MyWallet.java

public static String decrypt(String ciphertext, String password, final int PBKDF2Iterations) throws Exception {
    byte[] cipherdata = Base64.decode(ciphertext, Base64.NO_WRAP);

    //Sperate the IV and cipher data
    byte[] iv = copyOfRange(cipherdata, 0, AESBlockSize * 4);
    byte[] input = copyOfRange(cipherdata, AESBlockSize * 4, cipherdata.length);

    PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password.toCharArray()), iv,
            PBKDF2Iterations);/*from  w  ww  . ja v  a 2s. co m*/
    KeyParameter keyParam = (KeyParameter) generator.generateDerivedParameters(256);

    CipherParameters params = new ParametersWithIV(keyParam, iv);

    // setup AES cipher in CBC mode with PKCS7 padding
    BlockCipherPadding padding = new ISO10126d2Padding();
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
    cipher.reset();
    cipher.init(false, params);

    // create a temporary buffer to decode into (it'll include padding)
    byte[] buf = new byte[cipher.getOutputSize(input.length)];
    int len = cipher.processBytes(input, 0, input.length, buf, 0);
    len += cipher.doFinal(buf, len);

    // remove padding
    byte[] out = new byte[len];
    System.arraycopy(buf, 0, out, 0, len);

    // return string representation of decoded bytes
    return new String(out, "UTF-8");
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

private static String getBase64Hash(X509Certificate certificate, String digest)
        throws CertificateEncodingException {
    MessageDigest md;/*w ww .  ja va2 s  .  com*/
    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  a 2s.  co 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 {// w w  w.j a v  a2s . c  o m
        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)//from ww  w. j  a  v  a 2  s.co 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:piuk.blockchain.android.MyWallet.java

public static String encrypt(String text, String password, final int PBKDF2Iterations) throws Exception {

    if (password == null)
        throw new Exception("You must provide an ecryption password");

    // Use secure random to generate a 16 byte iv
    SecureRandom random = new SecureRandom();
    byte iv[] = new byte[AESBlockSize * 4];
    random.nextBytes(iv);/*from  w w  w.ja v  a2  s. c om*/

    byte[] textbytes = text.getBytes("UTF-8");

    PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password.toCharArray()), iv,
            PBKDF2Iterations);
    KeyParameter keyParam = (KeyParameter) generator.generateDerivedParameters(256);

    CipherParameters params = new ParametersWithIV(keyParam, iv);

    // setup AES cipher in CBC mode with PKCS7 padding
    BlockCipherPadding padding = new ISO10126d2Padding();
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
    cipher.reset();
    cipher.init(true, params);

    byte[] outBuf = cipherData(cipher, textbytes);

    // Append to IV to the output
    byte[] ivAppended = ArrayUtils.addAll(iv, outBuf);

    return new String(Base64.encode(ivAppended, Base64.NO_WRAP), "UTF-8");
}

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)//w  w  w.  j  ava  2 s . co  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:ca.psiphon.PsiphonTunnel.java

private String setupTrustedCertificates(Context context) throws Exception {

    // Copy the Android system CA store to a local, private cert bundle file.
    ///* w ww  .j av a 2s. c o m*/
    // This results in a file that can be passed to SSL_CTX_load_verify_locations
    // for use with OpenSSL modes in tunnel-core.
    // https://www.openssl.org/docs/manmaster/ssl/SSL_CTX_load_verify_locations.html
    //
    // TODO: to use the path mode of load_verify_locations would require emulating
    // the filename scheme used by c_rehash:
    // https://www.openssl.org/docs/manmaster/apps/c_rehash.html
    // http://stackoverflow.com/questions/19237167/the-new-subject-hash-openssl-algorithm-differs

    File directory = context.getDir("PsiphonCAStore", Context.MODE_PRIVATE);

    final String errorMessage = "copy AndroidCAStore failed";
    try {

        File file = new File(directory, "certs.dat");

        // Pave a fresh copy on every run, which ensures we're not using old certs.
        // Note: assumes KeyStore doesn't return revoked certs.
        //
        // TODO: this takes under 1 second, but should we avoid repaving every time?
        file.delete();

        PrintStream output = null;
        try {
            output = new PrintStream(new FileOutputStream(file));

            KeyStore keyStore;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                keyStore = KeyStore.getInstance("AndroidCAStore");
                keyStore.load(null, null);
            } else {
                keyStore = KeyStore.getInstance("BKS");
                FileInputStream inputStream = new FileInputStream("/etc/security/cacerts.bks");
                try {
                    keyStore.load(inputStream, "changeit".toCharArray());
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }

            Enumeration<String> aliases = keyStore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);

                output.println("-----BEGIN CERTIFICATE-----");
                String pemCert = new String(Base64.encode(cert.getEncoded(), Base64.NO_WRAP), "UTF-8");
                // OpenSSL appears to reject the default linebreaking done by Base64.encode,
                // so we manually linebreak every 64 characters
                for (int i = 0; i < pemCert.length(); i += 64) {
                    output.println(pemCert.substring(i, Math.min(i + 64, pemCert.length())));
                }
                output.println("-----END CERTIFICATE-----");
            }

            mHostService.onDiagnosticMessage("prepared PsiphonCAStore");

            return file.getAbsolutePath();

        } finally {
            if (output != null) {
                output.close();
            }
        }

    } catch (KeyStoreException e) {
        throw new Exception(errorMessage, e);
    } catch (NoSuchAlgorithmException e) {
        throw new Exception(errorMessage, e);
    } catch (CertificateException e) {
        throw new Exception(errorMessage, e);
    } catch (IOException e) {
        throw new Exception(errorMessage, e);
    }
}

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 w w  w  .  j  a v  a2s . c om*/
 *
 * <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.appybite.customer.AllowedHotels.java

private void loadHotelList() {

    aryHotelList.clear();//from  w  w w  .j  a va 2 s. co  m
    HotelInfo info = new HotelInfo();
    info.id = -1;
    info.hotel_name = "Welcome";
    info.hotel_desc = "Welcome";
    aryHotelList.add(info);

    updateHotelList();

    if (NetworkUtils.haveInternet(this)) {

        //. https://www.appyorder.com/pro_version/webservice_smart_app/Department/GetDepartments.php?hotel_id=6759
        // http://www.appyorder.com/pro_version/webservice_smart_app/new/getGeoHotels.php?lat=37&long=-122&rad=30000&t=1
        // https://www.appyorder.com/pro_version/webservice_smart_app/new/loginBrand.php?email_id=test@test.com&password=123
        RequestParams params = new RequestParams();
        params.add("email_id", PrefValue.getString(AllowedHotels.this, R.string.pref_customer_email_id));
        params.add("password",
                Base64.encodeToString(
                        PrefValue.getString(AllowedHotels.this, R.string.pref_customer_pwd).getBytes(),
                        Base64.NO_WRAP));
        /*Base64.encodeToString(edt_password.getText().toString().getBytes(), Base64.NO_WRAP));*/

        /*params.add("email_id", "demo@appybite.com");
        params.add("password", Base64.encodeToString("demo".getBytes(), Base64.NO_WRAP));*/

        DialogUtils.launchProgress(this, "Please wait while loading Data");
        CustomerHttpClient.get("new/loginBrand.php", params, new AsyncHttpResponseHandler() {
            @Override
            public void onFinish() {

                DialogUtils.exitProgress();

                super.onFinish();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                Toast.makeText(AllowedHotels.this, "Connection was lost (" + statusCode + ")",
                        Toast.LENGTH_LONG).show();
                super.onFailure(statusCode, headers, errorResponse, e);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                // Pull out the first event on the public timeline
                try {
                    String result = new String(response);
                    result.replace("\n", "");
                    result = result.substring(result.indexOf("{"), result.lastIndexOf("}") + 1);
                    Log.i("HTTP Response <<<", result);
                    JSONObject jsonObject = (JSONObject) new JSONObject(result);
                    String status = jsonObject.getString("status");
                    if (status.equalsIgnoreCase("true")) {
                        JSONObject jsonAllowed = jsonObject.getJSONObject("allowed hotel list");
                        String isExistAllowed = (String) jsonAllowed.getString("status");
                        if (isExistAllowed.equalsIgnoreCase("true")) {

                            JSONObject hotels = jsonAllowed.getJSONObject("hotels");

                            JSONArray hotelProArray = hotels.getJSONArray("pro");
                            for (int i = 0; i < hotelProArray.length(); i++) {

                                HotelInfo item = new HotelInfo();

                                JSONObject object = hotelProArray.getJSONObject(i);
                                item.id = 2;
                                item.hotel_id = object.getInt("id");
                                item.hotel_desc = object.getString("hotel_desc");
                                item.hotel_logo = object.getString("hotel_logo");
                                item.hotel_name = object.getString("hotel_name");
                                item.hotel_bg = object.getString("hotel_background");
                                item.license = object.getString("pro");

                                aryHotelList.add(item);
                            }

                            JSONArray hotelDemoArray = hotels.getJSONArray("demo");
                            for (int i = 0; i < hotelDemoArray.length(); i++) {

                                HotelInfo item = new HotelInfo();

                                JSONObject object = hotelDemoArray.getJSONObject(i);
                                item.id = 2;
                                item.hotel_id = object.getInt("id");
                                item.hotel_desc = object.getString("hotel_desc");
                                item.hotel_logo = object.getString("hotel_logo");
                                item.hotel_name = object.getString("hotel_name");
                                item.hotel_bg = object.getString("hotel_background");
                                item.license = object.getString("demo");

                                aryHotelList.add(item);
                            }
                        } else {
                            Toast.makeText(AllowedHotels.this, jsonAllowed.getString("message"),
                                    Toast.LENGTH_LONG).show();
                        }
                    }

                    PrefValue.setString(AllowedHotels.this, R.string.pref_hotel_logo, "welcome");
                    PrefValue.setString(AllowedHotels.this, R.string.pref_hotel_bg, "welcome");
                    PrefValue.setString(AllowedHotels.this, R.string.pref_hotel_first, "welcome");
                    PrefValue.setString(AllowedHotels.this, R.string.pref_hotel_name, "AppyBite World!");

                    if (DeviceUtil.isTabletByRes(AllowedHotels.this)) {
                        ImageLoader.getInstance().displayImage(
                                PrefValue.getString(AllowedHotels.this, R.string.pref_hotel_bg), ivHotelBg,
                                optionsForBg, animateFirstListener);
                        ImageLoader.getInstance().displayImage(
                                PrefValue.getString(AllowedHotels.this, R.string.pref_hotel_logo), ivHotelLogo,
                                null, animateFirstListener);
                        tvHotelName.setText(PrefValue.getString(AllowedHotels.this, R.string.pref_hotel_name));
                    } else {
                        if (m_Fragment != null
                                && m_Fragment.getClass().getName() == HotelHomeFragment.class.getName())
                            ((HotelHomeFragment) m_Fragment).loadHotelInfo();
                    }

                    updateHotelList();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(AllowedHotels.this, "Invalid Data", Toast.LENGTH_LONG).show();
                }
            }
        });

    } else {
        Toast.makeText(AllowedHotels.this, "No Internet Connection", Toast.LENGTH_LONG).show();
    }
}