List of usage examples for android.util Base64 encodeToString
public static String encodeToString(byte[] input, int flags)
From source file:org.quantumbadger.redreader.reddit.api.RedditOAuth.java
public static FetchAccessTokenResult fetchAccessTokenSynchronous(final Context context, final RefreshToken refreshToken) { final String uri = ACCESS_TOKEN_URL; StatusLine responseStatus = null;//from www .ja va2 s . c o m try { final HttpClient httpClient = CacheManager.createHttpClient(context); final HttpPost request = new HttpPost(uri); final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token")); nameValuePairs.add(new BasicNameValuePair("refresh_token", refreshToken.token)); request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); request.addHeader("Authorization", "Basic " + Base64.encodeToString((CLIENT_ID + ":").getBytes(), Base64.URL_SAFE | Base64.NO_WRAP)); final HttpResponse response = httpClient.execute(request); responseStatus = response.getStatusLine(); if (responseStatus.getStatusCode() != 200) { return new FetchAccessTokenResult(FetchAccessTokenResultStatus.UNKNOWN_ERROR, new RRError(context.getString(R.string.error_unknown_title), context.getString(R.string.message_cannotlogin), null, responseStatus, request.getURI().toString())); } final JsonValue jsonValue = new JsonValue(response.getEntity().getContent()); jsonValue.buildInThisThread(); final JsonBufferedObject responseObject = jsonValue.asObject(); final String accessTokenString = responseObject.getString("access_token"); if (accessTokenString == null) { throw new RuntimeException("Null access token: " + responseObject.getString("error")); } final AccessToken accessToken = new AccessToken(accessTokenString); return new FetchAccessTokenResult(accessToken); } catch (IOException e) { return new FetchAccessTokenResult(FetchAccessTokenResultStatus.CONNECTION_ERROR, new RRError(context.getString(R.string.error_connection_title), context.getString(R.string.error_connection_message), e, responseStatus, uri)); } catch (Throwable t) { return new FetchAccessTokenResult(FetchAccessTokenResultStatus.UNKNOWN_ERROR, new RRError(context.getString(R.string.error_unknown_title), context.getString(R.string.error_unknown_message), t, responseStatus, uri)); } }
From source file:com.hkm.oc.wv.supportwebview.webviewSupports.java
protected void SavePNG(final int requestCode, final Uri filepath_uri) { final AsyncTask<Integer, Void, Boolean> task = new AsyncTask<Integer, Void, Boolean>() { private String error = ""; // private String imageEncoded = ""; @Override/*from www . java 2 s .com*/ protected Boolean doInBackground(Integer... k) { boolean result = false; try { Bitmap immagex = null; if (requestCode == WLR_CLIENT_SIGN) current_job_task.saveSignWLRClient(filepath_uri); if (requestCode == WLR_TEAM_SIGN) current_job_task.saveSignWLRTeam(filepath_uri); if (requestCode == WCS_CLIENT_SIGN) current_job_task.saveSignWCSClient(filepath_uri); // immagex = BitmapFactory.decodeStream(mFragmentActivity.getContentResolver().openInputStream(filepath_uri)); immagex = Tool.LoadScaledBitmap(mFragmentActivity.getContentResolver(), filepath_uri, 100000); if (immagex == null) throw new FileNotFoundException(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); //http://stackoverflow.com/questions/22031636/convert-android-base64-bitmap-and-display-on-html-base64-image final String imageEncoded = Base64.encodeToString(b, Base64.NO_WRAP); // final int strFileName = k[0]; // mWebView.loadUrl("javascript:PControl.checkComplete()"); /* final String m = new String(imageEncoded); final StringBuffer strBuilder = new StringBuffer(); final int bufferchars = 200; final int t = (int) Math.ceil(m.length() / bufferchars); for (int i = 0; i < t; i++) { final StringBuilder cc = new StringBuilder(); int next = (i + 1) * bufferchars; int dest = next > m.length() ? m.length() : next; final CharSequence g = m.subSequence(i * bufferchars, dest); cc.append(g); strBuilder.append(g); mWebView.loadUrl("javascript:PControl.fillPNG('" + cc.toString() + "');"); } String TAG = "loading image tag"; Log.d(TAG, strBuilder.toString());*/ result = true; } catch (FileNotFoundException e) { result = false; } catch (Exception e) { result = false; } return result; } @Override protected void onPostExecute(Boolean saved) { runOnUiThread(new Runnable() { @Override public void run() { progressBar_dismiss("signature saved and confirmed.", new DsingleCB() { @Override public void oncontified(DialogFragment dialog) { if (requestCode == WLR_CLIENT_SIGN) mWebView.loadUrl( "javascript:PControl.fillEndF(1,'" + filepath_uri.toString() + "');"); if (requestCode == WLR_TEAM_SIGN) mWebView.loadUrl( "javascript:PControl.fillEndF(2,'" + filepath_uri.toString() + "');"); if (requestCode == WCS_CLIENT_SIGN) mWebView.loadUrl( "javascript:PControl.fillEndF(3,'" + filepath_uri.toString() + "');"); } }); } }); } }; task.execute(requestCode); }
From source file:com.mpower.daktar.android.utilities.WebUtils.java
public static String getSHA512(final String input) { String retval = ""; try {/*www .ja v a 2 s . c o m*/ final MessageDigest m = MessageDigest.getInstance("SHA-512"); final byte[] out = m.digest(input.getBytes()); retval = Base64.encodeToString(out, Base64.NO_WRAP); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); } return retval; }
From source file:org.mobisocial.corral.CorralDownloadClient.java
private static String hashToString(long hash) { try {/* w w w . j a v a 2 s .c o m*/ ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); dos.writeLong(hash); dos.writeInt(-4); byte[] data = bos.toByteArray(); return Base64.encodeToString(data, Base64.DEFAULT).substring(0, 11); } catch (IOException e) { return null; } }
From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java
@Nullable private String getApkDigestSha256() { try {/* ww w. j a va 2 s . c o m*/ FileInputStream fis = new FileInputStream(context.getPackageCodePath()); MessageDigest md = MessageDigest.getInstance(SHA_256); try { DigestInputStream dis = new DigestInputStream(fis, md); byte[] buffer = new byte[2048]; while (dis.read(buffer) != -1) { // } dis.close(); } finally { fis.close(); } return Base64.encodeToString(md.digest(), Base64.NO_WRAP); } catch (IOException | NoSuchAlgorithmException e) { return null; } }
From source file:io.winch.phonegap.plugin.WinchPlugin.java
private void iterateAsBase64(final CallbackContext callbackContext, JSONArray args) { try {/* w ww.j a v a 2s . c o m*/ String namespace = args.getString(0); Enumerator it1 = new Enumerator() { public int next() { JSONObject obj = new JSONObject(); try { obj.put(KEY, key); String base64 = Base64.encodeToString(data, Base64.NO_WRAP); obj.put(DATA, base64); } catch (JSONException e) { e.printStackTrace(); } PluginResult r = new PluginResult(PluginResult.Status.OK, obj); r.setKeepCallback(true); callbackContext.sendPluginResult(r); return Enumerator.Code.NONE; } }; mWinch.getNamespace(namespace).enumerate(it1); } catch (JSONException e1) { e1.printStackTrace(); } catch (WinchError e) { e.log(); PluginResult r = buildErrorResult(e.getErrorCode(), e.getMessage()); callbackContext.sendPluginResult(r); } PluginResult r = new PluginResult(PluginResult.Status.OK, false); r.setKeepCallback(false); callbackContext.sendPluginResult(r); }
From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java
public String doRedirect(String urlRedirect, boolean useTim) { // android.os.Debug.waitForDebugger(); try {/*from www .ja va2 s . co m*/ // with server phpOIDC, check for '#' if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?")) || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) { String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&"); String code = ""; String state = ""; String state_key = "state"; for (int i = 0; i < params.length; i++) { String param = params[i]; int idxEqual = param.indexOf('='); if (idxEqual >= 0) { String key = param.substring(0, idxEqual); String value = param.substring(idxEqual + 1); if (key.startsWith("code")) code = value; if (key.startsWith("state")) state = value; if (key.startsWith("session_state")) { state = value; state_key = "session_state"; } } } // display code and state Logd(TAG, "doRedirect => code: " + code + " / state: " + state); // doRepost(code,state); if (code.length() > 0) { // get token_endpoint endpoint String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url); if (isEmpty(token_endpoint)) { Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url); return null; } List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); HttpURLConnection huc = getHUC(token_endpoint); huc.setInstanceFollowRedirects(false); if (useTim) { if (mUsePrivateKeyJWT) { nameValuePairs.add(new BasicNameValuePair("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")); String client_assertion = secureStorage.getPrivateKeyJwt(token_endpoint); Logd(TAG, "client_assertion: " + client_assertion); nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion)); } else { huc.setRequestProperty("Authorization", "Basic " + secureStorage.getClientSecretBasic()); } } else { String authorization = (mOcp.m_client_id + ":" + mOcp.m_client_secret); authorization = Base64.encodeToString(authorization.getBytes(), Base64.DEFAULT); huc.setRequestProperty("Authorization", "Basic " + authorization); } huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); huc.setDoOutput(true); huc.setChunkedStreamingMode(0); OutputStream os = huc.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8"); BufferedWriter writer = new BufferedWriter(out); nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code")); nameValuePairs.add(new BasicNameValuePair("code", code)); nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri)); if (state != null && state.length() > 0) nameValuePairs.add(new BasicNameValuePair(state_key, state)); // write URL encoded string from list of key value pairs writer.write(getQuery(nameValuePairs)); writer.flush(); writer.close(); out.close(); os.close(); Logd(TAG, "doRedirect => before connect"); huc.connect(); int responseCode = huc.getResponseCode(); System.out.println("2 - code " + responseCode); Log.d(TAG, "doRedirect => responseCode " + responseCode); InputStream in = null; try { in = new BufferedInputStream(huc.getInputStream()); } catch (IOException ioe) { sysout("io exception: " + huc.getErrorStream()); } if (in != null) { String result = convertStreamToString(in); // now you have the string representation of the HTML request in.close(); Logd(TAG, "doRedirect: " + result); // save as static for now return result; } else { Logd(TAG, "doRedirect null"); } } } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.example.cake.mqtttest.registerActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { super.onActivityResult(requestCode, resultCode, imageReturnedIntent); switch (requestCode) { case SELECT_PHOTO: if (resultCode == RESULT_OK) { Uri selectedImage = imageReturnedIntent.getData(); InputStream imageStream = null; try { imageStream = getContentResolver().openInputStream(selectedImage); Bitmap yourSelectedImage = decodeUri(selectedImage); ImageView x = (ImageView) findViewById(R.id.avatarImageView); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream.toByteArray(); encoded = Base64.encodeToString(byteArray, Base64.DEFAULT); x.setImageBitmap(yourSelectedImage); } catch (FileNotFoundException e) { e.printStackTrace();/*from ww w . j a v a2 s . com*/ } } } }
From source file:com.ntsync.android.sync.client.NetworkUtilities.java
public static Pair<UserRegistrationState, String> registrateUser(Context context, String email, byte[] srpPassword, byte[] pwdSalt, String name) throws ServerException, NetworkErrorException { String username;/*from w w w .ja v a 2s . c om*/ UserRegistrationState state; int retryCount = 5; boolean retry; do { retry = false; state = null; try { // create new Username username = createUsername(context, email); if (username == null) { return new Pair<UserRegistrationState, String>(UserRegistrationState.EMAIL_INVALID, null); } Pair<byte[], BigInteger> verif = SRP6Helper.createUserVerification(username, srpPassword); final HttpPost post = new HttpPost(REGISTRATION_URI); List<BasicNameValuePair> values = new ArrayList<BasicNameValuePair>(); values.add(new BasicNameValuePair("username", username)); values.add(new BasicNameValuePair("email", email)); values.add(new BasicNameValuePair("verif", Base64.encodeToString(BigIntegers.asUnsignedByteArray(verif.right), Base64.DEFAULT))); values.add(new BasicNameValuePair("srpSalt", Base64.encodeToString(verif.left, Base64.DEFAULT))); values.add(new BasicNameValuePair("pwdSalt", Base64.encodeToString(pwdSalt, Base64.DEFAULT))); values.add(new BasicNameValuePair("personname", name)); values.add(new BasicNameValuePair("locale", Locale.getDefault().toString())); HttpEntity postEntity = new UrlEncodedFormEntity(values, SyncDataHelper.DEFAULT_CHARSET_NAME); post.setHeader(postEntity.getContentEncoding()); post.setEntity(postEntity); byte[] content; final HttpResponse resp = getHttpClient(context).execute(post, createHttpContext(username, null)); content = getResponse(resp); if (content != null && content.length > 0) { String respCode = new String(content, SyncDataHelper.DEFAULT_CHARSET_NAME); state = UserRegistrationState.fromErrorVal(respCode); } if (state == null) { throw new ServerException("No valid response"); } } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new NetworkErrorException(ex); } if (state == UserRegistrationState.USERNAME_IN_USE) { // Create a new username when alredy in use (concurrent catch of // username) retry = true; } retryCount--; } while (retry && retryCount > 0); return new Pair<UserRegistrationState, String>(state, username); }
From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java
@SuppressLint("PackageManagerGetSignatures") private List<String> getApkCertificateDigests() { List<String> apkCertificateDigests = new ArrayList<>(); PackageManager pm = context.getPackageManager(); PackageInfo packageInfo;/* w w w . ja v a 2 s .c om*/ try { packageInfo = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES); } catch (PackageManager.NameNotFoundException wtf) { return apkCertificateDigests; } Signature[] signatures = packageInfo.signatures; for (Signature signature : signatures) { try { MessageDigest md = MessageDigest.getInstance(SHA_256); md.update(signature.toByteArray()); byte[] digest = md.digest(); apkCertificateDigests.add(Base64.encodeToString(digest, Base64.NO_WRAP)); } catch (NoSuchAlgorithmException ignored) { } } return apkCertificateDigests; }