List of usage examples for android.util Base64 encodeToString
public static String encodeToString(byte[] input, int flags)
From source file:ca.uwaterloo.magic.goodhikes.ProfileActivity.java
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_CANCELED) return;/*from w w w . java 2 s . com*/ if (requestCode == FROM_GALLERY) if (resultCode == RESULT_OK) { Uri selectedImage = data.getData(); profile_image.setImageURI(selectedImage); try { /* uri -> bitmap -> encoded string * store string in sharedpreference */ image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage); ByteArrayOutputStream byte_out = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 90, byte_out); //image is the bitmap object image = Bitmap.createScaledBitmap(image, 640, 480, false); byte[] byte_arr = byte_out.toByteArray(); String encoded = Base64.encodeToString(byte_arr, Base64.DEFAULT); Log.d(LOG_TAG, "encoded string length: " + encoded.length()); String input = "uid="; input += URLEncoder.encode(user.getId(), "UTF-8"); input += "&image_str="; input += URLEncoder.encode(encoded, "UTF-8"); new SyncImage().execute(input); userManager.setImage(encoded); //Log.d(LOG_TAG, "set image str: " + userManager.getImage()); } catch (Exception e) { Log.d(LOG_TAG, e.getMessage()); } } }
From source file:mobisocial.musubi.nearby.scanner.GpsScannerTask.java
@Override protected List<NearbyItem> doInBackground(Void... params) { if (DBG)//from w ww. ja v a2 s .c o m Log.d(TAG, "Scanning for nearby gps..."); while (!mmLocationScanComplete) { synchronized (mmLocationResult) { if (!mmLocationScanComplete) { try { if (DBG) Log.d(TAG, "Waiting for location results..."); mmLocationResult.wait(); } catch (InterruptedException e) { } } } } if (DBG) Log.d(TAG, "Got location " + mmLocation); if (isCancelled()) { return null; } try { if (DBG) Log.d(TAG, "Querying gps server..."); Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/findgroup"); StringBuffer sb = new StringBuffer(); DefaultHttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(uri.toString()); httpPost.addHeader("Content-Type", "application/json"); JSONArray buckets = new JSONArray(); double lat = mmLocation.getLatitude(); double lng = mmLocation.getLongitude(); long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2); Log.i(TAG, "coords: " + Arrays.toString(coords)); //TODO: encrypt coords with mmPassword for (long c : coords) { MessageDigest md; try { byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes(); md = MessageDigest.getInstance("SHA-256"); ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length); b.putLong(c); b.put(obfuscate); String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT); buckets.put(buckets.length(), secret_bucket); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("your platform does not support sha256", e); } } Log.i(TAG, "buckets: " + buckets); httpPost.setEntity(new StringEntity(buckets.toString())); try { HttpResponse execute = client.execute(httpPost); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { if (isCancelled()) { return null; } sb.append(s); } } catch (Exception e) { e.printStackTrace(); } HashSet<Pair<TByteArrayList, TByteArrayList>> dupes = new HashSet<Pair<TByteArrayList, TByteArrayList>>(); String response = sb.toString(); JSONArray groupsJSON = new JSONArray(response); Log.d(TAG, "Got " + groupsJSON.length() + " groups"); for (int i = 0; i < groupsJSON.length(); i++) { try { String s_enc_data = groupsJSON.get(i).toString(); byte[] enc_data = Base64.decode(s_enc_data, Base64.DEFAULT); byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes()); byte[] data; Cipher cipher; AlgorithmParameterSpec iv_spec; SecretKeySpec sks; try { cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); } catch (Exception e) { throw new RuntimeException("AES not supported on this platform", e); } try { iv_spec = new IvParameterSpec(enc_data, 0, 16); sks = new SecretKeySpec(key, "AES"); cipher.init(Cipher.DECRYPT_MODE, sks, iv_spec); } catch (Exception e) { throw new RuntimeException("bad iv or key", e); } try { data = cipher.doFinal(enc_data, 16, enc_data.length - 16); } catch (Exception e) { throw new RuntimeException("body decryption failed", e); } JSONObject group = new JSONObject(new String(data)); String group_name = group.getString("group_name"); byte[] group_capability = Base64.decode(group.getString("group_capability"), Base64.DEFAULT); String sharer_name = group.getString("sharer_name"); byte[] sharer_hash = Base64.decode(group.getString("sharer_hash"), Base64.DEFAULT); byte[] thumbnail = null; if (group.has("thumbnail")) thumbnail = Base64.decode(group.getString("thumbnail"), Base64.DEFAULT); int member_count = group.getInt("member_count"); int sharer_type = group.getInt("sharer_type"); Pair<TByteArrayList, TByteArrayList> p = Pair.with(new TByteArrayList(sharer_hash), new TByteArrayList(group_capability)); if (dupes.contains(p)) continue; dupes.add(p); addNearbyItem(new NearbyFeed(mContext, group_name, group_capability, sharer_name, Authority.values()[sharer_type], sharer_hash, thumbnail, member_count)); } catch (Throwable e) { Log.e(TAG, "Failed to parse group " + i, e); } } } catch (Exception e) { if (DBG) Log.d(TAG, "Error searching nearby feeds", e); } return null; }
From source file:net.sourcewalker.garanbot.api.GaranboClient.java
private String getAuthHeader() { byte[] input = String.format("%s:%s", username, password).getBytes(); return "Basic " + Base64.encodeToString(input, Base64.NO_WRAP); }
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * {@code connect} is for forming the secure connection between server and * android, sending and receiving of the data. * /*from w w w . ja v a2 s. c om*/ * @param arg0 * data which is to be sent to server. * * @return data in string format, received from the server. */ public String connect(String... arg0) { int nrOfDataToSendToServer = arg0.length; nrOfDataToSendToServer = nrOfDataToSendToServer - 1; boolean valid = false; String dataFromServer = "unverified", serverPublicKeySigStr, serverDataSig; try { //Creating the server certificate Certificate serverCertificate = getServerCertificate(); KeyStore keyStore = getKeyStore(serverCertificate); TrustManagerFactory tmf = getTrustManager(keyStore); SSLContext sslContext = getSSLContext(tmf); HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection urlConnection = getURLConnection(sslContext, hostnameVerifier); // Converting the data into JSONObject JSONObject obj = new JSONObject(); for (int i = 0; i <= nrOfDataToSendToServer; i++) { obj.put("param" + i, arg0[i]); } // Converting the JSONObject into string String dataToSend = obj.toString(); KeyPairGenerator keyGen = getKeyPairGenerator(); KeyPair keyPair = keyGen.generateKeyPair(); //Public key for verifying the digital signature PublicKey clientPublicKeySig = keyPair.getPublic(); //Private key for signing the data PrivateKey clientPrivateKeySig = keyPair.getPrivate(); // Get signed data String sigData = getDataSig(clientPrivateKeySig, dataToSend); // Creating URL Format String urlData = URLEncoder.encode("clientPublicKeySig", "UTF-8") + "=" + URLEncoder .encode(Base64.encodeToString(clientPublicKeySig.getEncoded(), Base64.DEFAULT), "UTF-8"); urlData += "&" + URLEncoder.encode("clientData", "UTF-8") + "=" + URLEncoder.encode(dataToSend, "UTF-8"); urlData += "&" + URLEncoder.encode("clientDataSig", "UTF-8") + "=" + URLEncoder.encode(sigData, "UTF-8"); // Sending the data to the server OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(urlData); wr.flush(); wr.close(); // Receiving the data from server BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while ((line = reader.readLine()) != null) { // Append server response in string sb.append(line + "\n"); // sb.append(line); } String text = sb.toString(); reader.close(); // Extracting the data, public key and signature received from // server Vector<String> storeExtractedValues = new Vector<String>(); storeExtractedValues = extractDataFromJson(text, "data"); dataFromServer = storeExtractedValues.get(0); storeExtractedValues = extractDataFromJson(text, "serverPublicKeySig"); serverPublicKeySigStr = storeExtractedValues.get(0); storeExtractedValues = extractDataFromJson(text, "serverDataSig"); serverDataSig = storeExtractedValues.get(0); // Converting the Server Public key format to Java compatible from PublicKey serverPublicKeySig = getServerPublicKey(serverPublicKeySigStr); // Verify the received data valid = getDataValidity(serverPublicKeySig, dataFromServer, serverDataSig); // Disconnect the url connection urlConnection.disconnect(); if (dataFromServer.equalsIgnoreCase("unverified")) { CExceptionHandling.ExceptionState = ExceptionSet.SENT_DATA_UNVERIFIED; return "-1"; } else if (valid == false) { CExceptionHandling.ExceptionState = ExceptionSet.RECEIVED_DATA_UNVERIFIED; return "-1"; } else { return dataFromServer; } } catch (Exception e) { CExceptionHandling.ExceptionMsg = e.getMessage(); if (e.toString().equals("java.net.SocketException: Network unreachable")) { CExceptionHandling.ExceptionState = ExceptionSet.NO_DATA_CONNECTION; } else if (e.toString().equals( "java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 443) after 10000ms")) { CExceptionHandling.ExceptionState = ExceptionSet.CONNECTION_TIMEOUT; } else { CExceptionHandling.ExceptionState = ExceptionSet.OTHER_EXCEPTIONS; } return "-1"; } }
From source file:pro.jariz.reisplanner.api.NSTask.java
protected String doReq(String... uri) { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response;/*from ww w . java2 s.com*/ String responseString = null; try { HttpGet get = new HttpGet(uri[0]); get.setHeader("Authorization", "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP)); response = httpclient.execute(get); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); responseString = out.toString(); } else { //Closes the connection. response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (ClientProtocolException e) { NSTask.LastExceptionMessage = e.getMessage(); NSAPI.Error(e); return null; } catch (IOException e) { NSTask.LastExceptionMessage = e.getMessage(); NSAPI.Error(e); return null; } return responseString; }
From source file:com.charabia.SmsViewActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create the list fragment and add it as our sole content. if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { CursorLoaderListFragment listFragment = new CursorLoaderListFragment(); getSupportFragmentManager().beginTransaction().add(android.R.id.content, listFragment).commit(); }/*from ww w . j a va 2s . com*/ try { String texte = "bonjour"; byte[] data = tools.encrypt("15555215556", texte.getBytes()); Log.v("CHARABIA", "data=" + Base64.encodeToString(data, Base64.NO_WRAP)); Log.v("CHARABIA", "data=" + Tools.bytesToHex(data)); String result = new String(tools.decrypt("15555215556", data)); Log.v("CHARABIA", "result=" + result); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.oakesville.mythling.util.HttpHelper.java
private byte[] retrieveWithBasicAuth() throws IOException { Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); String credentials = Base64.encodeToString((user + ":" + password).getBytes(), Base64.DEFAULT); headers.put("Authorization", "Basic " + credentials); return retrieve(headers); }
From source file:com.amansoni.tripbook.activity.FacebookActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Add code to print out the key hash try {//from www . j a va 2 s .co m PackageInfo info = getPackageManager().getPackageInfo("com.amansoni.tripbook", PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)); } } catch (PackageManager.NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { } uiHelper = new UiLifecycleHelper(this, callback); uiHelper.onCreate(savedInstanceState); if (savedInstanceState != null) { String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY); pendingAction = PendingAction.valueOf(name); } setContentView(R.layout.facebook_activity); loginButton = (LoginButton) findViewById(R.id.login_button); loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() { @Override public void onUserInfoFetched(GraphUser user) { FacebookActivity.this.user = user; updateUI(); // It's possible that we were waiting for this.user to be populated in order to post a // status update. handlePendingAction(); } }); profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture); greeting = (TextView) findViewById(R.id.greeting); postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton); postStatusUpdateButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { onClickPostStatusUpdate(); } }); postPhotoButton = (Button) findViewById(R.id.postPhotoButton); postPhotoButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { onClickPostPhoto(); } }); pickFriendsButton = (Button) findViewById(R.id.pickFriendsButton); pickFriendsButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { onClickPickFriends(); } }); pickPlaceButton = (Button) findViewById(R.id.pickPlaceButton); pickPlaceButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { onClickPickPlace(); } }); controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container); final FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_container); if (fragment != null) { // If we're being re-created and have a fragment, we need to a) hide the main UI controls and // b) hook up its listeners again. controlsContainer.setVisibility(View.GONE); if (fragment instanceof FriendPickerFragment) { setFriendPickerListeners((FriendPickerFragment) fragment); } else if (fragment instanceof PlacePickerFragment) { setPlacePickerListeners((PlacePickerFragment) fragment); } } // Listen for changes in the back stack so we know if a fragment got popped off because the user // clicked the back button. fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { if (fm.getBackStackEntryCount() == 0) { // We need to re-show our UI. controlsContainer.setVisibility(View.VISIBLE); } } }); // Can we present the share dialog for regular links? canPresentShareDialog = FacebookDialog.canPresentShareDialog(this, FacebookDialog.ShareDialogFeature.SHARE_DIALOG); // Can we present the share dialog for photos? canPresentShareDialogWithPhotos = FacebookDialog.canPresentShareDialog(this, FacebookDialog.ShareDialogFeature.PHOTOS); }
From source file:com.restswitch.controlpanel.MainActivity.java
private void sendDevice(String devid, String host, String msg, String pwdHash) { try {//from w w w .ja v a 2s . co m final long utcStart = System.currentTimeMillis(); String b32UntilUtc = B32Coder.encodeDatetimeNow(8000); // valid for 8 sec String method = "PUT"; String uri = ("/pub/" + devid); String val = (method + uri + msg + b32UntilUtc); String b64Hash = null; try { Mac hmacSha256 = Mac.getInstance("HmacSHA256"); hmacSha256.init(new javax.crypto.spec.SecretKeySpec(pwdHash.getBytes("utf-8"), "HmacSHA256")); byte[] hash = hmacSha256.doFinal(val.getBytes("UTF-8")); b64Hash = Base64.encodeToString(hash, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP); } catch (Exception ex) { alertError("Invalid password, verify app settings."); return; } Properties headers = new Properties(); headers.setProperty("x-body", msg); headers.setProperty("x-auth1", b32UntilUtc); headers.setProperty("x-auth2", b64Hash); AjaxTask ajaxTask = new AjaxTask(); ajaxTask.putAjaxEventHandler(this); // // use to set a custom ca // boolean rc = ajaxTask.putRootCaCert(rootCa, true); // if(!rc) { // alertError("Failed to initialize network task."); // return; // } AjaxTask.Data data = new AjaxTask.Data(); data.param1 = devid; data.param2 = utcStart; ajaxTask.invoke("http", host, uri, method, headers, msg, data); } catch (Exception ex) { alertError(ex.getMessage()); } }
From source file:mobisocial.musubi.nearby.GpsBroadcastTask.java
@Override protected Void doInBackground(Void... params) { if (DBG)//from w w w. ja va 2 s. com Log.d(TAG, "Uploading group for nearby gps..."); while (!mmLocationScanComplete) { synchronized (mmLocationResult) { if (!mmLocationScanComplete) { try { if (DBG) Log.d(TAG, "Waiting for location results..."); mmLocationResult.wait(); } catch (InterruptedException e) { } } } } if (DBG) Log.d(TAG, "Got location " + mmLocation); if (isCancelled()) { return null; } try { SQLiteOpenHelper db = App.getDatabaseSource(mContext); FeedManager fm = new FeedManager(db); IdentitiesManager im = new IdentitiesManager(db); String group_name = UiUtil.getFeedNameFromMembersList(fm, mFeed); byte[] group_capability = mFeed.capability_; List<MIdentity> owned = im.getOwnedIdentities(); MIdentity sharer = null; for (MIdentity i : owned) { if (i.type_ != Authority.Local) { sharer = i; break; } } String sharer_name = UiUtil.safeNameForIdentity(sharer); byte[] sharer_hash = sharer.principalHash_; byte[] thumbnail = fm.getFeedThumbnailForId(mFeed.id_); if (thumbnail == null) thumbnail = im.getMusubiThumbnail(sharer) != null ? sharer.musubiThumbnail_ : im.getThumbnail(sharer); int member_count = fm.getFeedMemberCount(mFeed.id_); JSONObject group = new JSONObject(); group.put("group_name", group_name); group.put("group_capability", Base64.encodeToString(group_capability, Base64.DEFAULT)); group.put("sharer_name", sharer_name); group.put("sharer_type", sharer.type_.ordinal()); group.put("sharer_hash", Base64.encodeToString(sharer_hash, Base64.DEFAULT)); if (thumbnail != null) group.put("thumbnail", Base64.encodeToString(thumbnail, Base64.DEFAULT)); group.put("member_count", member_count); byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes()); byte[] data = group.toString().getBytes(); byte[] iv = new byte[16]; new SecureRandom().nextBytes(iv); byte[] partial_enc_data; Cipher cipher; AlgorithmParameterSpec iv_spec; SecretKeySpec sks; try { cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); } catch (Exception e) { throw new RuntimeException("AES not supported on this platform", e); } try { iv_spec = new IvParameterSpec(iv); sks = new SecretKeySpec(key, "AES"); cipher.init(Cipher.ENCRYPT_MODE, sks, iv_spec); } catch (Exception e) { throw new RuntimeException("bad iv or key", e); } try { partial_enc_data = cipher.doFinal(data); } catch (Exception e) { throw new RuntimeException("body encryption failed", e); } TByteArrayList bal = new TByteArrayList(iv.length + partial_enc_data.length); bal.add(iv); bal.add(partial_enc_data); byte[] enc_data = bal.toArray(); if (DBG) Log.d(TAG, "Posting to gps server..."); Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/sharegroup"); StringBuffer sb = new StringBuffer(); DefaultHttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(uri.toString()); httpPost.addHeader("Content-Type", "application/json"); JSONArray buckets = new JSONArray(); JSONObject descriptor = new JSONObject(); double lat = mmLocation.getLatitude(); double lng = mmLocation.getLongitude(); long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2); for (long c : coords) { MessageDigest md; try { byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes(); md = MessageDigest.getInstance("SHA-256"); ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length); b.putLong(c); b.put(obfuscate); String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT); buckets.put(buckets.length(), secret_bucket); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("your platform does not support sha256", e); } } descriptor.put("buckets", buckets); descriptor.put("data", Base64.encodeToString(enc_data, Base64.DEFAULT)); descriptor.put("expiration", new Date().getTime() + 1000 * 60 * 60); httpPost.setEntity(new StringEntity(descriptor.toString())); try { HttpResponse execute = client.execute(httpPost); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { if (isCancelled()) { return null; } sb.append(s); } if (sb.toString().equals("ok")) mSucceeded = true; else { System.err.println(sb); } } catch (Exception e) { e.printStackTrace(); } //TODO: report failures etc } catch (Exception e) { Log.e(TAG, "Failed to broadcast group", e); } return null; }