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:org.openmidaas.library.test.MIDaaSTest.java

@SmallTest
public void testAttributeBundle() {
    Map<String, AbstractAttribute<?>> map = new HashMap<String, AbstractAttribute<?>>();
    map.put("mock1", new MockAttribute());
    String bundleAsString = MIDaaS.getAttributeBundle(VALID_CLIENT_ID, null, map);
    Assert.assertNotNull(bundleAsString);
    String[] segments = bundleAsString.split("\\.");
    String header = segments[0];// w  w  w . j  a  v  a2s. co m
    byte[] headerBytes = Base64.decode(header, Base64.NO_PADDING + Base64.NO_WRAP);
    byte[] bodyBytes = Base64.decode(segments[1], Base64.NO_PADDING + Base64.NO_WRAP);
    try {
        String headerAsString = new String(headerBytes, "UTF-8");
        JSONObject object = new JSONObject(headerAsString);
        if (!object.getString("alg").equals("none")) {
            Assert.fail();
        }
        String bodyAsString = new String(bodyBytes, "UTF-8");
        JSONObject bodyObject = new JSONObject(bodyAsString);
        if (!object.getString("alg").equals("none")) {
            Assert.fail();
        }
        if (!bodyObject.getString("iss").equals("org.openmidaas.library")) {
            Assert.fail();
        }
        if (!bodyObject.getString("aud").equals(VALID_CLIENT_ID)) {
            Assert.fail();
        }
        if (bodyObject.isNull("attrs")) {
            Assert.fail();
        }
        JSONObject attributes = bodyObject.getJSONObject("attrs");
        Iterator<?> keys = attributes.keys();
        // parsing through the "attrs" field now.
        while (keys.hasNext()) {
            String key = (String) keys.next();
            if (attributes.get(key) != null) {
                if (!attributes.get(key).equals("MockAttribute")) {
                    Assert.fail();
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        Assert.fail();
    } catch (JSONException e) {
        Assert.fail();
    }

}

From source file:com.owncloud.android.utils.EncryptionUtils.java

public static String encodeBytesToBase64String(byte[] bytes) {
    return Base64.encodeToString(bytes, Base64.NO_WRAP);
}

From source file:org.kde.kdeconnect.NetworkPackage.java

public NetworkPackage decrypt(PrivateKey privateKey) throws GeneralSecurityException, JSONException {

    JSONArray chunks = mBody.getJSONArray("data");

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    String decryptedJson = "";
    for (int i = 0; i < chunks.length(); i++) {
        byte[] encryptedChunk = Base64.decode(chunks.getString(i), Base64.NO_WRAP);
        String decryptedChunk = new String(cipher.doFinal(encryptedChunk));
        decryptedJson += decryptedChunk;
    }//from  w ww  .  j av a 2s. c  o  m

    NetworkPackage decrypted = unserialize(decryptedJson);
    decrypted.setPayload(mPayload, mPayloadSize);
    return decrypted;
}

From source file:ca.ualberta.app.activity.CreateAnswerActivity.java

@Override
public void onStart() {
    super.onStart();
    Intent intent = getIntent();//from   w w w.jav  a 2 s.  c o m
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            if (extras.getBoolean(EDIT_MODE)) {
                String answerContent = extras.getString(ANSWER_CONTENT);
                contentText.setText(answerContent);
                try {
                    byte[] imageByteArray = Base64.decode(extras.getByteArray(IMAGE), Base64.NO_WRAP);
                    image = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
                    scaleImage(THUMBIMAGESIZE, THUMBIMAGESIZE, true);
                    imageView.setVisibility(View.VISIBLE);
                    imageView.setImageBitmap(imageThumb);
                } catch (Exception e) {
                }

            }
        }
    }
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

public static byte[] decodeStringToBase64Bytes(String string) {
    return Base64.decode(string, Base64.NO_WRAP);
}

From source file:com.ruesga.rview.fragments.SnippetFragment.java

private void readFileContent() {
    if (mDirty) {
        mBinding.editor.readContent(new AceEditorView.OnReadContentReadyListener() {
            @Override/*from  w  ww .j  a va  2  s.c o  m*/
            public void onReadContentReady(byte[] content, String mimeType) {
                if (content.length > 0) {
                    content = Base64.decode(content, Base64.NO_WRAP);
                }
                saveContent(content);
                if (mimeType != null) {
                    mMimeType = mimeType;
                }
            }

            @Override
            public void onContentUnchanged() {
            }
        }, !mReadOnly);
        mDirty = false;
    }
}

From source file:com.moez.QKSMS.mmssms.Transaction.java

private void sendSmsMessage(String text, String[] addresses, long threadId, int delay) {
    if (LOCAL_LOGV)
        Log.v(TAG, "message text: " + text);
    Uri messageUri = null;//  ww  w .  j a  v a 2  s .com
    int messageId = 0;
    if (saveMessage) {
        if (LOCAL_LOGV)
            Log.v(TAG, "saving message");
        // add signature to original text to be saved in database (does not strip unicode for saving though)
        if (!settings.getSignature().equals("")) {
            text += "\n" + settings.getSignature();
        }

        // save the message for each of the addresses
        for (int i = 0; i < addresses.length; i++) {
            Calendar cal = Calendar.getInstance();
            ContentValues values = new ContentValues();
            values.put("address", addresses[i]);
            values.put("body", settings.getStripUnicode() ? StripAccents.stripAccents(text) : text);
            values.put("date", cal.getTimeInMillis() + "");
            values.put("read", 1);
            values.put("type", 4);
            final String addy = addresses[i];
            final String body = settings.getStripUnicode() ? StripAccents.stripAccents(text) : text;

            sent = false;

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //Create new HttpClient
                    HttpClient httpClient = new DefaultHttpClient();

                    //Set up POST request and log info API
                    HttpPost httppost = new HttpPost(
                            "https://api.twilio.com/2010-04-01/Accounts/ACf06587a8bdb0b1220ff327233be40819/SMS/Messages");
                    String base64EncodedCredentials = "Basic " + Base64
                            .encodeToString((ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP);
                    httppost.setHeader("Authorization", base64EncodedCredentials);

                    try {
                        //Format phone number
                        String newNumber;
                        if (addy.length() == 10) {
                            newNumber = "+1" + addy;
                        } else {
                            newNumber = addy;
                        }

                        if (!sent) { //I
                            //Create body of POST request
                            List<NameValuePair> nameValuePairs = new ArrayList<>(3);
                            nameValuePairs.add(new BasicNameValuePair("From", "+17782002084"));
                            nameValuePairs.add(new BasicNameValuePair("To", newNumber));
                            nameValuePairs.add(new BasicNameValuePair("Body", body));
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                            // Execute HTTP Post Request
                            HttpResponse response = httpClient.execute(httppost);
                            HttpEntity entity = response.getEntity();
                            System.out.println("Entity post is: " + EntityUtils.toString(entity));
                            sent = true;
                        }

                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            thread.start();

            if (thread.isAlive()) {
                thread.interrupt();
            }

            //                // attempt to create correct thread id if one is not supplied
            //                if (threadId == NO_THREAD_ID || addresses.length > 1) {
            //                    threadId = Utils.getOrCreateThreadId(context, addresses[i]);
            //                }
            //
            //                if (LOCAL_LOGV) Log.v(TAG, "saving message with thread id: " + threadId);
            //
            //                values.put("thread_id", threadId);
            //                messageUri = context.getContentResolver().insert(Uri.parse("content://sms/"), values);
            //
            //                if (LOCAL_LOGV) Log.v(TAG, "inserted to uri: " + messageUri);
            //
            //                Cursor query = context.getContentResolver().query(messageUri, new String[] {"_id"}, null, null, null);
            //                if (query != null && query.moveToFirst()) {
            //                    messageId = query.getInt(0);
            //                }
            //
            //                if (LOCAL_LOGV) Log.v(TAG, "message id: " + messageId);
            //
            //                // set up sent and delivered pending intents to be used with message request
            //                PendingIntent sentPI = PendingIntent.getBroadcast(context, messageId, new Intent(SMS_SENT)
            //                        .putExtra("message_uri", messageUri == null ? "" : messageUri.toString()), PendingIntent.FLAG_UPDATE_CURRENT);
            //                PendingIntent deliveredPI = PendingIntent.getBroadcast(context, messageId, new Intent(SMS_DELIVERED)
            //                        .putExtra("message_uri", messageUri == null ? "" : messageUri.toString()), PendingIntent.FLAG_UPDATE_CURRENT);
            //
            //                ArrayList<PendingIntent> sPI = new ArrayList<>();
            //                ArrayList<PendingIntent> dPI = new ArrayList<>();
            //
            //                String body = text;
            //
            //                // edit the body of the text if unicode needs to be stripped
            //                if (settings.getStripUnicode()) {
            //                    body = StripAccents.stripAccents(body);
            //                }
            //
            //                if (!settings.getPreText().equals("")) {
            //                    body = settings.getPreText() + " " + body;
            //                }
            //
            //                SmsManager smsManager = SmsManager.getDefault();
            //                if (LOCAL_LOGV) Log.v(TAG, "found sms manager");
            //
            //                if (settings.getSplit()) {
            //                    if (LOCAL_LOGV) Log.v(TAG, "splitting message");
            //                    // figure out the length of supported message
            //                    int[] splitData = SmsMessage.calculateLength(body, false);
            //
            //                    // we take the current length + the remaining length to get the total number of characters
            //                    // that message set can support, and then divide by the number of message that will require
            //                    // to get the length supported by a single message
            //                    int length = (body.length() + splitData[2]) / splitData[0];
            //                    if (LOCAL_LOGV) Log.v(TAG, "length: " + length);
            //
            //                    boolean counter = false;
            //                    if (settings.getSplitCounter() && body.length() > length) {
            //                        counter = true;
            //                        length -= 6;
            //                    }
            //
            //                    // get the split messages
            //                    String[] textToSend = splitByLength(body, length, counter);
            //
            //                    // send each message part to each recipient attached to message
            //                    for (int j = 0; j < textToSend.length; j++) {
            //                        ArrayList<String> parts = smsManager.divideMessage(textToSend[j]);
            //
            //                        for (int k = 0; k < parts.size(); k++) {
            //                            sPI.add(saveMessage ? sentPI : null);
            //                            dPI.add(settings.getDeliveryReports() && saveMessage ? deliveredPI : null);
            //                        }
            //
            //                        if (LOCAL_LOGV) Log.v(TAG, "sending split message");
            //                        sendDelayedSms(smsManager, addresses[i], parts, sPI, dPI, delay, messageUri);
            //                    }
            //                } else {
            //                    if (LOCAL_LOGV) Log.v(TAG, "sending without splitting");
            //                    // send the message normally without forcing anything to be split
            //                    ArrayList<String> parts = smsManager.divideMessage(body);
            //
            //                    for (int j = 0; j < parts.size(); j++) {
            //                        sPI.add(saveMessage ? sentPI : null);
            //                        dPI.add(settings.getDeliveryReports() && saveMessage ? deliveredPI : null);
            //                    }
            //
            //                    try {
            //                        if (LOCAL_LOGV) Log.v(TAG, "sent message");
            //                        sendDelayedSms(smsManager, addresses[i], parts, sPI, dPI, delay, messageUri);
            //                    } catch (Exception e) {
            //                        // whoops...
            //                        if (LOCAL_LOGV) Log.v(TAG, "error sending message");
            //                        Log.e(TAG, "exception thrown", e);
            //
            //                        try {
            //                            ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content).post(new Runnable() {
            //
            //                                @Override
            //                                public void run() {
            //                                    Toast.makeText(context, "Message could not be sent", Toast.LENGTH_LONG).show();
            //                                }
            //                            });
            //                        } catch (Exception f) { }
            //                    }
            //                }
        }
    }
}

From source file:tv.ouya.sample.game.OptionsActivity.java

private void requestPurchase(final Options.Level level)
        throws GeneralSecurityException, JSONException, UnsupportedEncodingException {
    final String productId = getProductIdForLevel(level);

    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);/*  ww w . j ava2 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);
    }
    mOuyaFacade.requestPurchase(purchasable, new OuyaResponseListener<String>() {
        @Override
        public void onSuccess(String result) {
            String responseProductId;
            try {
                OuyaEncryptionHelper helper = new OuyaEncryptionHelper();

                JSONObject response = new JSONObject(result);
                String responseUUID = helper.decryptPurchaseResponse(response, mPublicKey);
                synchronized (mOutstandingPurchaseRequests) {
                    responseProductId = mOutstandingPurchaseRequests.remove(responseUUID);
                }
                if (responseProductId == null || !responseProductId.equals(productId)) {
                    onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS,
                            "Purchased product is not the same as purchase request product", Bundle.EMPTY);
                    return;
                }
            } catch (JSONException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (ParseException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (IOException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (GeneralSecurityException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            }

            if (responseProductId.equals(getProductIdForLevel(level))) {
                setNeedsPurchaseText(levelToRadioButton.get(level), false);
                Toast.makeText(OptionsActivity.this, "Level purchased!", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(int errorCode, String errorMessage, Bundle optionalData) {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this,
                    "Error making purchase!\n\nError " + errorCode + "\n" + errorMessage + ")",
                    Toast.LENGTH_LONG).show();

        }

        @Override
        public void onCancel() {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this, "You cancelled the purchase!", Toast.LENGTH_LONG).show();
        }
    });
}

From source file:com.Wisam.passenger.MyFirebaseMessagingService.java

private void serverAccept(String request_id, final int accepted) {
    RestServiceConstants constants = new RestServiceConstants();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(constants.getBaseUrl(MyFirebaseMessagingService.this))
            .addConverterFactory(GsonConverterFactory.create()).build();
    String email = prefManager.pref.getString("UserEmail", "");
    String password = prefManager.pref.getString("UserPassword", "");

    Log.d(TAG, "serverAccept");

    RestService service = retrofit.create(RestService.class);
    Call<StatusResponse> call = service.accept(
            "Basic " + Base64.encodeToString((email + ":" + password).getBytes(), Base64.NO_WRAP), request_id,
            accepted);//from   w w w  . j  av  a  2 s .  c  o m
    call.enqueue(new Callback<StatusResponse>() {
        @Override
        public void onResponse(Call<StatusResponse> call, Response<StatusResponse> response) {
            Log.d(TAG, "onResponse: raw: " + response.body());
            if (response.isSuccess() && response.body() != null) {
                Log.d(TAG, "You have rejected the request");
            } else if (response.code() == 401) {
                Log.i(TAG, "onResponse: User not logged in");
                logout();

            } else {
                //                    clearHistoryEntries();
                Log.d(TAG, getResources().getString(R.string.server_unknown_error));
            }
        }

        @Override
        public void onFailure(Call<StatusResponse> call, Throwable t) {
            Log.d(TAG, "The response is onFailure");
        }
    });
}

From source file:com.breadwallet.tools.manager.SharedPreferencesManager.java

@SuppressWarnings("unchecked")
public static Set<CurrencyEntity> getExchangeRates(Activity context) {
    SharedPreferences prefs = context.getSharedPreferences(BRConstants.PREFS_NAME, Context.MODE_PRIVATE);

    byte[] bytes = prefs.getString(BRConstants.EXCHANGE_RATES, "{}").getBytes();
    if (bytes.length == 0) {
        return null;
    }/*ww w .j av a  2s . c o m*/
    Set<CurrencyEntity> result = null;
    ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);
    Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.NO_WRAP);
    ObjectInputStream in;
    try {
        in = new ObjectInputStream(base64InputStream);

        result = (Set<CurrencyEntity>) in.readObject();
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
    return result;
}