List of usage examples for android.util Base64 encodeToString
public static String encodeToString(byte[] input, int flags)
From source file:azad.hallaji.farzad.com.masirezendegi.PageVirayesh.java
private String encodeImage(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); String encImage = Base64.encodeToString(b, Base64.DEFAULT); return encImage; }
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;/*from w w w. j a v a 2 s .c o m*/ 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:com.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java
/** * Signs the data using the key pair stored in the Android Key Store. This signature can be * used with the data later to verify it was signed by this application. * @return A string encoding of the data signature generated *//*w ww . j av a 2 s.c o m*/ public String signData(String inputStr) throws KeyStoreException, UnrecoverableEntryException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException, CertificateException { byte[] data = inputStr.getBytes(); // BEGIN_INCLUDE(sign_load_keystore) KeyStore ks = KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE); // Weird artifact of Java API. If you don't have an InputStream to load, you still need // to call "load", or it'll crash. ks.load(null); // Load the key pair from the Android Key Store KeyStore.Entry entry = ks.getEntry(mAlias, null); /* If the entry is null, keys were never stored under this alias. * Debug steps in this situation would be: * -Check the list of aliases by iterating over Keystore.aliases(), be sure the alias * exists. * -If that's empty, verify they were both stored and pulled from the same keystore * "AndroidKeyStore" */ if (entry == null) { Log.w(TAG, "No key found under alias: " + mAlias); Log.w(TAG, "Exiting signData()..."); return null; } /* If entry is not a KeyStore.PrivateKeyEntry, it might have gotten stored in a previous * iteration of your application that was using some other mechanism, or been overwritten * by something else using the same keystore with the same alias. * You can determine the type using entry.getClass() and debug from there. */ if (!(entry instanceof KeyStore.PrivateKeyEntry)) { Log.w(TAG, "Not an instance of a PrivateKeyEntry"); Log.w(TAG, "Exiting signData()..."); return null; } // END_INCLUDE(sign_data) // BEGIN_INCLUDE(sign_create_signature) // This class doesn't actually represent the signature, // just the engine for creating/verifying signatures, using // the specified algorithm. Signature s = Signature.getInstance(SecurityConstants.SIGNATURE_SHA256withRSA); // Initialize Signature using specified private key s.initSign(((KeyStore.PrivateKeyEntry) entry).getPrivateKey()); // Sign the data, store the result as a Base64 encoded String. s.update(data); byte[] signature = s.sign(); String result = Base64.encodeToString(signature, Base64.DEFAULT); // END_INCLUDE(sign_data) return result; }
From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java
@Override public void tweets(final StatusUpdate latestStatus, @NonNull final ResponseCallback callback) { Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(mConsumerKey) .setOAuthConsumerSecret(mConsumerSecret).build(); final Twitter instance = new TwitterFactory(configuration).getInstance(); if (mAccessToken != null) { instance.setOAuthAccessToken(mAccessToken); }//from w w w . j a v a2 s .c o m doValidate(mAccessToken, instance).continueWithTask(new Continuation<User, Task<AccessToken>>() { @Override public Task<AccessToken> then(Task<User> task) throws Exception { if (task.isFaulted()) { final Task<AccessToken>.TaskCompletionSource source = Task.<AccessToken>create(); SharedPreferences preferences = getActivity().getSharedPreferences("twitter", Activity.MODE_PRIVATE); preferences.edit().clear().apply(); mAccessToken = null; instance.setOAuthAccessToken(null); doGetAuthenticationURL(instance).onSuccessTask(new Continuation<RequestToken, Task<Bundle>>() { @Override public Task<Bundle> then(Task<RequestToken> task) throws Exception { return doDialogAuthentication(task.getResult()); } }).onSuccessTask(new Continuation<Bundle, Task<AccessToken>>() { @Override public Task<AccessToken> then(Task<Bundle> task) throws Exception { return doGetAccessToken(instance, task.getResult()); } }).continueWith(new Continuation<AccessToken, AccessToken>() { @Override public AccessToken then(Task<AccessToken> task) throws Exception { if (task.isFaulted()) { Log.d(BuildConfig.DEBUG_TAG, "Failed", task.getError()); // Toast.makeText(getActivity(), task.getError().getMessage(), Toast.LENGTH_LONG).show(); // callback.onCancelled(task.getError()); source.trySetError(task.getError()); } else if (task.isCompleted()) { AccessToken accessToken = task.getResult(); String serialized = Base64.encodeToString(SerializationUtils.serialize(accessToken), Base64.DEFAULT); SharedPreferences preferences = getActivity().getSharedPreferences("twitter", Activity.MODE_PRIVATE); preferences.edit().putString("access_token_str", serialized).apply(); instance.setOAuthAccessToken(accessToken); mAccessToken = accessToken; source.trySetResult(mAccessToken); return accessToken; } return null; } }); return source.getTask(); } else { return Task.forResult(mAccessToken); } // } // }).onSuccessTask(new Continuation<AccessToken, Task<Map<String, RateLimitStatus>>>() { // @Override // public Task<Map<String, RateLimitStatus>> then(Task<AccessToken> task) throws Exception { // return doCheckStatus(instance); } }).onSuccessTask(new Continuation<AccessToken, Task<Status>>() { @Override public Task<Status> then(Task<AccessToken> task) throws Exception { // Map<String, RateLimitStatus> result = task.getResult(); return doTweet(instance, latestStatus); } }).continueWith(new Continuation<Status, Object>() { @Override public Object then(Task<Status> task) throws Exception { if (task.isFaulted()) { Log.d(BuildConfig.DEBUG_TAG, "Failed", task.getError()); String message = task.getError().getMessage(); if (!TextUtils.isEmpty(message)) { // Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } callback.onCancelled(task.getError()); } else if (task.isCompleted()) { callback.onCompleted(task.getResult()); } return null; } }); }
From source file:azad.hallaji.farzad.com.masirezendegi.PageVirayesh.java
private String encodeImage(String path) { File imagefile = new File(path); FileInputStream fis = null;//from ww w. j a va 2 s .c o m try { fis = new FileInputStream(imagefile); } catch (FileNotFoundException e) { e.printStackTrace(); } Bitmap bm = BitmapFactory.decodeStream(fis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); String encImage = Base64.encodeToString(b, Base64.DEFAULT); //Base64.de return encImage; }
From source file:com.microsoft.windowsazure.messaging.Connection.java
/** * Generates an AuthToken// w ww.j a va2s.co m * @param url The target URL * @return An AuthToken * @throws java.security.InvalidKeyException */ private String generateAuthToken(String url) throws InvalidKeyException { String keyName = mConnectionData.get(SHARED_ACCESS_KEY_NAME); if (isNullOrWhiteSpace(keyName)) { throw new AssertionError("SharedAccessKeyName"); } String key = mConnectionData.get(SHARED_ACCESS_KEY); if (isNullOrWhiteSpace(key)) { throw new AssertionError("SharedAccessKey"); } try { url = URLEncoder.encode(url, UTF8_ENCODING).toLowerCase(Locale.ENGLISH); } catch (UnsupportedEncodingException e) { // this shouldn't happen because of the fixed encoding } // Set expiration in seconds Calendar expireDate = Calendar.getInstance(TimeZone.getTimeZone(UTC_TIME_ZONE)); expireDate.add(Calendar.MINUTE, EXPIRE_MINUTES); long expires = expireDate.getTimeInMillis() / 1000; String toSign = url + '\n' + expires; // sign byte[] bytesToSign = toSign.getBytes(); Mac mac = null; try { mac = Mac.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException e) { // This shouldn't happen because of the fixed algorithm } SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm()); mac.init(secret); byte[] signedHash = mac.doFinal(bytesToSign); String base64Signature = Base64.encodeToString(signedHash, Base64.DEFAULT); base64Signature = base64Signature.trim(); try { base64Signature = URLEncoder.encode(base64Signature, UTF8_ENCODING); } catch (UnsupportedEncodingException e) { // this shouldn't happen because of the fixed encoding } // construct authorization string String token = "SharedAccessSignature sr=" + url + "&sig=" + base64Signature + "&se=" + expires + "&skn=" + keyName; return token; }
From source file:com.example.httpjson.AppEngineClient.java
public String getTokenFromServer() { String s = null;/*from w w w.ja va2s .c o m*/ try { URL uri = new URL("https://rtonames.sprintlabs.io/token"); Map<String, List<String>> headers = new HashMap<String, List<String>>(); String key = "Authorization"; String authStr = "6eece178-9fcf-45b7-ab50-08b8066daabe:e494a4e72b6f7c7672b74d311cbabf2672be8c24c9496554077936097195a5ac69b6acd11eb09a1ae07a40d2e7f0348d"; String encoding = Base64.encodeToString(authStr.getBytes(), Base64.DEFAULT); encoding = encoding.replace("\n", "").replace("\r", ""); System.out.println(encoding); List<String> value = Arrays.asList("Basic " + encoding); headers.put(key, value); AppEngineClient aec1 = new AppEngineClient(); Request request = aec1.new GET(uri, headers); AsyncTask<Request, Void, Response> obj = new asyncclass().execute(request); Response response = obj.get(); obj.cancel(true); obj = null; String body = null; try { body = new String(response.body, "UTF-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JSONObject tokenjson = AppEngineClient.getJSONObject(body); if (tokenjson.has("token")) { try { s = tokenjson.getString("token"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return s; }
From source file:jog.my.memory.gcm.ServerUtilities.java
/** * Convert images to the string representation * @param pics - pictures to send//from w ww. j a va 2s . c o m * @return arraylist of string representation of pictures */ public static ArrayList<String> convertPhotosToStringRepresentation(ArrayList<Picture> pics) { ArrayList<String> listPhotos = new ArrayList<>(); for (int i = 0; i < pics.size(); i++) { // String stringEncodedImage = // Base64.encodeToString(pics.get(i).getmImageAsByteArray(), Base64.DEFAULT); // listPhotos.add(stringEncodedImage); Bitmap bitmap = pics.get(i).getmImage(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); byte[] bitmapByte = outputStream.toByteArray(); listPhotos.add(Base64.encodeToString(bitmapByte, Base64.DEFAULT)); // try { // listPhotos.add(new String(bitmapByte)); // } // catch(Exception e){ // Log.d(TAG,"The encoding didn't work"); // } } return listPhotos; }
From source file:com.aknowledge.v1.automation.RemoteActivity.java
private void getDevices() { Log.d("RemoteActivity", "Get Devices URL = " + hostname + "/api/devices"); JsonArrayRequest req = new JsonArrayRequest(hostname + "/api/devices", new Response.Listener<JSONArray>() { @Override/*from w ww . j av a2 s . com*/ public void onResponse(JSONArray response) { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } Log.d("RemoteActivity", "Get Devices " + response.toString()); parseMyDevices(response.toString()); if (handler != null) { handler.removeCallbacksAndMessages(null); } handler = new Handler(); Runnable scheduledUpdate = new Runnable() { @Override public void run() { getDevices(); } }; handler.postDelayed(scheduledUpdate, refreshRate); // pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("RemoteActivity", "Error: " + error.getMessage()); if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } showServerAlert(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); String authString = user + ":" + pass; String encodedPass = null; try { encodedPass = Base64.encodeToString(authString.getBytes(), Base64.DEFAULT); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("Remote Activity", pass + " " + encodedPass); headers.put("Content-Type", "application/json"); headers.put("Authorization", "Basic " + encodedPass); return headers; } }; req.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); PyHomeController.getInstance().addToRequestQueue(req, statusTag); }
From source file:br.com.vpsa.oauth2android.token.MacTokenTypeDefinition.java
private static String calculateMAC(String key, String normalizedString, String algorithm) { String macString = ""; try {//from w ww . ja v a 2s . c o m System.out.println("algorithm=" + algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key.getBytes(), algorithm)); macString = Base64.encodeToString(mac.doFinal(normalizedString.getBytes()), Base64.DEFAULT); } catch (InvalidKeyException ex) { Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE, null, ex); } return macString; }