List of usage examples for android.util Base64 encode
public static byte[] encode(byte[] input, int flags)
From source file:es.javocsoft.android.lib.toucan.client.ToucanClient.java
/** * Enables a registered device./*from w ww. jav a 2 s . com*/ * * @param callback A callback to run when operation finishes. */ public void doEnableRegisteredDevice(ResponseCallback callback) { try { String appHashSignature = generateSHA1(appPublicKey + apiToken); String urlParams = "dUId=" + toucanClient.deviceUniqueId + "&appPubKey=" + appPublicKey + "&appHashSignature=" + appHashSignature; String encodedUrlParams = new String(Base64.encode(urlParams.getBytes(), 0), "UTF-8"); String urlEncodedUrlParams = URLEncoder.encode(encodedUrlParams, "UTF-8"); String finalUrl = API_ENDPOINT_ENABLE_REGISTERED_DEVICE + "=" + urlEncodedUrlParams; if (ToolBox.net_isNetworkAvailable(context)) { new ToucanGetWorker(context, apiToken, finalUrl, API_OPERATION_DEVICE_ENABLE, callback).start(); } else { cacheOperationRequest( new ToucanGetWorker(context, apiToken, finalUrl, API_OPERATION_DEVICE_ENABLE, callback), true); } } catch (Exception e) { Log.e(LOG_TAG, "Error doing operation " + API_OPERATION_DEVICE_ENABLE.toUpperCase() + " to Toucan API (" + e.getMessage() + ")", e); } }
From source file:piuk.blockchain.android.MyWallet.java
public static String encrypt(String text, String password, final int PBKDF2Iterations) throws Exception { if (password == null) throw new Exception("You must provide an ecryption password"); // Use secure random to generate a 16 byte iv SecureRandom random = new SecureRandom(); byte iv[] = new byte[AESBlockSize * 4]; random.nextBytes(iv);// w w w .ja va 2 s. com byte[] textbytes = text.getBytes("UTF-8"); PBEParametersGenerator generator = new PKCS5S2ParametersGenerator(); generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password.toCharArray()), iv, PBKDF2Iterations); KeyParameter keyParam = (KeyParameter) generator.generateDerivedParameters(256); CipherParameters params = new ParametersWithIV(keyParam, iv); // setup AES cipher in CBC mode with PKCS7 padding BlockCipherPadding padding = new ISO10126d2Padding(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding); cipher.reset(); cipher.init(true, params); byte[] outBuf = cipherData(cipher, textbytes); // Append to IV to the output byte[] ivAppended = ArrayUtils.addAll(iv, outBuf); return new String(Base64.encode(ivAppended, Base64.NO_WRAP), "UTF-8"); }
From source file:ca.psiphon.PsiphonTunnel.java
private String setupTrustedCertificates(Context context) throws Exception { // Copy the Android system CA store to a local, private cert bundle file. ///* ww w . j a v a2 s .c om*/ // This results in a file that can be passed to SSL_CTX_load_verify_locations // for use with OpenSSL modes in tunnel-core. // https://www.openssl.org/docs/manmaster/ssl/SSL_CTX_load_verify_locations.html // // TODO: to use the path mode of load_verify_locations would require emulating // the filename scheme used by c_rehash: // https://www.openssl.org/docs/manmaster/apps/c_rehash.html // http://stackoverflow.com/questions/19237167/the-new-subject-hash-openssl-algorithm-differs File directory = context.getDir("PsiphonCAStore", Context.MODE_PRIVATE); final String errorMessage = "copy AndroidCAStore failed"; try { File file = new File(directory, "certs.dat"); // Pave a fresh copy on every run, which ensures we're not using old certs. // Note: assumes KeyStore doesn't return revoked certs. // // TODO: this takes under 1 second, but should we avoid repaving every time? file.delete(); PrintStream output = null; try { output = new PrintStream(new FileOutputStream(file)); KeyStore keyStore; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { keyStore = KeyStore.getInstance("AndroidCAStore"); keyStore.load(null, null); } else { keyStore = KeyStore.getInstance("BKS"); FileInputStream inputStream = new FileInputStream("/etc/security/cacerts.bks"); try { keyStore.load(inputStream, "changeit".toCharArray()); } finally { if (inputStream != null) { inputStream.close(); } } } Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias); output.println("-----BEGIN CERTIFICATE-----"); String pemCert = new String(Base64.encode(cert.getEncoded(), Base64.NO_WRAP), "UTF-8"); // OpenSSL appears to reject the default linebreaking done by Base64.encode, // so we manually linebreak every 64 characters for (int i = 0; i < pemCert.length(); i += 64) { output.println(pemCert.substring(i, Math.min(i + 64, pemCert.length()))); } output.println("-----END CERTIFICATE-----"); } mHostService.onDiagnosticMessage("prepared PsiphonCAStore"); return file.getAbsolutePath(); } finally { if (output != null) { output.close(); } } } catch (KeyStoreException e) { throw new Exception(errorMessage, e); } catch (NoSuchAlgorithmException e) { throw new Exception(errorMessage, e); } catch (CertificateException e) { throw new Exception(errorMessage, e); } catch (IOException e) { throw new Exception(errorMessage, e); } }
From source file:net.inbox.InboxGPG.java
/** * PGP/MIME serialization.//from w w w . j ava2 s . c o m **/ private String mime_serialization() { String bounds = Utils.boundary(); String msg_mime = "Content-type: multipart/mixed;\n boundary=" + "\"" + bounds + "\"\n"; // Message textual contents msg_mime += "\n--" + bounds + "\n"; msg_mime += "Content-Type: text/plain; charset=\"utf-8\"\n"; msg_mime += "Content-Transfer-Encoding: 8bit\n\n"; if (msg_contents != null) msg_mime += msg_contents + "\n--" + bounds; if (attachment_paths == null) { msg_mime += "--\n"; } else { // Message attachments for (int i = 0; i < attachment_paths.size(); ++i) { File ff = new File(attachment_paths.get(i)); msg_mime += "\n--" + bounds + "\n"; if (Utils.all_ascii(ff.getName())) { msg_mime += "Content-Type: application/octet-stream; name=\"" + ff.getName() + "\"\n"; msg_mime += "Content-Transfer-Encoding: base64\n"; msg_mime += "Content-Disposition: attachment; filename=\"" + ff.getName() + "\"\n"; } else { msg_mime += "Content-Type: application/octet-stream; name*=\"" + Utils.to_base64_utf8(ff.getName()) + "\"\n"; msg_mime += "Content-Transfer-Encoding: base64\n"; String new_name = Utils.content_disposition_name(true, ff.getName()); msg_mime += "Content-Disposition: attachment; filename*=" + new_name + "\n"; } msg_mime += "\n"; ByteArrayOutputStream b_stream = new ByteArrayOutputStream(); try { InputStream in_stream = new FileInputStream(ff); byte[] bfr = new byte[(int) ff.length()]; if ((int) ff.length() > 0) { int t; while ((t = in_stream.read(bfr)) != -1) { b_stream.write(bfr, 0, t); } } } catch (IOException e) { Pager.log += getString(R.string.ex_field) + e.getMessage() + "\n\n"; Dialogs.toaster(true, e.getMessage(), this); } msg_mime += new String(Base64.encode(b_stream.toByteArray(), Base64.DEFAULT)); if (msg_mime.charAt(msg_mime.length() - 1) == '\n') { msg_mime = msg_mime.substring(0, msg_mime.length() - 1); } } msg_mime += "\n--" + bounds + "--\n"; } // Outer boundary shell bounds = Utils.boundary(); msg_mime = "Content-type: multipart/mixed;\n boundary=" + "\"" + bounds + "\"\n" + "\n--" + bounds + "\n" + msg_mime; msg_mime += "\n--" + bounds + "--\n"; return msg_mime; }
From source file:eu.operando.operandoapp.database.DatabaseHelper.java
public void sendSettingsToServer(final String imei) { new Thread(new Runnable() { @Override/*from w w w . java 2 s . co m*/ public void run() { String xml_settings = exportAllPermissionsPerDomain(); if (xml_settings != null) { try { String urlParameters = "userxml=" + xml_settings + "&userID=" + Base64.encode(DigestUtils.sha1(imei), Base64.DEFAULT); byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); URL url = new URL(serverUrl + "/prefs"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) { wr.write(postData); } int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { //Do something on HTTP_OK ????? } else { throw new Exception(); } Log.d("SENT", Integer.toString(responseCode)); } catch (Exception e) { //create a file as database to resend later Writer writer = null; try { File file = new File(MainContext.INSTANCE.getContext().getFilesDir(), "resend.inf"); if (!file.exists()) { writer = new BufferedWriter(new FileWriter(file)); writer.write("1"); //currently putting 1 for "true" to resend } } catch (Exception ex) { ex.getMessage(); } finally { try { writer.close(); } catch (Exception ex) { ex.getMessage(); } } } } } }).start(); }
From source file:org.apache.cordova.core.CameraLauncher.java
/** * Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript. * * @param bitmap//from w w w. j a v a2 s . co m */ public void processPicture(Bitmap bitmap) { ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream(); try { if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) { byte[] code = jpeg_data.toByteArray(); byte[] output = Base64.encode(code, Base64.DEFAULT); String js_out = new String(output); this.callbackContext.success(js_out); js_out = null; output = null; code = null; } } catch (Exception e) { this.failPicture("Error compressing image."); } jpeg_data = null; }
From source file:com.raceyourself.android.samsung.ProviderService.java
private void authorize() { UserDetail me = Helper.getUser();// ww w . j av a2 s. c om if (me != null && me.getApiAccessToken() != null) return; AccountManager mAccountManager = AccountManager.get(this); List<Account> accounts = new ArrayList<Account>(); accounts.addAll(Arrays.asList(mAccountManager.getAccountsByType("com.google"))); accounts.addAll(Arrays.asList(mAccountManager.getAccountsByType("com.googlemail"))); String email = null; for (Account account : accounts) { if (account.name != null && account.name.contains("@")) { email = account.name; break; } } // Potential fault: Can there be multiple accounts? Do we need to sort or provide a selector? // hash email so we don't send user's identity to server // can't guarantee uniqueness but want very low probability of collisions // using SHA-256 means we'd expect a collision on approx. our 1-millionth user // TODO: make this more unique before Samsung sell 1m Gear IIs. MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(email.getBytes()); String hash = new String(messageDigest.digest()); hash = new String(Base64.encode(hash.getBytes(), Base64.DEFAULT)).replace("@", "_").replace("\n", "_"); //base64 encode and substitute @ symbols hash += "@hashed.raceyourself.com"; // make it look like an email so it passes server validation Helper.login(hash, SERVER_TOKEN); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "Implementation of SHA-256 algorithm not found. Authorisation failed. Exiting."); throw new RuntimeException(); } }
From source file:com.connectsdk.service.WebOSTVService.java
private void sendToast(JSONObject payload, ResponseListener<Object> listener) { if (!payload.has("iconData")) { Context context = DiscoveryManager.getInstance().getContext(); try {// w ww . ja va 2s. c o m Drawable drawable = context.getPackageManager().getApplicationIcon(context.getPackageName()); if (drawable != null) { BitmapDrawable bitDw = ((BitmapDrawable) drawable); Bitmap bitmap = bitDw.getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] bitmapByte = stream.toByteArray(); bitmapByte = Base64.encode(bitmapByte, Base64.NO_WRAP); String bitmapData = new String(bitmapByte); payload.put("iconData", bitmapData); payload.put("iconExtension", "png"); } } catch (NameNotFoundException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } String uri = "palm://system.notifications/createToast"; ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>(this, uri, payload, true, listener); request.send(); }
From source file:com.pheromone.plugins.FileUtils.java
/** * Read content of text file and return as base64 encoded data url. * * @param filename The name of the file. * @return Contents of file = data:<media type>;base64,<data> * @throws FileNotFoundException, IOException *//*from www.j a va2 s. c om*/ public String readAsDataURL(String filename) throws FileNotFoundException, IOException { byte[] bytes = new byte[1000]; BufferedInputStream bis = new BufferedInputStream(getPathFromUri(filename), 1024); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int numRead = 0; while ((numRead = bis.read(bytes, 0, 1000)) >= 0) { bos.write(bytes, 0, numRead); } // Determine content type from file name String contentType = null; if (filename.startsWith("content:")) { Uri fileUri = Uri.parse(filename); contentType = this.ctx.getContentResolver().getType(fileUri); } else { contentType = getMimeType(filename); } byte[] base64 = Base64.encode(bos.toByteArray(), Base64.DEFAULT); String data = "data:" + contentType + ";base64," + new String(base64); return data; }
From source file:org.apache.cordova.FileUtils.java
/** * Read the contents of a file.// www . java2 s . co m * This is done in a background thread; the result is sent to the callback. * * @param filename The name of the file. * @param start Start position in the file. * @param end End position to stop at (exclusive). * @param callbackContext The context through which to send the result. * @param encoding The encoding to return contents as. Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets) * @param resultType The desired type of data to send to the callback. * @return Contents of file. */ public void readFileAs(final String filename, final int start, final int end, final CallbackContext callbackContext, final String encoding, final int resultType) { this.cordova.getThreadPool().execute(new Runnable() { public void run() { try { byte[] bytes = readAsBinaryHelper(filename, start, end); PluginResult result; switch (resultType) { case PluginResult.MESSAGE_TYPE_STRING: result = new PluginResult(PluginResult.Status.OK, new String(bytes, encoding)); break; case PluginResult.MESSAGE_TYPE_ARRAYBUFFER: result = new PluginResult(PluginResult.Status.OK, bytes); break; case PluginResult.MESSAGE_TYPE_BINARYSTRING: result = new PluginResult(PluginResult.Status.OK, bytes, true); break; default: // Base64. String contentType = FileHelper.getMimeType(filename, cordova); byte[] base64 = Base64.encode(bytes, Base64.NO_WRAP); String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII"); result = new PluginResult(PluginResult.Status.OK, s); } callbackContext.sendPluginResult(result); } catch (FileNotFoundException e) { callbackContext .sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR)); } catch (IOException e) { Log.d(LOG_TAG, e.getLocalizedMessage()); callbackContext .sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR)); } } }); }