List of usage examples for android.util Base64 encodeToString
public static String encodeToString(byte[] input, int flags)
From source file:uk.ac.horizon.ubihelper.service.PeerManager.java
/** called from checkMessage(pi) to handle message in state STATE_PEER_REQ */ private boolean handlePeerReqResponse(PeerRequestInfo pi, Message m) { if (m.type != Message.Type.MANAGEMENT) { failPeer(pi, "Received init_peer_req response of type " + m.type); return false; }// ww w .j a va2 s . co m String pinGuess = null; try { JSONObject msg = new JSONObject(m.body); String type = msg.getString(MessageUtils.KEY_TYPE); if (!MessageUtils.MSG_RESP_PEER_PIN.equals(type)) { if (MessageUtils.MSG_RESP_PEER_NOPIN.equals(type)) { return handlePeerNopin(pi, msg); } failPeer(pi, "Received init_peer_req response " + type); // TODO resp_peer_known return false; } // id, name, port, pin pinGuess = msg.getString(MessageUtils.KEY_PIN); pi.id = msg.getString(MessageUtils.KEY_ID); // TODO known IDs? int port = msg.getInt(MessageUtils.KEY_PORT); if (port != pi.port) Log.w(TAG, "resp_peer_pin has different port: " + port + " vs " + pi.port); String name = msg.getString(MessageUtils.KEY_NAME); if (pi.instanceName == null) pi.instanceName = name; else if (!name.equals(pi.instanceName)) Log.w(TAG, "resp_peer_pin has different name: " + name + " vs " + pi.instanceName); } catch (JSONException e) { failPeer(pi, "Error in resp_peer_pin message: " + e); return false; } Log.i(TAG, "Received resp_peer_pin in state peer_req with pin=" + pinGuess); // pin? if (!pi.pin.equals(pinGuess)) { failPeer(pi, "Incorrect pin: " + pinGuess); return false; } // done try { JSONObject resp = new JSONObject(); resp.put(MessageUtils.KEY_TYPE, MessageUtils.MSG_INIT_PEER_DONE); byte sbuf[] = new byte[8]; protocol.getRandom(sbuf); pi.secret1 = Base64.encodeToString(sbuf, Base64.DEFAULT); resp.put(MessageUtils.KEY_SECRET, pi.secret1); resp.put(MessageUtils.KEY_PINNONCE, pi.pinnonce); JSONObject info = getInfo(); if (info != null) resp.put(MessageUtils.KEY_INFO, info); Message r = new Message(Message.Type.MANAGEMENT, null, null, resp.toString()); pi.pc.sendMessage(r); pi.state = PeerRequestState.STATE_PEER_DONE; pi.detail = null; broadcastPeerState(pi); return true; } catch (JSONException e) { // shouldn't happen! Log.e(TAG, "JSON error (shoulnd't be): " + e); } return false; }
From source file:com.orange.oidc.tim.service.SIMStorage.java
public String getClientSecretBasic() { String bearer = (getClientId() + ":" + getTimSecret()); return Base64.encodeToString(bearer.getBytes(), Base64.DEFAULT); }
From source file:com.vkassin.mtrade.Common.java
public static void delOrder(final Context ctx, History hist) { JSONObject msg = new JSONObject(); try {// w w w . j a v a2s .co m msg.put("objType", Common.CREATE_REMOVE_ORDER); msg.put("time", Calendar.getInstance().getTimeInMillis()); msg.put("version", Common.PROTOCOL_VERSION); msg.put("orderNum", ++ordernum); msg.put("action", "REMOVE"); msg.put("transSerial", hist.getSerial()); if (isSSL) { // ? ?: reject-orderNum-transitSerial // : reject-50249-107683 String forsign = "reject-" + msg.getString("orderNum") + "-" + msg.getString("transSerial"); byte[] signed = Common.signText(Common.signProfile, forsign.getBytes(), true); String gsign = Base64.encodeToString(signed, Base64.DEFAULT); msg.put("gostSign", gsign); } mainActivity.writeJSONMsg(msg); } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "Error! Cannot create JSON order object (delOrder)", e); } }
From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java
/** * Creates a JSON Object from a Tweet TODO: Move this where it belongs! * /*from w ww .j ava2 s .co m*/ * @param c * @return * @throws JSONException */ protected JSONObject getJSON(Cursor c) throws JSONException { JSONObject o = new JSONObject(); if (c.getColumnIndex(Tweets.COL_USER_TID) < 0 || c.getColumnIndex(TwitterUsers.COL_SCREEN_NAME) < 0) { Log.i(TAG, "missing user data"); return null; } else { o.put(Tweets.COL_USER_TID, c.getLong(c.getColumnIndex(Tweets.COL_USER_TID))); o.put(TYPE, MESSAGE_TYPE_TWEET); o.put(TwitterUsers.COL_SCREEN_NAME, c.getString(c.getColumnIndex(TwitterUsers.COL_SCREEN_NAME))); if (c.getColumnIndex(Tweets.COL_CREATED_AT) >= 0) o.put(Tweets.COL_CREATED_AT, c.getLong(c.getColumnIndex(Tweets.COL_CREATED_AT))); if (c.getColumnIndex(Tweets.COL_CERTIFICATE) >= 0) o.put(Tweets.COL_CERTIFICATE, c.getString(c.getColumnIndex(Tweets.COL_CERTIFICATE))); if (c.getColumnIndex(Tweets.COL_SIGNATURE) >= 0) o.put(Tweets.COL_SIGNATURE, c.getString(c.getColumnIndex(Tweets.COL_SIGNATURE))); if (c.getColumnIndex(Tweets.COL_TEXT) >= 0) o.put(Tweets.COL_TEXT, c.getString(c.getColumnIndex(Tweets.COL_TEXT))); if (c.getColumnIndex(Tweets.COL_REPLY_TO_TWEET_TID) >= 0) o.put(Tweets.COL_REPLY_TO_TWEET_TID, c.getLong(c.getColumnIndex(Tweets.COL_REPLY_TO_TWEET_TID))); if (c.getColumnIndex(Tweets.COL_LAT) >= 0) o.put(Tweets.COL_LAT, c.getDouble(c.getColumnIndex(Tweets.COL_LAT))); if (c.getColumnIndex(Tweets.COL_LNG) >= 0) o.put(Tweets.COL_LNG, c.getDouble(c.getColumnIndex(Tweets.COL_LNG))); if (!c.isNull(c.getColumnIndex(Tweets.COL_MEDIA_URIS))) { String photoUri = c.getString(c.getColumnIndex(Tweets.COL_MEDIA_URIS)); Uri uri = Uri.parse(photoUri); o.put(Tweets.COL_MEDIA_URIS, uri.getLastPathSegment()); } if (c.getColumnIndex(Tweets.COL_HTML_PAGES) >= 0) o.put(Tweets.COL_HTML_PAGES, c.getString(c.getColumnIndex(Tweets.COL_HTML_PAGES))); if (c.getColumnIndex(Tweets.COL_SOURCE) >= 0) o.put(Tweets.COL_SOURCE, c.getString(c.getColumnIndex(Tweets.COL_SOURCE))); if (c.getColumnIndex(Tweets.COL_TID) >= 0 && !c.isNull(c.getColumnIndex(Tweets.COL_TID))) o.put(Tweets.COL_TID, c.getLong(c.getColumnIndex(Tweets.COL_TID))); if (c.getColumnIndex(TwitterUsers.COL_PROFILE_IMAGE_URI) >= 0 && c.getColumnIndex(TweetsContentProvider.COL_USER_ROW_ID) >= 0) { String imageUri = c.getString(c.getColumnIndex(TwitterUsers.COL_PROFILE_IMAGE_URI)); Bitmap profileImage = ImageLoader.getInstance().loadImageSync(imageUri); if (profileImage != null) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); profileImage.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); String profileImageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT); o.put(TwitterUsers.JSON_FIELD_PROFILE_IMAGE, profileImageBase64); } } return o; } }
From source file:se.leap.bitmaskclient.ProviderAPI.java
private boolean loadCertificate(String cert_string) { try {//from w w w .j ava2 s .co m // API returns concatenated cert & key. Split them for OpenVPN options String certificateString = null, keyString = null; String[] certAndKey = cert_string.split("(?<=-\n)"); for (int i = 0; i < certAndKey.length - 1; i++) { if (certAndKey[i].contains("KEY")) { keyString = certAndKey[i++] + certAndKey[i]; } else if (certAndKey[i].contains("CERTIFICATE")) { certificateString = certAndKey[i++] + certAndKey[i]; } } RSAPrivateKey key = ConfigHelper.parseRsaKeyFromString(keyString); keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT); preferences.edit() .putString(Constants.PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----") .commit(); X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString); certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT); preferences.edit() .putString(Constants.CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----") .commit(); return true; } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } }
From source file:net.openid.appauth.AuthorizationRequest.java
private static String generateRandomState() { SecureRandom sr = new SecureRandom(); byte[] random = new byte[STATE_LENGTH]; sr.nextBytes(random);//w ww. ja v a 2 s .c om return Base64.encodeToString(random, Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE); }
From source file:com.google.android.gms.common.GooglePlayServicesUtil.java
private static byte[] m107a(PackageInfo packageInfo, byte[]... bArr) { try {/*from ww w .j a v a2 s . c o m*/ CertificateFactory instance = CertificateFactory.getInstance("X509"); if (packageInfo.signatures.length != 1) { Log.w("GooglePlayServicesUtil", "Package has more than one signature."); return null; } try { try { ((X509Certificate) instance .generateCertificate(new ByteArrayInputStream(packageInfo.signatures[0].toByteArray()))) .checkValidity(); byte[] toByteArray = packageInfo.signatures[0].toByteArray(); for (byte[] bArr2 : bArr) { if (Arrays.equals(bArr2, toByteArray)) { return bArr2; } } if (Log.isLoggable("GooglePlayServicesUtil", 2)) { Log.v("GooglePlayServicesUtil", "Signature not valid. Found: \n" + Base64.encodeToString(toByteArray, 0)); } return null; } catch (CertificateExpiredException e) { Log.w("GooglePlayServicesUtil", "Certificate has expired."); return null; } catch (CertificateNotYetValidException e2) { Log.w("GooglePlayServicesUtil", "Certificate is not yet valid."); return null; } } catch (CertificateException e3) { Log.w("GooglePlayServicesUtil", "Could not generate certificate."); return null; } } catch (CertificateException e4) { Log.w("GooglePlayServicesUtil", "Could not get certificate instance."); return null; } }
From source file:com.cloudant.sync.cordova.CloudantSyncPlugin.java
/** * @param rev - The DocumentRevision to transform * @return - The JSONObject from the converted DocumentRevision * @throws JSONException/*w w w . j av a 2s .co m*/ * @throws IOException */ private JSONObject buildJSON(DocumentRevision rev, boolean isCreate) throws JSONException, IOException { JSONObject result = new JSONObject(); result.put(DOC_ID, rev.getId()); result.put(DOC_REV, rev.getRevision()); if (!isCreate) { result.put(DOC_DELETED, rev.isDeleted()); } if (!rev.isDeleted()) { Map<String, Attachment> attachmentMap = rev.getAttachments(); if (attachmentMap != null && !attachmentMap.isEmpty()) { JSONObject attachments = new JSONObject(); for (Map.Entry<String, Attachment> entry : attachmentMap.entrySet()) { Attachment attachment = entry.getValue(); InputStream is = attachment.getInputStream(); byte[] bytes = IOUtils.toByteArray(is); String data = Base64.encodeToString(bytes, Base64.NO_WRAP); JSONObject attachmentJSON = new JSONObject(); attachmentJSON.put(DOC_ATTACHMENTS_CONTENT_TYPE, attachment.type); attachmentJSON.put(DOC_ATTACHMENTS_DATA, data); attachments.put(entry.getKey(), attachmentJSON); } result.put(DOC_ATTACHMENTS, attachments); } } Map<String, Object> body = rev.getBody().asMap(); for (Map.Entry<String, Object> entry : body.entrySet()) { result.put(entry.getKey(), entry.getValue()); } return result; }
From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java
private String encodeBitmap(Bitmap bitmap) { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); BufferedOutputStream out = new BufferedOutputStream(bytesOut); bitmap.compress(CompressFormat.JPEG, 50, out); return Base64.encodeToString(bytesOut.toByteArray(), Base64.DEFAULT); }
From source file:com.vkassin.mtrade.Common.java
public static void putOrder(final Context ctx, Quote quote) { final Instrument it = Common.selectedInstrument;// adapter.getItem(selectedRowId); final Dialog dialog = new Dialog(ctx); dialog.setContentView(R.layout.order_dialog); dialog.setTitle(R.string.OrderDialogTitle); datetxt = (EditText) dialog.findViewById(R.id.expdateedit); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); Date dat1 = new Date(); datetxt.setText(sdf.format(dat1));//from ww w.jav a 2 s . c o m mYear = dat1.getYear() + 1900; mMonth = dat1.getMonth(); mDay = dat1.getDate(); final Date dat = new GregorianCalendar(mYear, mMonth, mDay).getTime(); datetxt.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.i(TAG, "Show DatePickerDialog"); DatePickerDialog dpd = new DatePickerDialog(ctx, mDateSetListener, mYear, mMonth, mDay); dpd.show(); } }); TextView itext = (TextView) dialog.findViewById(R.id.instrtext); itext.setText(it.symbol); final Spinner aspinner = (Spinner) dialog.findViewById(R.id.acc_spinner); List<String> list = new ArrayList<String>(Common.getAccountList()); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(Common.app_ctx, android.R.layout.simple_spinner_item, list); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item); aspinner.setAdapter(dataAdapter); final EditText pricetxt = (EditText) dialog.findViewById(R.id.priceedit); final EditText quanttxt = (EditText) dialog.findViewById(R.id.quantedit); final Button buttonpm = (Button) dialog.findViewById(R.id.buttonPriceMinus); buttonpm.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { double price = Double.valueOf(pricetxt.getText().toString()); price -= 0.01; if (price < 0) price = 0; pricetxt.setText(twoDForm.format(price)); } catch (Exception e) { Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show(); } } }); final Button buttonpp = (Button) dialog.findViewById(R.id.buttonPricePlus); buttonpp.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { double price = Double.valueOf(pricetxt.getText().toString()); price += 0.01; pricetxt.setText(twoDForm.format(price)); } catch (Exception e) { Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show(); } } }); final Button buttonqm = (Button) dialog.findViewById(R.id.buttonQtyMinus); buttonqm.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { long qty = Long.valueOf(quanttxt.getText().toString()); qty -= 1; if (qty < 0) qty = 0; quanttxt.setText(String.valueOf(qty)); } catch (Exception e) { Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show(); } } }); final Button buttonqp = (Button) dialog.findViewById(R.id.buttonQtyPlus); buttonqp.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { long qty = Long.valueOf(quanttxt.getText().toString()); qty += 1; quanttxt.setText(String.valueOf(qty)); } catch (Exception e) { Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show(); } } }); final RadioButton bu0 = (RadioButton) dialog.findViewById(R.id.radio0); final RadioButton bu1 = (RadioButton) dialog.findViewById(R.id.radio1); if (quote != null) { // pricetxt.setText(quote.price.toString()); pricetxt.setText(quote.getPriceS()); if (quote.qtyBuy > 0) { quanttxt.setText(quote.qtyBuy.toString()); bu1.setChecked(true); bu0.setChecked(false); } else { quanttxt.setText(quote.qtySell.toString()); bu1.setChecked(false); bu0.setChecked(true); } } Button customDialog_Cancel = (Button) dialog.findViewById(R.id.cancelbutt); customDialog_Cancel.setOnClickListener(new Button.OnClickListener() { public void onClick(View arg0) { dialog.dismiss(); } }); Button customDialog_Put = (Button) dialog.findViewById(R.id.putorder); customDialog_Put.setOnClickListener(new Button.OnClickListener() { public void onClick(View arg0) { Double price = new Double(0); Long qval = new Long(0); try { price = Double.valueOf(pricetxt.getText().toString()); } catch (Exception e) { Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show(); return; } try { qval = Long.valueOf(quanttxt.getText().toString()); } catch (Exception e) { Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show(); return; } if (dat.compareTo(new GregorianCalendar(mYear, mMonth, mDay).getTime()) > 0) { Toast.makeText(ctx, R.string.CorrectDate, Toast.LENGTH_SHORT).show(); return; } JSONObject msg = new JSONObject(); try { msg.put("objType", Common.CREATE_REMOVE_ORDER); msg.put("time", Calendar.getInstance().getTimeInMillis()); msg.put("version", Common.PROTOCOL_VERSION); msg.put("device", "Android"); msg.put("instrumId", Long.valueOf(it.id)); msg.put("price", price); msg.put("qty", qval); msg.put("ordType", 1); msg.put("side", bu0.isChecked() ? 0 : 1); msg.put("code", String.valueOf(aspinner.getSelectedItem())); msg.put("orderNum", ++ordernum); msg.put("action", "CREATE"); boolean b = (((mYear - 1900) == dat.getYear()) && (mMonth == dat.getMonth()) && (mDay == dat.getDate())); if (!b) msg.put("expired", String.format("%02d.%02d.%04d", mDay, mMonth + 1, mYear)); if (isSSL) { // ? ?: newOrder-orderNum-instrumId-side-price-qty-code-ordType // : newOrder-16807-20594623-0-1150-13-1027700451-1 String forsign = "newOrder-" + ordernum + "-" + msg.getString("instrumId") + "-" + msg.getString("side") + "-" + JSONObject.numberToString(Double.valueOf(msg.getDouble("price"))) + "-" + msg.getString("qty") + "-" + msg.getString("code") + "-" + msg.getString("ordType"); byte[] signed = Common.signText(Common.signProfile, forsign.getBytes(), true); String gsign = Base64.encodeToString(signed, Base64.DEFAULT); msg.put("gostSign", gsign); } mainActivity.writeJSONMsg(msg); } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "Error! Cannot create JSON order object", e); } dialog.dismiss(); } }); dialog.show(); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.FILL_PARENT; lp.height = WindowManager.LayoutParams.FILL_PARENT; dialog.getWindow().setAttributes(lp); }