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.pdftron.pdf.utils.Utils.java
public static String encryptIt(Context context, String value) { String cryptoPass = context.getString(context.getApplicationInfo().labelRes); try {/*from w ww .j av a2 s .c o m*/ DESKeySpec keySpec = new DESKeySpec(cryptoPass.getBytes("UTF8")); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(keySpec); byte[] clearText = value.getBytes("UTF8"); // Cipher is not thread safe Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key); String encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT); Log.d("MiscUtils", "Encrypted: " + value + " -> " + encrypedValue); return encrypedValue; } catch (Exception e) { Log.d(e.getClass().getName(), e.getMessage()); } return value; }
From source file:com.phonegap.plugins.blinkid.BlinkIdScanner.java
/** * Called when the scanner intent completes. * /* w ww .j a v a 2s . c om*/ * @param requestCode * The request code originally supplied to * startActivityForResult(), allowing you to identify who this * result came from. * @param resultCode * The integer result code returned by the child activity through * its setResult(). * @param data * An Intent, which can return result data to the caller (various * data can be attached to Intent "extras"). */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE) { if (resultCode == ScanCard.RESULT_OK) { // First, obtain recognition result RecognitionResults results = data.getParcelableExtra(ScanCard.EXTRAS_RECOGNITION_RESULTS); // Get scan results array. If scan was successful, array will contain at least one element. // Multiple element may be in array if multiple scan results from single image were allowed in settings. BaseRecognitionResult[] resultArray = results.getRecognitionResults(); // Each recognition result corresponds to active recognizer. There are 7 types of // recognizers available (PDF417, USDL, Bardecoder, ZXing, MRTD, UKDL and MyKad), // so there are 7 types of results available. JSONArray resultsList = new JSONArray(); for (BaseRecognitionResult res : resultArray) { try { if (res instanceof Pdf417ScanResult) { // check if scan result is result of Pdf417 recognizer resultsList.put(buildPdf417Result((Pdf417ScanResult) res)); } else if (res instanceof BarDecoderScanResult) { // check if scan result is result of BarDecoder recognizer resultsList.put(buildBarDecoderResult((BarDecoderScanResult) res)); } else if (res instanceof ZXingScanResult) { // check if scan result is result of ZXing recognizer resultsList.put(buildZxingResult((ZXingScanResult) res)); } else if (res instanceof MRTDRecognitionResult) { // check if scan result is result of MRTD recognizer resultsList.put(buildMRTDResult((MRTDRecognitionResult) res)); } else if (res instanceof USDLScanResult) { // check if scan result is result of US Driver's Licence recognizer resultsList.put(buildUSDLResult((USDLScanResult) res)); } else if (res instanceof EUDLRecognitionResult) { // check if scan result is result of EUDL recognizer resultsList.put(buildUKDLResult((EUDLRecognitionResult) res)); } else if (res instanceof MyKadRecognitionResult) { // check if scan result is result of MyKad recognizer resultsList.put(buildMyKadResult((MyKadRecognitionResult) res)); } } catch (Exception e) { Log.e(LOG_TAG, "Error parsing " + res.getClass().getName()); } } try { JSONObject root = new JSONObject(); root.put(RESULT_LIST, resultsList); if (mImageType != IMAGE_NONE) { Image resultImage = ImageHolder.getInstance().getLastImage(); if (resultImage != null) { Bitmap resultImgBmp = resultImage.convertToBitmap(); if (resultImgBmp != null) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); boolean success = resultImgBmp.compress(Bitmap.CompressFormat.JPEG, COMPRESSED_IMAGE_QUALITY, byteArrayOutputStream); if (success) { String resultImgBase64 = Base64 .encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT); root.put(RESULT_IMAGE, resultImgBase64); } try { byteArrayOutputStream.close(); } catch (IOException ignorable) { } } ImageHolder.getInstance().clear(); } } root.put(CANCELLED, false); this.callbackContext.success(root); } catch (JSONException e) { Log.e(LOG_TAG, "This should never happen"); } } else if (resultCode == ScanCard.RESULT_CANCELED) { JSONObject obj = new JSONObject(); try { obj.put(CANCELLED, true); } catch (JSONException e) { Log.e(LOG_TAG, "This should never happen"); } this.callbackContext.success(obj); } else { this.callbackContext.error("Unexpected error"); } } }
From source file:com.orange.oidc.tim.service.SDCardStorage.java
public String getClientSecretBasic() { String bearer = (TIM_client_id + ":" + TIM_secret); return Base64.encodeToString(bearer.getBytes(), Base64.DEFAULT); }
From source file:reportsas.com.formulapp.Formulario.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (data != null) { if (data.hasExtra("data")) { Bitmap photobmp = (Bitmap) data.getParcelableExtra("data"); // iv.setImageBitmap(photobmp); ByteArrayOutputStream baos = new ByteArrayOutputStream(); photobmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); if (parametroCam == null) { parametroCam = new ParametrosRespuesta(2); }//from w ww. j a va 2 s . co m parametroCam.setValor(encodedImage); // prueba.setText(encodedImage); // new MyAsyncTask(Formulario.this) // .execute("POST",encodedImage, HTTP_EVENT); } } } if (requestCode == MY_REQUEST_CODE && resultCode == Pdf417ScanActivity.RESULT_OK) { // First, obtain scan results array. If scan was successful, array will contain at least one element. // Multiple element may be in array if multiple scan results from single image were allowed in settings. Parcelable[] resultArray = data .getParcelableArrayExtra(Pdf417ScanActivity.EXTRAS_RECOGNITION_RESULT_LIST); StringBuilder sb = new StringBuilder(); for (Parcelable p : resultArray) { if (p instanceof Pdf417ScanResult) { // check if scan result is result of Pdf417 recognizer Pdf417ScanResult result = (Pdf417ScanResult) p; // getStringData getter will return the string version of barcode contents String barcodeData = result.getStringData(); // isUncertain getter will tell you if scanned barcode contains some uncertainties boolean uncertainData = result.isUncertain(); // getRawData getter will return the raw data information object of barcode contents BarcodeDetailedData rawData = result.getRawData(); // BarcodeDetailedData contains information about barcode's binary layout, if you // are only interested in raw bytes, you can obtain them with getAllData getter byte[] rawDataBuffer = rawData.getAllData(); DataR = rawData.toString(); String[] arrayElements = DataR.split("Element #"); String Nombre = "", Apellido = "", cedula = "", fecha = "", dia, mes, ano; if (arrayElements.length >= 7) { String[] auxliarArray = arrayElements[7].split("decoded\\):"); String strDatos = auxliarArray[1]; char[] ca = strDatos.toCharArray(); for (int i = 0; i < strDatos.length(); i++) { if (Character.isLetter(ca[i])) //Si es letra Apellido += ca[i]; //Salto de lnea e imprimimos el carcter else //Si no es letra cedula += ca[i]; //Imprimimos el carcter } Apellido = Apellido.trim(); cedula = (cedula.replaceAll("\n", "")).trim(); if (cedula.length() == 0) { auxliarArray = arrayElements[5].split("decoded\\):"); strDatos = auxliarArray[1]; ca = strDatos.toCharArray(); Apellido = ""; for (int i = 0; i < strDatos.length(); i++) { if (Character.isLetter(ca[i])) //Si es letra Apellido += ca[i]; //Salto de lnea e imprimimos el carcter else //Si no es letra cedula += ca[i]; //Imprimimos el carcter } Apellido = Apellido.trim(); cedula = (cedula.replaceAll("\n", "")).trim(); cedula = cedula.substring(cedula.length() - 10, cedula.length()); cedula = eliminarceros(cedula); auxliarArray = arrayElements[9].split("decoded\\):"); Nombre = (auxliarArray[1].replaceAll("\n", "")).trim(); } else { cedula = eliminarceros(cedula); auxliarArray = arrayElements[11].split("decoded\\):"); Nombre = (auxliarArray[1].replaceAll("\n", "")).trim(); } auxliarArray = result.getStringData().toString().split(Nombre); strDatos = auxliarArray[1]; ca = strDatos.toCharArray(); Boolean result_ciclo = true; int i = 0; while (result_ciclo) { if (Character.isDigit(ca[i])) { fecha += ca[i]; } if (fecha.length() >= 9) { result_ciclo = false; } i++; } fecha = fecha.substring(1, fecha.length()); } else { int puntoI = 0; if (barcodeData.indexOf("1F") > 0) { puntoI = barcodeData.indexOf("1F"); } else if (barcodeData.indexOf("0M") > 0) { puntoI = barcodeData.indexOf("0M"); } else if (barcodeData.indexOf("0F") > 0) { puntoI = barcodeData.indexOf("0F"); } else if (barcodeData.indexOf("1M") > 0) { puntoI = barcodeData.indexOf("1M"); } else { } if (puntoI > 0) { String seb = barcodeData.substring(1, puntoI); fecha = barcodeData.substring(puntoI + 2, puntoI + 10); int posL = 0, posE; char[] ca = seb.toCharArray(); for (int w = seb.length() - 1; w > 0; w--) { if (Character.isLetter(ca[w])) { posL = w; break; } } seb = seb.substring(1, posL + 1); ca = seb.toCharArray(); for (int w = seb.length() - 1; w > 0; w--) { if (Character.isLetter(ca[w])) { Nombre = ca[w] + Nombre; posL = w; } else { break; } } seb = seb.substring(1, posL); ca = seb.toCharArray(); for (int w = seb.length() - 1; w > 0; w--) { if (Character.isDigit(ca[w])) { posL = w; break; } } for (int w = posL + 1; w <= seb.length(); w++) { if (Character.isLetter(ca[w])) { Apellido += ca[w]; } else { break; } } cedula = seb.substring(posL - 9, posL + 1); cedula = eliminarceros(cedula); } else { fecha = ""; } } if (fecha.length() == 0) { parametroScan = null; Toast toast1 = Toast.makeText(this, "Los datos de codigo no pudieron ser interpretados!", Toast.LENGTH_SHORT); toast1.show(); } else { dia = fecha.substring(6, 8); mes = fecha.substring(4, 6); ano = fecha.substring(0, 4); fecha = dia + "/" + mes + "/" + ano; Infocadena = "Nombre: \n" + Nombre + ".\nApellido: \n" + Apellido + ". \nCedula: \n" + cedula + ". \nFecha de Nacimiento: \n" + fecha + "."; if (parametroScan == null) { parametroScan = new ParametrosRespuesta(3); } parametroScan.setValor(Infocadena); } // new MyAsyncTask(Formulario.this) // .execute("POST",Infocadena, HTTP_EVENT); } else if (p instanceof BarDecoderScanResult) { // check if scan result is result of BarDecoder recognizer /* BarDecoderScanResult result = (BarDecoderScanResult) p; // with getBarcodeType you can obtain barcode type enum that tells you the type of decoded barcode BarcodeType type = result.getBarcodeType(); // as with PDF417, getStringData will return the string contents of barcode String barcodeData = result.getStringData(); if(checkIfDataIsUrlAndCreateIntent(barcodeData)) { return; } else { sb.append(type.name()); sb.append(" string data:\n"); sb.append(barcodeData); sb.append("\n\n\n");= }*/ } else if (p instanceof ZXingScanResult) { // check if scan result is result of ZXing recognizer /* ZXingScanResult result= (ZXingScanResult) p; // with getBarcodeType you can obtain barcode type enum that tells you the type of decoded barcode BarcodeType type = result.getBarcodeType(); // as with PDF417, getStringData will return the string contents of barcode String barcodeData = result.getStringData(); if(checkIfDataIsUrlAndCreateIntent(barcodeData)) { return; } else { sb.append(type.name()); sb.append(" string data:\n"); sb.append(barcodeData); sb.append("\n\n\n"); }*/ } else if (p instanceof USDLScanResult) { // check if scan result is result of US Driver's Licence recognizer USDLScanResult result = (USDLScanResult) p; // USDLScanResult can contain lots of information extracted from driver's licence // you can obtain information using the getField method with keys defined in // USDLScanResult class String name = result.getField(USDLScanResult.kCustomerFullName); sb.append(result.getTitle()); sb.append("\n\n"); sb.append(result.toString()); } } } }
From source file:eu.codeplumbers.cosi.services.CosiContactService.java
/** * Make remote request to get all calls stored in Cozy *//* ww w. j a va2 s .c om*/ public void getRemoteContacts() { URL urlO = null; try { urlO = new URL(designUrl); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { if (jsonArray.length() == 0) { EventBus.getDefault() .post(new ContactSyncEvent(SYNC_MESSAGE, "Your Cozy has no contacts stored.")); Contact.setAllUnsynced(); } else { for (int i = 0; i < jsonArray.length(); i++) { Log.d("Contact", i + ""); EventBus.getDefault().post(new ContactSyncEvent(SYNC_MESSAGE, "Reading contacts on Cozy " + (i + 1) + "/" + jsonArray.length() + "...")); try { JSONObject contactJson = jsonArray.getJSONObject(i).getJSONObject("value"); Contact contact = Contact.getByRemoteId(contactJson.get("_id").toString()); if (contact == null) { contact = Contact.getByName(contactJson.getString("n")); if (contact == null) { contact = new Contact(contactJson); } else { if (contactJson.has("n")) contact.setN(contactJson.getString("n")); else contact.setN(""); if (contactJson.has("fn")) contact.setFn(contactJson.getString("fn")); else contact.setFn(""); if (contactJson.has("revision")) { contact.setRevision(contactJson.getString("revision")); } else { contact.setRevision(DateUtils.formatDate(new Date().getTime())); } if (contactJson.has("tags") && !contactJson.getString("tags").equalsIgnoreCase("")) { contact.setTags(contactJson.getJSONArray("tags").toString()); } else { contact.setTags(new JSONArray().toString()); } contact.setPhotoBase64(""); contact.setAnniversary(""); if (contactJson.has("deviceId")) { contact.setDeviceId(contactJson.getString("deviceId")); } if (contactJson.has("systemId")) { contact.setSystemId(contactJson.getString("systemId")); } contact.setRemoteId(contactJson.getString("_id")); if (contactJson.has("_attachments")) { JSONObject attachment = contactJson.getJSONObject("_attachments"); contact.setAttachments(attachment.toString()); if (attachment.has("picture")) { JSONObject picture = attachment.getJSONObject("picture"); String attachmentName = new String( Base64.decode(picture.getString("digest").replace("md5-", ""), Base64.DEFAULT)); Log.d("Contact", attachmentName); } } contact.save(); if (contactJson.has("datapoints")) { JSONArray datapoints = contactJson.getJSONArray("datapoints"); for (int j = 0; j < datapoints.length(); j++) { JSONObject datapoint = datapoints.getJSONObject(j); String value = datapoint.getString("value"); ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact, value); if (contactDataPoint == null && !value.isEmpty()) { contactDataPoint = new ContactDataPoint(); contactDataPoint.setPref(false); contactDataPoint.setType(datapoint.getString("type")); contactDataPoint.setValue(value); contactDataPoint.setName(datapoint.getString("name")); contactDataPoint.setContact(contact); contactDataPoint.save(); } } } } } else { if (contactJson.has("n")) contact.setN(contactJson.getString("n")); else contact.setN(""); if (contactJson.has("fn")) contact.setFn(contactJson.getString("fn")); else contact.setFn(""); if (contactJson.has("revision")) { contact.setRevision(contactJson.getString("revision")); } else { contact.setRevision(DateUtils.formatDate(new Date().getTime())); } if (contactJson.has("tags") && !contactJson.getString("tags").equalsIgnoreCase("")) { contact.setTags(contactJson.getJSONArray("tags").toString()); } else { contact.setTags(new JSONArray().toString()); } contact.setPhotoBase64(""); contact.setAnniversary(""); if (contactJson.has("deviceId")) { contact.setDeviceId(contactJson.getString("deviceId")); } if (contactJson.has("systemId")) { contact.setSystemId(contactJson.getString("systemId")); } contact.setRemoteId(contactJson.getString("_id")); if (contactJson.has("_attachments")) { JSONObject attachment = contactJson.getJSONObject("_attachments"); contact.setAttachments(attachment.toString()); if (attachment.has("picture")) { JSONObject picture = attachment.getJSONObject("picture"); String attachmentName = new String(Base64.decode( picture.getString("digest").replace("md5-", ""), Base64.DEFAULT)); Log.d("Contact", attachmentName); } } contact.save(); if (contactJson.has("datapoints")) { JSONArray datapoints = contactJson.getJSONArray("datapoints"); for (int j = 0; j < datapoints.length(); j++) { JSONObject datapoint = datapoints.getJSONObject(j); String value = datapoint.getString("value"); ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact, value); if (contactDataPoint == null && !value.isEmpty()) { contactDataPoint = new ContactDataPoint(); contactDataPoint.setPref(false); contactDataPoint.setType(datapoint.getString("type")); contactDataPoint.setValue(value); contactDataPoint.setName(datapoint.getString("name")); contactDataPoint.setContact(contact); contactDataPoint.save(); } } } } contact.save(); allContacts.add(contact); } catch (JSONException e) { EventBus.getDefault() .post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } } } } else { errorMessage = new JSONObject(result).getString("error"); EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, errorMessage)); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } }
From source file:com.example.SmartBoard.MQTTHandler.java
public static Bitmap stringToBitmap(String encodedBitmap) { byte[] bitmapBytesOptImg = Base64.decode(encodedBitmap, Base64.DEFAULT); return BitmapFactory.decodeByteArray(bitmapBytesOptImg, 0, bitmapBytesOptImg.length); }
From source file:ru.gkpromtech.exhibition.db.Table.java
private ContentValues jsonToRow(ObjectNode object) throws IllegalAccessException, ParseException { ContentValues values = new ContentValues(); for (int i = 0; i < mFields.length; ++i) { String fieldName = mFields[i].getName(); JsonNode field = object.get(fieldName); if (field == null) continue; if (field.isNull()) { values.putNull(mColumns[i]); continue; }/*ww w . j ava 2 s .co m*/ switch (mType[i]) { case INTEGER: values.put(mColumns[i], field.asInt()); break; case SHORT: values.put(mColumns[i], (short) field.asInt()); break; case LONG: values.put(mColumns[i], field.asLong()); break; case FLOAT: values.put(mColumns[i], (float) field.asDouble()); break; case DOUBLE: values.put(mColumns[i], field.asDouble()); break; case STRING: values.put(mColumns[i], field.asText()); break; case BYTE_ARRAY: values.put(mColumns[i], Base64.decode(field.asText(), Base64.DEFAULT)); break; case DATE: values.put(mColumns[i], mDateFormat.parse(field.asText()).getTime()); break; case BOOLEAN: values.put(mColumns[i], field.asBoolean() ? 1 : 0); break; } } return values; }
From source file:be.blinkt.openvpn.activities.MainActivity.java
public void onResume() { super.onResume(); try {//from w w w. j a v a 2 s . com AppConfiguration appConf = getManagedConfiguration(); if (appConf != null) { String commonConfStr = new String(Base64.decode(appConf.getCommonConfiguration(), Base64.DEFAULT)); String userConfStr = new String(Base64.decode(appConf.getUserConfiguration(), Base64.DEFAULT)); Reader reader = new StringReader((commonConfStr + userConfStr)); ProfileManager pm = ProfileManager.getInstance(this); if (pm.getProfileByName("afw_vpn") == null) { ConfigParser confParser = new ConfigParser(); confParser.parseConfig(reader); VpnProfile profile = confParser.convertProfile(); //profile.mUsername = "jan"; //profile.mPassword = "jan"; profile.mName = "afw_vpn"; pm.addProfile(profile); profile.mAllowedAppsVpnAreDisallowed = false; String allowedApps = appConf.getAllowedApps(); String[] allowedAppsArray = allowedApps.split(","); for (String allowedApp : allowedAppsArray) profile.mAllowedAppsVpn.add(allowedApp); profile.writeConfigFile(this); } else { System.out.println("Profile already exists, not creating new"); } } else { System.out.println("EMPTY CONF"); } } catch (Exception e) { System.out.println("Exception managed profile: " + e); } }
From source file:se.leap.bitmaskclient.ProviderAPI.java
private boolean validCertificate(String cert_string) { boolean result = false; if (!ConfigHelper.checkErroneousDownload(cert_string)) { X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(cert_string); try {/*w w w.j a v a2s. c om*/ if (certificate != null) { JSONObject provider_json = new JSONObject(preferences.getString(Provider.KEY, "")); String fingerprint = provider_json.getString(Provider.CA_CERT_FINGERPRINT); String encoding = fingerprint.split(":")[0]; String expected_fingerprint = fingerprint.split(":")[1]; String real_fingerprint = base64toHex(Base64.encodeToString( MessageDigest.getInstance(encoding).digest(certificate.getEncoded()), Base64.DEFAULT)); result = real_fingerprint.trim().equalsIgnoreCase(expected_fingerprint.trim()); } else result = false; } catch (JSONException e) { result = false; } catch (NoSuchAlgorithmException e) { result = false; } catch (CertificateEncodingException e) { result = false; } } return result; }
From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java
private boolean saveFile(File file, String fileContent) { try {/*from ww w . ja v a 2 s. c om*/ FileOutputStream fOut = new FileOutputStream(file); byte[] decodedString = Base64.decode(fileContent, Base64.DEFAULT); fOut.write(decodedString); fOut.close(); return true; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; }