List of usage examples for android.util Base64 encodeToString
public static String encodeToString(byte[] input, int flags)
From source file:com.facebook.stetho.websocket.WebSocketHandler.java
private static String generateServerKey(String clientKey) { try {//from ww w .j a v a 2s . co m String serverKey = clientKey + SERVER_KEY_GUID; MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); sha1.update(Utf8Charset.encodeUTF8(serverKey)); return Base64.encodeToString(sha1.digest(), Base64.NO_WRAP); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
From source file:io.teak.sdk.Request.java
@Override public void run() { HttpsURLConnection connection = null; SecretKeySpec keySpec = new SecretKeySpec(this.session.appConfiguration.apiKey.getBytes(), "HmacSHA256"); String requestBody;/*from w w w . j av a 2s. c o m*/ String hostnameForEndpoint = this.hostname; if (hostnameForEndpoint == null) { hostnameForEndpoint = this.session.remoteConfiguration.getHostnameForEndpoint(this.endpoint); } try { ArrayList<String> payloadKeys = new ArrayList<>(this.payload.keySet()); Collections.sort(payloadKeys); StringBuilder builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); if (value != null) { String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(valueString).append("&"); } else { Log.e(LOG_TAG, "Value for key: " + key + " is null."); } } builder.deleteCharAt(builder.length() - 1); String stringToSign = "POST\n" + hostnameForEndpoint + "\n" + this.endpoint + "\n" + builder.toString(); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(keySpec); byte[] result = mac.doFinal(stringToSign.getBytes()); builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(URLEncoder.encode(valueString, "UTF-8")).append("&"); } builder.append("sig=") .append(URLEncoder.encode(Base64.encodeToString(result, Base64.NO_WRAP), "UTF-8")); requestBody = builder.toString(); } catch (Exception e) { Log.e(LOG_TAG, "Error signing payload: " + Log.getStackTraceString(e)); return; } try { if (Teak.isDebug) { Log.d(LOG_TAG, "Submitting request to '" + this.endpoint + "': " + new JSONObject(this.payload).toString(2)); } URL url = new URL("https://" + hostnameForEndpoint + this.endpoint); connection = (HttpsURLConnection) url.openConnection(); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(requestBody.getBytes().length)); // Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(requestBody); wr.flush(); wr.close(); // Get Response InputStream is; if (connection.getResponseCode() < 400) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (Teak.isDebug) { String responseText = response.toString(); try { responseText = new JSONObject(response.toString()).toString(2); } catch (Exception ignored) { } Log.d(LOG_TAG, "Reply from '" + this.endpoint + "': " + responseText); } // For extending classes done(connection.getResponseCode(), response.toString()); } catch (Exception e) { Log.e(LOG_TAG, Log.getStackTraceString(e)); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:fr.unix_experience.owncloud_sms.engine.OCHttpClient.java
public int execute(HttpMethod req) throws IOException { String basicAuth = "Basic " + Base64.encodeToString((_username + ":" + _password).getBytes(), Base64.NO_WRAP); req.setDoAuthentication(true);/* w w w . java 2s . c o m*/ req.addRequestHeader("Authorization", basicAuth); executeMethod(req); return followRedirections(req); }
From source file:com.fabernovel.alertevoirie.webservice.AVService.java
/** * Post the image related to the incident, with httpPost method. The comment has to be encoded in base64 * //from w w w . j av a 2 s.c om * @param udid * The device id * @param img_comment * The far image comment * @param incident_id * The id of the related incident * @param image_far * The file containing far image * @param image_near * The file containing close image */ @SuppressWarnings("unchecked") public void postImage(RequestListener listener, String udid, String img_comment, String incident_id, File image_far, File image_near, boolean newIncident) { this.listener = listener; ArrayList<Object> image_1 = new ArrayList<Object>(); ArrayList<Object> image_2 = new ArrayList<Object>(); if (image_far != null) { image_1.add(AV_URL + "photo/"); image_1.add(udid); try { image_1.add(Base64.encodeToString(img_comment.getBytes("UTF-8"), Base64.NO_WRAP));// .replace("=", "%3D")); } catch (UnsupportedEncodingException e) { Log.e(Constants.PROJECT_TAG, "UTF-8 not supported", e); image_1.add(Base64.encodeToString(img_comment.getBytes(), Base64.NO_WRAP));// .replace("=", "%3D")); } image_1.add(incident_id); image_1.add(AV_IMG_FAR); image_1.add(image_far); image_1.add(newIncident); } if (image_near != null) { image_2.add(AV_URL + "photo/"); image_2.add(udid); image_2.add(""); image_2.add(incident_id); image_2.add(AV_IMG_CLOSE); image_2.add(image_near); image_2.add(newIncident); } cancelTask(); currentTask = new postImage().execute(image_1.size() > 0 ? image_1 : null, image_2.size() > 0 ? image_2 : null); // if (image_far != null) { // currentTask = new postImage().execute(image_1, image_2); // } else { // currentTask = new postImage().execute(image_2); // } }
From source file:com.ntsync.android.sync.client.ClientKeyHelper.java
/** * /* ww w .j a va2 s. c o m*/ * @param account * @param accountManager * @param keyPwd * Password for Key * @param salt * @param existingSalt * @param pwdCheck * null for new Key otherwise used to Check if it is the right * Password. * @return * @throws InvalidKeyException * @throws UnsupportedEncodingException */ public static SecretKey createKey(Account account, AccountManager accountManager, String keyPwd, byte[] salt, boolean existingSalt, byte[] pwdCheck) throws InvalidKeyException, UnsupportedEncodingException { KeyGenerator keyGen = new KeyGenerator(); SecretKey skey = keyGen.generateKey(keyPwd, salt); byte[] raw = skey.getEncoded(); String keyValue = Base64.encodeToString(raw, Base64.DEFAULT); String saltStr = Base64.encodeToString(salt, Base64.DEFAULT); assert (existingSalt ? pwdCheck != null : true); byte[] check = pwdCheck; if (existingSalt && pwdCheck != null) { // Validate new Passwort validateKey(check, skey); } else if (!existingSalt) { check = createPwdCheck(skey); } String pwdCheckStr = check != null ? Base64.encodeToString(check, Base64.DEFAULT) : null; accountManager.setUserData(account, PRIVATE_KEY_SALTSAVED, existingSalt ? "true" : "false"); accountManager.setUserData(account, PRIVATE_KEYSALT, saltStr); accountManager.setUserData(account, PRIVATE_PWDCHECK, pwdCheckStr); accountManager.setUserData(account, PRIVATE_PWD, keyPwd); accountManager.setUserData(account, PRIVATE_KEY, keyValue); return skey; }
From source file:com.prad.yahooweather.YahooWeatherActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiHelper = new UiLifecycleHelper(this, callback); uiHelper.onCreate(savedInstanceState); if (savedInstanceState != null) { String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY); pendingAction = PendingAction.valueOf(name); }/*from w w w .j av a2 s .c o m*/ setContentView(R.layout.weather_layout); mImageView = (ImageView) findViewById(R.id.feed_image); // Add code to print out the key hash try { PackageInfo info = getPackageManager().getPackageInfo("com.prad.yahooweather", PackageManager.GET_SIGNATURES); // 9Q4TYYAtIO1mNDFa+Y57Ausm5lE= // Yahoo Weather // App ID: 612655528781332 // App Secret: c6ae83d7cf1aeba1c01045bd37f1db31 for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)); } } catch (Exception e) { } View f = (View) findViewById(R.id.resultTable); f.setVisibility(View.GONE); searchText = (EditText) findViewById(R.id.searchText); searchButton = (Button) findViewById(R.id.search_button); radioGroup = (RadioGroup) findViewById(R.id.searchTypeRadioGroup); mImageView.setLongClickable(true); mImageView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { // TODO Auto-generated method stub Session session = Session.getActiveSession(); if (session != null) { session.closeAndClearTokenInformation(); } else { Session session2 = Session.openActiveSession(YahooWeatherActivity.this, false, null); if (session2 != null) session2.closeAndClearTokenInformation(); } return true; } }); searchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String searchType = ""; boolean isValidInput = false; hideKeyboard(); String searchString = searchText.getText().toString(); if (searchString == null || "".equals(searchString)) { Toast.makeText(YahooWeatherActivity.this, "Text field is empty. Please enter zip or city name.", Toast.LENGTH_SHORT).show(); } else { if (checkIfValidZip(searchString)) { searchType = "zip"; isValidInput = true; } else { if (checkIfValidCity(searchString)) { searchType = "city"; isValidInput = true; } } } if (isValidInput) { new GetJSON().execute(searchString, searchType, getTempTyep()); } } }); postStatusUpdateButton = (TextView) findViewById(R.id.current_weather); postStatusUpdateButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { pendingAction = PendingAction.CURRENT_WEATHER; showFacebookshareDialog("Post Current Weather"); } }); postPhotoButton = (TextView) findViewById(R.id.weather_forecast); postPhotoButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { pendingAction = PendingAction.WEATHER_FORECAST; showFacebookshareDialog("Post Weather Forecast"); } }); canPresentShareDialog = FacebookDialog.canPresentShareDialog(this, FacebookDialog.ShareDialogFeature.SHARE_DIALOG); canPresentShareDialog = true; }
From source file:org.quantumbadger.redreader.reddit.api.RedditOAuth.java
private static FetchRefreshTokenResult fetchRefreshTokenSynchronous(final Context context, final Uri redirectUri) { final String error = redirectUri.getQueryParameter("error"); if (error != null) { if (error.equals("access_denied")) { return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.USER_REFUSED_PERMISSION, new RRError(context.getString(R.string.error_title_login_user_denied_permission), context.getString(R.string.error_message_login_user_denied_permission))); } else {// ww w . ja va 2 s . c om return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.INVALID_REQUEST, new RRError(context.getString(R.string.error_title_login_unknown_reddit_error) + error, context.getString(R.string.error_unknown_message))); } } final String code = redirectUri.getQueryParameter("code"); if (code == null) { return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.INVALID_RESPONSE, new RRError(context.getString(R.string.error_unknown_title), context.getString(R.string.error_unknown_message))); } final String uri = ACCESS_TOKEN_URL; StatusLine responseStatus = null; try { final HttpClient httpClient = CacheManager.createHttpClient(context); final HttpPost request = new HttpPost(uri); final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code")); nameValuePairs.add(new BasicNameValuePair("code", code)); nameValuePairs.add(new BasicNameValuePair("redirect_uri", REDIRECT_URI)); 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 FetchRefreshTokenResult(FetchRefreshTokenResultStatus.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 RefreshToken refreshToken = new RefreshToken(responseObject.getString("refresh_token")); final AccessToken accessToken = new AccessToken(responseObject.getString("access_token")); return new FetchRefreshTokenResult(refreshToken, accessToken); } catch (IOException e) { return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.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 FetchRefreshTokenResult(FetchRefreshTokenResultStatus.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.glabs.homegenie.client.Control.java
public static HttpGet getHttpGetRequest(String url) { HttpGet getRequest = new HttpGet(url); //getRequest.setHeader("Accept", "text/json"); if (!_hg_user.equals("") && !_hg_pass.equals("")) { getRequest.addHeader("Authorization", "Basic " + Base64.encodeToString((_hg_user + ":" + _hg_pass).getBytes(), Base64.NO_WRAP)); }/*from w w w .ja va2 s.c o m*/ return getRequest; }
From source file:org.wso2.emm.agent.utils.CommonUtils.java
/** * Generates keys, CSR and certificates for the devices. * @param context - Application context. * @param listener - DeviceCertCreationListener which provide device . *///from www.j a v a 2s. c o m public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener) throws AndroidAgentException { if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) { try { listener.onDeviceCertCreated( new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } else { try { ServerConfig utils = new ServerConfig(); final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE) .generateKeyPair(); X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject, deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate()); EndPointInfo endPointInfo = new EndPointInfo(); endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.POST); endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT); endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT)); new APIController().invokeAPI(endPointInfo, new APIResultCallBack() { @Override public void onReceiveAPIResult(Map<String, String> result, int requestCode) { try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream( Base64.decode(result.get("response"), Base64.DEFAULT)); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null); keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS, (Key) deviceKeyPair.getPrivate(), Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { cert }); keyStore.store(byteArrayOutputStream, Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray()); FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME, Context.MODE_PRIVATE); outputStream.write(byteArrayOutputStream.toByteArray()); byteArrayOutputStream.close(); outputStream.close(); try { listener.onDeviceCertCreated(new BufferedInputStream( context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } catch (CertificateException e) { Log.e(TAG, e.getMessage()); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }, Constants.SCEP_REQUEST_CODE, context, true); } catch (NoSuchAlgorithmException e) { throw new AndroidAgentException("No algorithm for key generation", e); } catch (SignatureException e) { throw new AndroidAgentException("Invalid Signature", e); } catch (NoSuchProviderException e) { throw new AndroidAgentException("Invalid provider", e); } catch (InvalidKeyException e) { throw new AndroidAgentException("Invalid key", e); } } }
From source file:com.luyaozhou.recognizethisforglass.ViewFinder.java
private void processPictureWhenReady(final String picturePath) { final File pictureFile = new File(picturePath); //Map<String, String > result = new HashMap<String,String>(); if (pictureFile.exists()) { // The picture is ready; process it. Bitmap imageBitmap = null;/*from w w w . j ava 2s.c o m*/ try { // Bundle extras = data.getExtras(); // imageBitmap = (Bitmap) extras.get("data"); FileInputStream fis = new FileInputStream(picturePath); //get the bitmap from file imageBitmap = (Bitmap) BitmapFactory.decodeStream(fis); if (imageBitmap != null) { Bitmap lScaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 1600, 1200, false); if (lScaledBitmap != null) { imageBitmap.recycle(); imageBitmap = null; ByteArrayOutputStream lImageBytes = new ByteArrayOutputStream(); lScaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, lImageBytes); lScaledBitmap.recycle(); lScaledBitmap = null; byte[] lImageByteArray = lImageBytes.toByteArray(); HashMap<String, String> lValuePairs = new HashMap<String, String>(); lValuePairs.put("base64Image", Base64.encodeToString(lImageByteArray, Base64.DEFAULT)); lValuePairs.put("compressionLevel", "30"); lValuePairs.put("documentIdentifier", "DRIVER_LICENSE_CA"); lValuePairs.put("documentHints", ""); lValuePairs.put("dataReturnLevel", "15"); lValuePairs.put("returnImageType", "1"); lValuePairs.put("rotateImage", "0"); lValuePairs.put("data1", ""); lValuePairs.put("data2", ""); lValuePairs.put("data3", ""); lValuePairs.put("data4", ""); lValuePairs.put("data5", ""); lValuePairs.put("userName", "zbroyan@miteksystems.com"); lValuePairs.put("password", "google1"); lValuePairs.put("phoneKey", "1"); lValuePairs.put("orgName", "MobileImagingOrg"); String lSoapMsg = formatSOAPMessage("InsertPhoneTransaction", lValuePairs); DefaultHttpClient mHttpClient = new DefaultHttpClient(); // mHttpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.R) HttpPost mHttpPost = new HttpPost(); mHttpPost.setHeader("User-Agent", "UCSD Team"); mHttpPost.setHeader("Content-typURIe", "text/xml;charset=UTF-8"); //mHttpPost.setURI(URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx?op=InsertPhoneTransaction")); mHttpPost.setURI( URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx")); StringEntity se = new StringEntity(lSoapMsg, HTTP.UTF_8); se.setContentType("text/xml; charset=UTF-8"); mHttpPost.setEntity(se); HttpResponse mResponse = mHttpClient.execute(mHttpPost, new BasicHttpContext()); String responseString = new BasicResponseHandler().handleResponse(mResponse); parseXML(responseString); //Todo: this is test code. Need to be implemented //result = parseXML(testStr); Log.i("test", "test:" + " " + responseString); Log.i("test", "test: " + " " + map.size()); } } } catch (Exception e) { e.printStackTrace(); } // this part will be relocated in order to let the the server process picture if (map.size() == 0) { Intent display = new Intent(getApplicationContext(), DisplayInfoFailed.class); display.putExtra("result", (java.io.Serializable) iQAMsg); startActivity(display); } else { Intent display = new Intent(getApplicationContext(), DisplayInfo.class); display.putExtra("result", (java.io.Serializable) map); startActivity(display); } } else { // The file does not exist yet. Before starting the file observer, you // can update your UI to let the user know that the application is // waiting for the picture (for example, by displaying the thumbnail // image and a progress indicator). final File parentDirectory = pictureFile.getParentFile(); FileObserver observer = new FileObserver(parentDirectory.getPath(), FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) { // Protect against additional pending events after CLOSE_WRITE // or MOVED_TO is handled. private boolean isFileWritten; @Override public void onEvent(int event, final String path) { if (!isFileWritten) { // For safety, make sure that the file that was created in // the directory is actually the one that we're expecting. File affectedFile = new File(parentDirectory, path); isFileWritten = affectedFile.equals(pictureFile); if (isFileWritten) { stopWatching(); // Now that the file is ready, recursively call // processPictureWhenReady again (on the UI thread). runOnUiThread(new Runnable() { @Override public void run() { new LongOperation().execute(picturePath); } }); } } } }; observer.startWatching(); } }