List of usage examples for android.util Base64 DEFAULT
int DEFAULT
To view the source code for android.util Base64 DEFAULT.
Click Source Link
From source file:com.facebook.login.LoginMethodHandler.java
private static String getUserIDFromSignedRequest(String signedRequest) throws FacebookException { if (signedRequest == null || signedRequest.isEmpty()) { throw new FacebookException("Authorization response does not contain the signed_request"); }/*from ww w. ja va 2s.c o m*/ try { String[] signatureAndPayload = signedRequest.split("\\."); if (signatureAndPayload.length == 2) { byte[] data = Base64.decode(signatureAndPayload[1], Base64.DEFAULT); String dataStr = new String(data, "UTF-8"); JSONObject jsonObject = new JSONObject(dataStr); return jsonObject.getString("user_id"); } } catch (UnsupportedEncodingException ex) { } catch (JSONException ex) { } throw new FacebookException("Failed to retrieve user_id from signed_request"); }
From source file:com.polatic.pantaudki.home.HomeFragment.java
@Deprecated public static String encodeTobase64(Bitmap image) { Bitmap img = image;// w w w . j av a 2s. c om ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); img.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); byte[] b = byteArrayOutputStream.toByteArray(); String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT); return imageEncoded; }
From source file:org.openihs.seendroid.lib.Connection.java
private void addHeaders(HttpMessage message) { String credentials = Base64.encodeToString((this.username + ":" + this.password).getBytes(), Base64.DEFAULT); message.addHeader("User-agent", "SeenDroid"); message.addHeader("Authorization", "Basic " + credentials.substring(0, credentials.length() - 1)); }
From source file:com.google.samples.apps.abelana.AbelanaThings.java
private static String signData(String data) { try {/*from w w w . ja v a 2 s. c o m*/ if (signer == null) { signer = Signature.getInstance("SHA256withRSA"); signer.initSign(credential.getServiceAccountPrivateKey()); } signer.update(data.getBytes("UTF-8")); byte[] rawSignature = signer.sign(); return new String(Base64.encode(rawSignature, Base64.DEFAULT)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } return null; }
From source file:br.com.vpsa.oauth2android.token.RefreshToken.java
/** * This method is special for the RefreshToken. It makes an authorized request to * the TokenEndpoint (AccessTokenServer) to request a new AccessToken. Therefore * it presents the RefreshToken in a basic http Authorization Header. <br> * You may use GET for the http Method, but it is recommended to use POST. If * the <code>method</code> parameter is empty POST will be used.<br> * The result is an Response-Instance containing the new Access-Token or throwing * an Exception if the server responds with an error. * @param client <code>Client</code> of this application * @param server <code>Server</code> Instance with the service-providers endpoints * @param method <code>String</code> value of the http-method used. * @return the <code>Response</code> of the request containing the AccessToken * @throws InvalidRequestException the request is missing a parameter or is otherwise invalid * @throws InvalidClientException the client could not be identified * @throws InvalidGrantException the authorization grant is not valid * @throws UnauthorizedClientException the token is not valid or is of the wrong type * @throws UnsupportedGrantTypeException the client used an unsupported method for the authorization grant * @throws InvalidScopeException the scope is incomplete or invalid * @throws OAuthException if this is catched, no other {@link org.gerstner.oauth2android.exception.OAuthException} extending Exception will be thrown. * @throws IOException a connection error occurred during the request *//*from w w w . j a v a2s. c o m*/ public Response executeRefreshRequest(Client client, Server server, String method) throws IOException, InvalidRequestException, InvalidClientException, InvalidGrantException, UnauthorizedClientException, UnsupportedGrantTypeException, InvalidScopeException, OAuthException { HttpClient httpClient = new DefaultHttpClient(); Response response; if (method == null) { method = ""; } if (method.equalsIgnoreCase(Connection.HTTP_METHOD_GET)) { String parameterString = "grant_type=refresh_token&client_id=" + client.getClientID() + "&refresh_token=" + this.getToken(); HttpGet httpGet = new HttpGet(server.getAccessTokenServer() + "?" + parameterString); String authorization = Base64.encodeToString( (client.getClientID() + ":" + client.getClientSecret()).getBytes(), Base64.DEFAULT); Header header = new BasicHeader("Authorization", "Basic " + authorization); httpGet.addHeader(header); response = new Response(httpClient.execute(httpGet)); } else { HttpPost httpPost = new HttpPost(server.getAccessTokenServer()); httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> parameterList = new ArrayList<NameValuePair>(); parameterList.add(new BasicNameValuePair("grant_type", "refresh_token")); parameterList.add(new BasicNameValuePair("client_id", client.getClientID())); parameterList.add(new BasicNameValuePair("refresh_token", this.getToken())); httpPost.setEntity(new UrlEncodedFormEntity(parameterList)); response = new Response(httpClient.execute(httpPost)); } return response; }
From source file:com.example.yudiandrean.socioblood.LoginActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //FacebookSdk.sdkInitialize(this.getApplicationContext()); setContentView(R.layout.activity_login); try {/*from www . jav a 2 s . c om*/ PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 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) { } TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET); Fabric.with(this, new Twitter(authConfig)); //instantiate callbacks manager //mCallbackManager = CallbackManager.Factory.create(); inputEmail = (EditText) findViewById(R.id.email); inputPassword = (EditText) findViewById(R.id.password); Btnregister = (Button) findViewById(R.id.registerbtn); btnLogin = (Button) findViewById(R.id.login); passreset = (Button) findViewById(R.id.passres); // facebookLogin = (LoginButton) findViewById(R.id.facebook_login); //facebookLogin.setReadPermissions(permissionNeeds); session = new SessionManager(getApplicationContext()); // Check if user is already logged in or not if (session.isLoggedIn()) { // User is already logged in. Take him to main activity Intent intent = new Intent(LoginActivity.this, FeedActivity.class); startActivity(intent); finish(); } // accessTokenTracker = new AccessTokenTracker() { // @Override // protected void onCurrentAccessTokenChanged( // AccessToken oldAccessToken, // AccessToken currentAccessToken) { // // App code // } // }; // // profileTracker = new ProfileTracker() { // @Override // protected void onCurrentProfileChanged( // Profile oldProfile, // Profile currentProfile) { // // App code // } // }; passreset.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(), PasswordReset.class); startActivityForResult(myIntent, 0); finish(); } }); Btnregister.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(), Register.class); startActivityForResult(myIntent, 0); finish(); } }); /** * Login button click event * A Toast is set to alert when the Email and Password field is empty **/ btnLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if ((!inputEmail.getText().toString().equals("")) && (!inputPassword.getText().toString().equals(""))) { NetAsync(view); } else if ((!inputEmail.getText().toString().equals(""))) { Toast.makeText(getApplicationContext(), "Password field empty", Toast.LENGTH_SHORT).show(); } else if ((!inputPassword.getText().toString().equals(""))) { Toast.makeText(getApplicationContext(), "Email field empty", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Email and Password field are empty", Toast.LENGTH_SHORT).show(); } } }); // //facebook login // facebookLogin.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() { // // // @Override // public void onSuccess(LoginResult loginResults) { // //login ok get access token // AccessToken.getCurrentAccessToken(); // // // } // // @Override // public void onCancel() { // // Toast.makeText(getApplicationContext(), // "Login Cancelled", Toast.LENGTH_SHORT).show(); // } // // // @Override // public void onError(FacebookException e) { // Toast.makeText(getApplicationContext(), // "Login Failed!", Toast.LENGTH_SHORT).show(); // } // }); //Session Manager // TwitterSession session = // Twitter.getSessionManager().getActiveSession(); // TwitterAuthToken authToken = session.getAuthToken(); // String token = authToken.token; // String secret = authToken.secret; //Guest Authentication TwitterCore.getInstance().logInGuest(new Callback<AppSession>() { @Override public void success(Result<AppSession> result) { AppSession guestAppSession = result.data; } @Override public void failure(TwitterException exception) { // unable to get an AppSession with guest auth } }); }
From source file:com.airbop.client.GCMIntentService.java
/** * Decode a base64 string into a Bitmap//from w w w .ja v a 2 s. co m */ private static Bitmap decodeImage(String image_data) { // Decode the encoded string into largeIcon Bitmap largeIcon = null; if ((image_data != null) && (!image_data.equals(""))) { byte[] decodedImage = Base64.decode(image_data, Base64.DEFAULT); if (decodedImage != null) { largeIcon = BitmapFactory.decodeByteArray(decodedImage, 0, decodedImage.length); } } return largeIcon; }
From source file:net.sourcewalker.garanbot.api.ItemService.java
public Bitmap getPicture(int id) throws ClientException { try {/*w ww . j a va 2 s . co m*/ HttpResponse response = client.get("/item/" + id + "/picture"); int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case HttpStatus.SC_OK: Base64InputStream stream = new Base64InputStream(response.getEntity().getContent(), Base64.DEFAULT); Bitmap result = BitmapFactory.decodeStream(stream); if (result == null) { throw new ClientException("Picture could not be decoded!"); } return result; case HttpStatus.SC_NOT_FOUND: return null; default: throw new ClientException("Got HTTP error: " + response.getStatusLine().toString()); } } catch (IOException e) { throw new ClientException("IO error: " + e.getMessage(), e); } }
From source file:com.paymaya.sdk.android.checkout.PayMayaCheckoutActivity.java
private void requestCreateCheckout() { new AsyncTask<Void, Void, Response>() { @Override/* w ww. j a va2 s . c o m*/ protected Response doInBackground(Void... voids) { try { Request request = new Request(Request.Method.POST, PayMayaConfig.getEnvironment() == PayMayaConfig.ENVIRONMENT_PRODUCTION ? BuildConfig.API_CHECKOUT_ENDPOINT_PRODUCTION : BuildConfig.API_CHECKOUT_ENDPOINT_SANDBOX); byte[] body = JSONUtils.toJSON(mCheckout).toString().getBytes(); request.setBody(body); String key = mClientKey + ":"; String authorization = Base64.encodeToString(key.getBytes(), Base64.DEFAULT); Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers.put("Authorization", "Basic " + authorization); headers.put("Content-Length", Integer.toString(body.length)); request.setHeaders(headers); AndroidClient androidClient = new AndroidClient(); return androidClient.call(request); } catch (JSONException e) { return new Response(-1, ""); } } @Override protected void onPostExecute(Response response) { if (response.getCode() == 200) { try { JSONObject responseBody = new JSONObject(response.getResponse()); mSessionRedirectUrl = responseBody.getString("redirectUrl"); String[] redirectUrlParts = mSessionRedirectUrl.split("\\?"); mSessionCheckoutId = redirectUrlParts[redirectUrlParts.length - 1]; if (Build.MANUFACTURER.toLowerCase().contains("samsung")) { mSessionRedirectUrl += "&cssfix=true"; } loadUrl(mSessionRedirectUrl); } catch (JSONException e) { finishFailure(e.getMessage()); } } else { finishFailure(response.getResponse()); } } }.execute(); }
From source file:com.ericrgon.postmark.BaseFragmentActivity.java
protected void encrypt(SecretKey key, String destinationPreference, String value) { byte[] encryptedValue = SecurityUtil.encrypt(key, value); SharedPreferences.Editor editor = getSharedPreferences(CREDENTIALS_PREF_FILE, MODE_PRIVATE).edit(); editor.putString(destinationPreference, Base64.encodeToString(encryptedValue, Base64.DEFAULT)); editor.apply();/* www .j av a 2 s .com*/ }