Java Examples for android.util.Base64
The following java examples will help you to understand the usage of android.util.Base64. These source code samples are taken from different open source projects.
Example 1
| Project: D3Xmpp-master File: DES.java View source code |
public static String encryptDES(String encryptString, String encryptKey) throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
return android.util.Base64.encodeToString(encryptedData, android.util.Base64.NO_WRAP);
}Example 2
| Project: ctSESAM-android-master File: CrypterTest.java View source code |
public void testEncrypt() {
String messageString = "Important information with quite some length. " + "This message is as long as this because otherwise only one cipher block would " + "be encrypted. This long message insures that more than one block is needed.";
byte[] password;
byte[] message;
try {
password = "secret".getBytes("UTF-8");
message = messageString.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.d("Key generation error", "UTF-8 is not supported.");
password = "secret".getBytes();
message = messageString.getBytes();
}
Crypter crypter = new Crypter(Crypter.createKey(password, new byte[] {}));
byte[] ciphertext = crypter.encrypt(message);
assertEquals("5XJcX8Ju/KY9P17gSZWbvsMCxazUyWVS3SmGpwOqOJkBQU1Cyu0n9RkxbNJ1CJSoF8BPTH5d5xy6\n" + "IGIUb3kN6EdWBppTk/PAHbgQX/tBiW2Uwi7DMEg6GGebqr+Dj94Ur9JnpiCRUTZfDgUyTpy5GQQ3\n" + "TQUlDTqpvs+5n6cpdombXBnpcfl2ddQhawJLOFpGtED0h4LZtW0nEc7mvvSSRosXHohRNScrUCg0\n" + "Jm5/J29HVXQmFEyNmHYt2Wckk1gCP+Mt34klaNnuk3yFDLtQmg==\n", Base64.encodeToString(ciphertext, Base64.DEFAULT));
}Example 3
| Project: java-cloudant-master File: Base64OutputStreamFactory.java View source code |
public static OutputStream get(OutputStream os) {
try {
if (runningOnAndroid) {
Class c = Class.forName("android.util.Base64OutputStream");
Constructor ctor = c.getDeclaredConstructor(OutputStream.class, int.class);
// .com/reference/android/util/Base64.html#NO_WRAP
return (OutputStream) ctor.newInstance(os, 2);
} else {
Class c = Class.forName("org.apache.commons.codec.binary.Base64OutputStream");
Constructor ctor = c.getDeclaredConstructor(OutputStream.class, boolean.class, int.class, byte[].class);
return (OutputStream) ctor.newInstance(os, true, 0, null);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 4
| Project: sync-android-master File: Base64OutputStreamFactory.java View source code |
public static OutputStream get(OutputStream os) {
try {
if (Misc.isRunningOnAndroid()) {
Class c = Class.forName("android.util.Base64OutputStream");
Constructor ctor = c.getDeclaredConstructor(OutputStream.class, int.class);
// 2 = android.util.BASE64.NO_WRAP http://developer.android.com/reference/android/util/Base64.html#NO_WRAP
return (OutputStream) ctor.newInstance(os, 2);
} else {
Class c = Class.forName("org.apache.commons.codec.binary.Base64OutputStream");
Constructor ctor = c.getDeclaredConstructor(OutputStream.class, boolean.class, int.class, byte[].class);
return (OutputStream) ctor.newInstance(os, true, 0, null);
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
logger.log(Level.SEVERE, "Failed to load Base64OutputStream implementation", e);
return null;
}
}Example 5
| Project: TurtlePlayer-master File: ObjectKey.java View source code |
@Override
public String marshall(T object) {
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutput;
try {
objectOutput = new ObjectOutputStream(arrayOutputStream);
objectOutput.writeObject(object);
byte[] data = arrayOutputStream.toByteArray();
objectOutput.close();
arrayOutputStream.close();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(out, Base64.DEFAULT);
b64.write(data);
b64.close();
out.close();
return new String(out.toByteArray());
} catch (IOException e) {
Log.e(Preferences.TAG, "error saving key " + getKey() + " to: " + object.toString());
return "";
}
}Example 6
| Project: bike-friend-master File: PingtungUrlProvider.java View source code |
@Override
public URL getUrl() {
String dateStr = "PBike@Krtc" + dateFormat.format(new Date());
String base64Str = Base64.encodeToString(Utils.md5(dateStr).getBytes(), Base64.URL_SAFE);
String url = "http://pbike.pthg.gov.tw/BikeApp/BikeStationHandler.ashx?Key=" + base64Str;
//Log.i("bikefriend", base64Str);
return Utils.toUrl(url);
}Example 7
| Project: gojira-master File: BasicAuth.java View source code |
public static Header getBasicAuthHeader() {
// Add basic auth header if we have stored credentials
if (Hawk.contains(Preferences.KEY_USERNAME) && Hawk.contains(Preferences.KEY_PASSWORD)) {
// Get credentials from secure storage
String username = Hawk.get(Preferences.KEY_USERNAME);
String password = Hawk.get(Preferences.KEY_PASSWORD);
// Create basic auth header
String credentials = username + ":" + password;
String header = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
// Add auth header in the request
return new Header(AUTHORIZATION_HEADER, header);
}
return null;
}Example 8
| Project: Ummo-master File: HashKey.java View source code |
public void printHashKey() {
try {
PackageInfo info = getPackageManager().getPackageInfo("com.example.barnes.ummo", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.e("UMMOOOOOOOO KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}Example 9
| Project: YourAppIdea-master File: SecurityUtils.java View source code |
public static String logHashKey(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
return Base64.encodeToString(md.digest(), Base64.DEFAULT);
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(MCXApplication.LOG_TAG, "logHashKey error", e);
} catch (NoSuchAlgorithmException e) {
Log.e(MCXApplication.LOG_TAG, "logHashKey error", e);
}
return null;
}Example 10
| Project: zulip-android-master File: ZulipInterceptor.java View source code |
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder requestBuilder = chain.request().newBuilder();
requestBuilder.addHeader("client", "Android");
requestBuilder.addHeader("User-Agent", app.getUserAgent());
if (app.getApiKey() != null) {
String authstr = app.getEmail() + ":" + app.getApiKey();
requestBuilder.addHeader("Authorization", "Basic " + Base64.encodeToString(authstr.getBytes(), Base64.NO_WRAP));
}
Request request = requestBuilder.build();
return chain.proceed(request);
}Example 11
| Project: android-runtime-master File: StringConversionTest.java View source code |
private String readString() throws Exception {
String str = null;
Context context = com.tns.NativeScriptApplication.getInstance();
InputStream inputStream = null;
try {
String assetName = "app/tests/image.jpg";
int fileLength = 0;
AssetFileDescriptor fd = null;
try {
fd = context.getAssets().openFd(assetName);
fileLength = (int) fd.getLength();
} finally {
if (fd != null) {
fd.close();
}
}
inputStream = context.getAssets().open(assetName, AssetManager.ACCESS_STREAMING);
byte[] data = new byte[fileLength];
inputStream.read(data);
str = android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);
// This is not correct - the raw image data is NOT UTF-8 string
// TODO: Discuss
//str = new String(data, "UTF-8");
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return str;
}Example 12
| Project: androiddevice.info-master File: OtacertsProperty.java View source code |
@Override
public Object getProperty() throws JSONException {
JSONObject result = new JSONObject();
try {
Iterator<Map.Entry<String, X509Certificate>> certs = getTrustedCerts(new File("/system/etc/security/otacerts.zip")).entrySet().iterator();
while (certs.hasNext()) {
Map.Entry<String, X509Certificate> cert = certs.next();
result.put(cert.getKey(), encodeToString(cert.getValue().getEncoded(), Base64.DEFAULT));
}
} catch (IOException e) {
return JSONObject.NULL;
} catch (GeneralSecurityException e) {
return JSONObject.NULL;
}
return result;
}Example 13
| Project: android-security-master File: SignatureUtils.java View source code |
public static boolean checkSignature(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : packageInfo.signatures) {
MessageDigest sha = MessageDigest.getInstance("SHA");
sha.update(signature.toByteArray());
final String currentSignature = Base64.encodeToString(sha.digest(), Base64.DEFAULT);
if (SIGNATURE.equals(currentSignature)) {
return true;
}
}
} catch (Exception e) {
Log.e(TAG, "Failed to check signature", e);
}
return false;
}Example 14
| Project: AndroidGeek-master File: AuthHttpClient.java View source code |
@Override
public Response intercept(Chain chain) throws IOException {
// https://developer.github.com/v3/auth/#basic-authentication
// https://developer.github.com/v3/oauth/#non-web-application-flow
String userCredentials = userName + ":" + password;
String basicAuth = "Basic " + new String(Base64.encode(userCredentials.getBytes(), Base64.DEFAULT));
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder().header("Authorization", basicAuth.trim());
Request request = requestBuilder.build();
return chain.proceed(request);
}Example 15
| Project: appaloosa-android-tools-master File: BlacklistUrlUtils.java View source code |
private static String buildParams() {
String imei = DeviceUtils.getDeviceID();
String encodedImei = Base64.encodeToString(imei.getBytes(), Base64.DEFAULT).trim();
String locale = Appaloosa.getApplicationContext().getResources().getConfiguration().locale.getLanguage();
String packageName = SysUtils.getApplicationPackage();
int versionCode = SysUtils.getApplicationVersionCode();
return String.format(CHECK_BLACKLIST_URL, Appaloosa.getStoreId(), Appaloosa.getStoreToken(), packageName, encodedImei, versionCode, locale);
}Example 16
| Project: couchbase-lite-android-master File: Base64Test.java View source code |
public void testDecode() throws IOException {
String input1 = "eyJwdWJsaWMta2V5Ijp7ImFsZ29yaXRobSI6IkRTIiwieSI6ImNhNWJiYTYzZmI4MDQ2OGE0MjFjZjgxYTIzN2VlMDcwYTJlOTM4NTY0ODhiYTYzNTM0ZTU4NzJjZjllMGUwMDk0ZWQ2NDBlOGNhYmEwMjNkYjc5ODU3YjkxMzBlZGNmZGZiNmJiNTUwMWNjNTk3MTI1Y2NiMWQ1ZWQzOTVjZTMyNThlYjEwN2FjZTM1ODRiOWIwN2I4MWU5MDQ4NzhhYzBhMjFlOWZkYmRjYzNhNzNjOTg3MDAwYjk4YWUwMmZmMDQ4ODFiZDNiOTBmNzllYzVlNDU1YzliZjM3NzFkYjEzMTcxYjNkMTA2ZjM1ZDQyZmZmZjQ2ZWZiZDcwNjgyNWQiLCJwIjoiZmY2MDA0ODNkYjZhYmZjNWI0NWVhYjc4NTk0YjM1MzNkNTUwZDlmMWJmMmE5OTJhN2E4ZGFhNmRjMzRmODA0NWFkNGU2ZTBjNDI5ZDMzNGVlZWFhZWZkN2UyM2Q0ODEwYmUwMGU0Y2MxNDkyY2JhMzI1YmE4MWZmMmQ1YTViMzA1YThkMTdlYjNiZjRhMDZhMzQ5ZDM5MmUwMGQzMjk3NDRhNTE3OTM4MDM0NGU4MmExOGM0NzkzMzQzOGY4OTFlMjJhZWVmODEyZDY5YzhmNzVlMzI2Y2I3MGVhMDAwYzNmNzc2ZGZkYmQ2MDQ2MzhjMmVmNzE3ZmMyNmQwMmUxNyIsInEiOiJlMjFlMDRmOTExZDFlZDc5OTEwMDhlY2FhYjNiZjc3NTk4NDMwOWMzIiwiZyI6ImM1MmE0YTBmZjNiN2U2MWZkZjE4NjdjZTg0MTM4MzY5YTYxNTRmNGFmYTkyOTY2ZTNjODI3ZTI1Y2ZhNmNmNTA4YjkwZTVkZTQxOWUxMzM3ZTA3YTJlOWUyYTNjZDVkZWE3MDRkMTc1ZjhlYmY2YWYzOTdkNjllMTEwYjk2YWZiMTdjN2EwMzI1OTMyOWU0ODI5YjBkMDNiYmM3ODk2YjE1YjRhZGU1M2UxMzA4NThjYzM0ZDk2MjY5YWE4OTA0MWY0MDkxMzZjNzI0MmEzODg5NWM5ZDViY2NhZDRmMzg5YWYxZDdhNGJkMTM5OGJkMDcyZGZmYTg5NjIzMzM5N2EifSwicHJpbmNpcGFsIjp7ImVtYWlsIjoiamVuc0Btb29zZXlhcmQuY29tIn0sImlhdCI6MTM1ODI5NjIzNzU3NywiZXhwIjoxMzU4MzgyNjM3NTc3LCJpc3MiOiJsb2dpbi5wZXJzb25hLm9yZyJ9";
String expected1 = "{\"public-key\":{\"algorithm\":\"DS\",\"y\":\"ca5bba63fb80468a421cf81a237ee070a2e93856488ba63534e5872cf9e0e0094ed640e8caba023db79857b9130edcfdfb6bb5501cc597125ccb1d5ed395ce3258eb107ace3584b9b07b81e904878ac0a21e9fdbdcc3a73c987000b98ae02ff04881bd3b90f79ec5e455c9bf3771db13171b3d106f35d42ffff46efbd706825d\",\"p\":\"ff600483db6abfc5b45eab78594b3533d550d9f1bf2a992a7a8daa6dc34f8045ad4e6e0c429d334eeeaaefd7e23d4810be00e4cc1492cba325ba81ff2d5a5b305a8d17eb3bf4a06a349d392e00d329744a5179380344e82a18c47933438f891e22aeef812d69c8f75e326cb70ea000c3f776dfdbd604638c2ef717fc26d02e17\",\"q\":\"e21e04f911d1ed7991008ecaab3bf775984309c3\",\"g\":\"c52a4a0ff3b7e61fdf1867ce84138369a6154f4afa92966e3c827e25cfa6cf508b90e5de419e1337e07a2e9e2a3cd5dea704d175f8ebf6af397d69e110b96afb17c7a03259329e4829b0d03bbc7896b15b4ade53e130858cc34d96269aa89041f409136c7242a38895c9d5bccad4f389af1d7a4bd1398bd072dffa896233397a\"},\"principal\":{\"email\":\"jens@mooseyard.com\"},\"iat\":1358296237577,\"exp\":1358382637577,\"iss\":\"login.persona.org\"}";
String output1a = new String(android.util.Base64.decode(input1, android.util.Base64.DEFAULT));
Assert.assertEquals(expected1, output1a);
String output1b = new String(com.couchbase.lite.util.Base64.decode(input1, com.couchbase.lite.util.Base64.DEFAULT));
Assert.assertEquals(expected1, output1b);
String input2 = "eyJleHAiOjEzNTgyOTY0Mzg0OTUsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NDk4NC8ifQ";
String expected2 = "{\"exp\":1358296438495,\"aud\":\"http://localhost:4984/\"}";
String output2a = new String(android.util.Base64.decode(input2, android.util.Base64.DEFAULT));
Assert.assertEquals(expected2, output2a);
String output2b = new String(com.couchbase.lite.util.Base64.decode(input2, com.couchbase.lite.util.Base64.DEFAULT));
Assert.assertEquals(expected2, output2b);
}Example 17
| Project: Couchbase-master File: Base64Test.java View source code |
public void testDecode() throws IOException {
String input1 = "eyJwdWJsaWMta2V5Ijp7ImFsZ29yaXRobSI6IkRTIiwieSI6ImNhNWJiYTYzZmI4MDQ2OGE0MjFjZjgxYTIzN2VlMDcwYTJlOTM4NTY0ODhiYTYzNTM0ZTU4NzJjZjllMGUwMDk0ZWQ2NDBlOGNhYmEwMjNkYjc5ODU3YjkxMzBlZGNmZGZiNmJiNTUwMWNjNTk3MTI1Y2NiMWQ1ZWQzOTVjZTMyNThlYjEwN2FjZTM1ODRiOWIwN2I4MWU5MDQ4NzhhYzBhMjFlOWZkYmRjYzNhNzNjOTg3MDAwYjk4YWUwMmZmMDQ4ODFiZDNiOTBmNzllYzVlNDU1YzliZjM3NzFkYjEzMTcxYjNkMTA2ZjM1ZDQyZmZmZjQ2ZWZiZDcwNjgyNWQiLCJwIjoiZmY2MDA0ODNkYjZhYmZjNWI0NWVhYjc4NTk0YjM1MzNkNTUwZDlmMWJmMmE5OTJhN2E4ZGFhNmRjMzRmODA0NWFkNGU2ZTBjNDI5ZDMzNGVlZWFhZWZkN2UyM2Q0ODEwYmUwMGU0Y2MxNDkyY2JhMzI1YmE4MWZmMmQ1YTViMzA1YThkMTdlYjNiZjRhMDZhMzQ5ZDM5MmUwMGQzMjk3NDRhNTE3OTM4MDM0NGU4MmExOGM0NzkzMzQzOGY4OTFlMjJhZWVmODEyZDY5YzhmNzVlMzI2Y2I3MGVhMDAwYzNmNzc2ZGZkYmQ2MDQ2MzhjMmVmNzE3ZmMyNmQwMmUxNyIsInEiOiJlMjFlMDRmOTExZDFlZDc5OTEwMDhlY2FhYjNiZjc3NTk4NDMwOWMzIiwiZyI6ImM1MmE0YTBmZjNiN2U2MWZkZjE4NjdjZTg0MTM4MzY5YTYxNTRmNGFmYTkyOTY2ZTNjODI3ZTI1Y2ZhNmNmNTA4YjkwZTVkZTQxOWUxMzM3ZTA3YTJlOWUyYTNjZDVkZWE3MDRkMTc1ZjhlYmY2YWYzOTdkNjllMTEwYjk2YWZiMTdjN2EwMzI1OTMyOWU0ODI5YjBkMDNiYmM3ODk2YjE1YjRhZGU1M2UxMzA4NThjYzM0ZDk2MjY5YWE4OTA0MWY0MDkxMzZjNzI0MmEzODg5NWM5ZDViY2NhZDRmMzg5YWYxZDdhNGJkMTM5OGJkMDcyZGZmYTg5NjIzMzM5N2EifSwicHJpbmNpcGFsIjp7ImVtYWlsIjoiamVuc0Btb29zZXlhcmQuY29tIn0sImlhdCI6MTM1ODI5NjIzNzU3NywiZXhwIjoxMzU4MzgyNjM3NTc3LCJpc3MiOiJsb2dpbi5wZXJzb25hLm9yZyJ9";
String expected1 = "{\"public-key\":{\"algorithm\":\"DS\",\"y\":\"ca5bba63fb80468a421cf81a237ee070a2e93856488ba63534e5872cf9e0e0094ed640e8caba023db79857b9130edcfdfb6bb5501cc597125ccb1d5ed395ce3258eb107ace3584b9b07b81e904878ac0a21e9fdbdcc3a73c987000b98ae02ff04881bd3b90f79ec5e455c9bf3771db13171b3d106f35d42ffff46efbd706825d\",\"p\":\"ff600483db6abfc5b45eab78594b3533d550d9f1bf2a992a7a8daa6dc34f8045ad4e6e0c429d334eeeaaefd7e23d4810be00e4cc1492cba325ba81ff2d5a5b305a8d17eb3bf4a06a349d392e00d329744a5179380344e82a18c47933438f891e22aeef812d69c8f75e326cb70ea000c3f776dfdbd604638c2ef717fc26d02e17\",\"q\":\"e21e04f911d1ed7991008ecaab3bf775984309c3\",\"g\":\"c52a4a0ff3b7e61fdf1867ce84138369a6154f4afa92966e3c827e25cfa6cf508b90e5de419e1337e07a2e9e2a3cd5dea704d175f8ebf6af397d69e110b96afb17c7a03259329e4829b0d03bbc7896b15b4ade53e130858cc34d96269aa89041f409136c7242a38895c9d5bccad4f389af1d7a4bd1398bd072dffa896233397a\"},\"principal\":{\"email\":\"jens@mooseyard.com\"},\"iat\":1358296237577,\"exp\":1358382637577,\"iss\":\"login.persona.org\"}";
String output1a = new String(android.util.Base64.decode(input1, android.util.Base64.DEFAULT));
Assert.assertEquals(expected1, output1a);
String output1b = new String(com.couchbase.lite.util.Base64.decode(input1, com.couchbase.lite.util.Base64.DEFAULT));
Assert.assertEquals(expected1, output1b);
String input2 = "eyJleHAiOjEzNTgyOTY0Mzg0OTUsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NDk4NC8ifQ";
String expected2 = "{\"exp\":1358296438495,\"aud\":\"http://localhost:4984/\"}";
String output2a = new String(android.util.Base64.decode(input2, android.util.Base64.DEFAULT));
Assert.assertEquals(expected2, output2a);
String output2b = new String(com.couchbase.lite.util.Base64.decode(input2, com.couchbase.lite.util.Base64.DEFAULT));
Assert.assertEquals(expected2, output2b);
}Example 18
| Project: FaceBookExample-master File: Utils.java View source code |
public static String getSHA_key(Context ctx) {
try {
info = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
something = new String(Base64.encode(md.digest(), 0));
Log.e("Hash key", something);
System.out.println("Hash key" + something);
}
} catch (NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
return something;
}Example 19
| Project: IBM-Ready-App-for-Telecommunications-master File: StringObfuscator.java View source code |
/**
* Do the actual decoding of the string using base64 encryption
*
* @param encodedString the encoded string to be decoded
* @return the decoded string
*/
public static String decode(String encodedString) {
String decodedString = "";
if (encodedString.equals("your_encoded_twitter_key") || encodedString.equals("your_encoded_twitter_secret")) {
return decodedString;
}
byte[] data = Base64.decode(encodedString, Base64.DEFAULT);
try {
decodedString = new String(data, "UTF-8");
} catch (Exception e) {
Log.d(TAG, "DECODING STRING FAILURE");
}
return decodedString;
}Example 20
| Project: IrssiNotifier-master File: Crypto.java View source code |
public static String decrypt(String key, String payload) throws CryptoException {
try {
byte[] payloadBytes = Base64.decode(payload, Base64.URL_SAFE);
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
// Remove OpenSSL Salted_
byte[] salt = new byte[8];
System.arraycopy(payloadBytes, 8, salt, 0, 8);
SecretKeyFactory fact = SecretKeyFactory.getInstance("PBEWITHMD5AND128BITAES-CBC-OPENSSL", "BC");
c.init(Cipher.DECRYPT_MODE, fact.generateSecret(new PBEKeySpec(key.toCharArray(), salt, 100)));
// Decrypt the rest of the byte array (after stripping off the salt)
byte[] data = c.doFinal(payloadBytes, 16, payloadBytes.length - 16);
String decrypted = new String(data, "utf8");
// trim out
return decrypted.substring(0, decrypted.length() - 1);
// trailing
// \n
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Unable to decrypt data", e);
throw new CryptoException("Unable to decrypt data", e);
}
}Example 21
| Project: Loop-master File: UnauthorizedNetworkInterceptor.java View source code |
// endregion
@Override
public Response intercept(Chain chain) throws IOException {
if (chain != null) {
Request originalRequest = chain.request();
Map<String, String> headersMap = new HashMap<>();
String clientId = context.getString(R.string.client_id);
String clientSecret = context.getString(R.string.client_secret);
// concatenate username and password with colon for authentication
final String credentials = clientId + ":" + clientSecret;
String authorization = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headersMap.put("Authorization", authorization);
headersMap.put("Accept", "application/json");
Request modifiedRequest = RequestUtility.updateHeaders(originalRequest, headersMap);
return chain.proceed(modifiedRequest);
}
return null;
}Example 22
| Project: magpi-android-master File: SecurityUtils.java View source code |
public static String Hmac(String secret, String data) {
try {
SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
String result = Base64.encodeToString(rawHmac, Base64.NO_WRAP);
return result;
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException();
}
}Example 23
| Project: material-cat-master File: Model.java View source code |
public static Model deSerializeFromString(String string) {
if (string == null) {
return null;
}
byte[] bytes = Base64.decode(string.getBytes(), Base64.DEFAULT);
Model data = null;
try {
ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(bytes));
data = (Model) is.readObject();
} catch (IOExceptionClassNotFoundException | ClassCastException | e) {
Log.e(TAG, e.getMessage());
}
return data;
}Example 24
| Project: meetup-client-master File: Commands.java View source code |
public static String authenticate(String s) {
String s1 = (new StringBuilder("\000x@x.com\0")).append(s).toString();
return (new StringBuilder("<ns2:auth ns3:service='webupdates' mechanism='X-GOOGLE-TOKEN' xmlns:ns3='http://www.google.com/talk/protocol/auth' xmlns:ns2='urn:ietf:params:xml:ns:xmpp-sasl' ns3:allow-generated-jid='true' ns3:client-uses-full-bind-result='true'>")).append(Base64.encodeToString(encodeUtf8(s1), 0)).append("</ns2:auth>").toString();
}Example 25
| Project: Musubi-Android-master File: JSON.java View source code |
public static String fastAddBase64(String original, String key, byte[] data) {
String encoded = Base64.encodeToString(data, Base64.DEFAULT);
StringBuilder sb = new StringBuilder(encoded.length() + key.length() + original.length() + 32);
sb.append(original.subSequence(0, original.lastIndexOf('}')));
sb.append(",\"");
sb.append(key);
sb.append("\":\"");
sb.append(encoded);
sb.append("\"}");
return sb.toString();
}Example 26
| Project: MyLibrary-master File: Base64Test.java View source code |
@Test
public void testEncodeToStringAndDecode() throws Exception {
byte[] input = { 11, 22, 33 };
String temp = Base64.encodeToString(input, Base64.NO_PADDING | Base64.NO_WRAP | Base64.URL_SAFE);
byte[] output = Base64.decode(temp, Base64.NO_PADDING | Base64.NO_WRAP | Base64.URL_SAFE);
assertEquals(new String(input), new String(output));
byte[] temp2 = android.util.Base64.encode(input, Base64.NO_PADDING | Base64.NO_WRAP | Base64.URL_SAFE);
byte[] output2 = Base64.decode(temp2, Base64.NO_PADDING | Base64.NO_WRAP | Base64.URL_SAFE);
assertEquals(new String(input), new String(output2));
}Example 27
| Project: player-sdk-native-android-master File: OfflineKeySetStorage.java View source code |
public byte[] loadKeySetId(byte[] initData) throws FileNotFoundException {
String encodedInitData = Base64.encodeToString(initData, Base64.NO_WRAP);
String encodedKeySetId = mSettings.getString(encodedInitData, null);
if (encodedKeySetId == null) {
throw new FileNotFoundException("Can't load keySetId");
}
return Base64.decode(encodedKeySetId, 0);
}Example 28
| Project: popcorn-android-master File: SignUtils.java View source code |
public static int checkAppSignature(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : packageInfo.signatures) {
byte[] signatureBytes = signature.toByteArray();
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(signatureBytes);
String currentSignature = Base64.encodeToString(md.digest(), Base64.NO_WRAP);
Timber.d("Detected signature: %s", currentSignature);
//compare signatures
if (SIGNATURE.equals(currentSignature) || SIGNATURE_DEV.equals(currentSignature)) {
return VALID;
}
}
} catch (Exception e) {
}
return INVALID;
}Example 29
| Project: SmartZPN-master File: ShadowsocksConfig.java View source code |
public static ShadowsocksConfig parse(String proxyInfo) throws Exception {
ShadowsocksConfig config = new ShadowsocksConfig();
Uri uri = Uri.parse(proxyInfo);
if (uri.getPort() == -1) {
String base64String = uri.getHost();
proxyInfo = "ss://" + new String(Base64.decode(base64String.getBytes("ASCII"), Base64.DEFAULT));
uri = Uri.parse(proxyInfo);
}
String userInfoString = uri.getUserInfo();
if (userInfoString != null) {
String[] userStrings = userInfoString.split(":");
config.EncryptMethod = userStrings[0];
if (userStrings.length >= 2) {
config.Password = userStrings[1];
}
}
config.ServerAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
config.Encryptor = EncryptorFactory.createEncryptorByConfig(config);
return config;
}Example 30
| Project: voxe-android-master File: Icon.java View source code |
public Optional<String> getUniqueId() {
if (uniqueId == null) {
Optional<String> largestIconUrl = getLargestIconUrl();
if (largestIconUrl.isPresent()) {
byte[] urlBytes = largestIconUrl.get().getBytes();
String encodedUrl = "tag_" + Base64.encodeToString(urlBytes, Base64.NO_WRAP);
uniqueId = Optional.of(encodedUrl);
} else {
uniqueId = Optional.absent();
}
}
return uniqueId;
}Example 31
| Project: yotacast-master File: BSRecord.java View source code |
synchronized void saveState() {
Parcel parcel = Parcel.obtain();
try {
mInstanceState.writeToParcel(parcel, 0);
String savedState = Base64.encodeToString(parcel.marshall(), 0);
if (savedState != null) {
Editor editor = getPreference().edit();
editor.putString(PREF_NAME, savedState);
editor.commit();
}
} finally {
parcel.recycle();
}
}Example 32
| Project: commcare-odk-master File: KeyRecordParser.java View source code |
/*
* (non-Javadoc)
* @see org.commcare.xml.ElementParser#parse()
*/
@Override
public ArrayList<UserKeyRecord> parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException {
this.checkNode("auth_keys");
while (this.nextTagInBlock("auth_keys")) {
this.checkNode("key_record");
Date valid = getDateAttribute("valid", false);
Date expires = getDateAttribute("expires", true);
this.nextTag("uuid");
String title = parser.getAttributeValue(null, "title");
String uuid = parser.nextText();
if (uuid == null) {
throw new InvalidStructureException("No <uuid> value found for incoming key record", parser);
}
this.nextTag("key");
//We don't really use this for now
String type = parser.getAttributeValue(null, "type");
//Base64 Encoded AES key
String encodedKey = parser.nextText();
byte[] theKey;
try {
theKey = Base64.decode(encodedKey);
} catch (Base64DecoderException e) {
e.printStackTrace();
throw new InvalidStructureException("Invalid AES key in key record", parser);
}
byte[] wrappedKey = CryptUtil.wrapKey(theKey, currentpwd);
UserKeyRecord record = new UserKeyRecord(username, UserKeyRecord.generatePwdHash(currentpwd), wrappedKey, valid, expires, uuid, UserKeyRecord.TYPE_NEW);
keyRecords.add(record);
}
commit(keyRecords);
return keyRecords;
}Example 33
| Project: LegacyNFC-master File: FriendsActivity.java View source code |
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == ADD_FRIEND_QR) {
if (resultCode == Activity.RESULT_OK) {
try {
String data = intent.getStringExtra("SCAN_RESULT");
if (!data.startsWith(ConnectionHandoverManager.USER_HANDOVER_PREFIX)) {
throw new Exception();
}
// make sure it parses
new NdefMessage(android.util.Base64.decode(data.substring(ConnectionHandoverManager.USER_HANDOVER_PREFIX.length()), android.util.Base64.URL_SAFE));
mScannedNdefString = data.substring(ConnectionHandoverManager.USER_HANDOVER_PREFIX.length());
showDialog(DIALOG_NAME);
} catch (Exception e) {
toast("QR code is not a vNFC tag.");
}
}
}
}Example 34
| Project: enviroCar-app-master File: PIDSupportedQuirkTest.java View source code |
@Test
public void testQuirk() {
byte[] bytesWait = Base64.decode("QjcwN0U4MDA8vg==", Base64.DEFAULT);
byte[] bytesFull = Base64.decode("QjcwN0U4MDA8vj48uBM=", Base64.DEFAULT);
PIDSupportedQuirk quirk = new PIDSupportedQuirk();
Assert.assertTrue(quirk.shouldWaitForNextTokenLine(bytesWait));
Assert.assertFalse(quirk.shouldWaitForNextTokenLine(bytesFull));
}Example 35
| Project: hk-master File: CryptoHooker.java View source code |
/** * Attach on Base64 class */ private void attachOnBase64Class() { Map<String, Integer> methodsToHook = new HashMap<String, Integer>(); methodsToHook.put("decode", 0); methodsToHook.put("encode", 0); methodsToHook.put("encodeToString", 0); try { hookMethods(null, "android.util.Base64", methodsToHook); SubstrateMain.log("hooking android.util.Base64 methods sucessful"); } catch (HookerInitializationException e) { SubstrateMain.log("hooking android.util.Base64 methods has failed", e); } }
Example 36
| Project: ComicBook-master File: ImageStoreManager.java View source code |
@Override
protected void doInBackgroundGuarded(Void... params) {
try {
ContentResolver contentResolver = getReactApplicationContext().getContentResolver();
Uri uri = Uri.parse(mUri);
InputStream is = contentResolver.openInputStream(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
try {
while ((bytesRead = is.read(buffer)) > -1) {
b64os.write(buffer, 0, bytesRead);
}
mSuccess.invoke(baos.toString());
} catch (IOException e) {
mError.invoke(e.getMessage());
} finally {
closeQuietly(is);
// this also closes baos
closeQuietly(b64os);
}
} catch (FileNotFoundException e) {
mError.invoke(e.getMessage());
}
}Example 37
| Project: ig-json-parser-master File: BenchmarkActivity.java View source code |
private String loadFromFile(int resourceId) throws IOException {
InputStreamReader inputStreamReader = null;
try {
// we're doing this absurd thing with encoding the json file in base64 because phabricator
// chokes on it otherwise.
inputStreamReader = new InputStreamReader(new Base64InputStream(getResources().openRawResource(resourceId), Base64.DEFAULT), "UTF-8");
StringBuilder sb = new StringBuilder();
char[] buffer = new char[8 * 1024];
int bytesRead;
while ((bytesRead = inputStreamReader.read(buffer)) != -1) {
sb.append(buffer, 0, bytesRead);
}
return sb.toString();
} finally {
try {
if (inputStreamReader != null) {
inputStreamReader.close();
}
} catch (IOException ignored) {
}
}
}Example 38
| Project: kdeconnect-android-master File: ContactsHelper.java View source code |
public static String photoId64Encoded(Context context, String photoId) {
if (photoId == null) {
return "";
}
Uri photoUri = Uri.parse(photoId);
InputStream input = null;
Base64OutputStream output = null;
try {
ByteArrayOutputStream encodedPhoto = new ByteArrayOutputStream();
output = new Base64OutputStream(encodedPhoto, Base64.DEFAULT);
input = context.getContentResolver().openInputStream(photoUri);
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) != -1) {
output.write(buffer, 0, len);
}
return encodedPhoto.toString();
} catch (Exception ex) {
Log.e("ContactsHelper", ex.toString());
return "";
} finally {
try {
input.close();
} catch (Exception ignored) {
}
;
try {
output.close();
} catch (Exception ignored) {
}
;
}
}Example 39
| Project: mvfa-master File: MVDataHelper.java View source code |
/**
* Returns the GET response of the given url.
*
* @throws IOException
* @return The response of the given URL. If no response was found, null is
* returned.
*/
public static String getResponse(String username, String password, String url) throws IOException {
/* DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(username + ":" + password));
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
*/
DefaultHttpClient httpclient = new DefaultHttpClient();
Credentials creds = new UsernamePasswordCredentials(username, password);
httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds);
String auth = android.util.Base64.encodeToString((username + ":" + password).getBytes("UTF-8"), android.util.Base64.NO_WRAP);
HttpGet httpget = new HttpGet(url);
httpget.addHeader("Authorization", "Basic " + auth);
HttpResponse response = httpclient.execute(httpget);
if (response.getEntity() != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
Log.v(MVDataHelper.class.getSimpleName(), "Response:" + sb.toString());
return sb.toString();
}
return null;
}Example 40
| Project: OBDintheCloud-master File: GetHTTPTask.java View source code |
private InputStream getHttpConnection(String urlString) throws IOException {
InputStream stream = null;
HttpURLConnection httpConnection;
URL url;
String userPassword, encoding;
// prepare authorization string using android.util.Base64
userPassword = String.format("%s:%s", USERNAME, PASSWORD);
int flags = Base64.NO_WRAP | Base64.URL_SAFE;
encoding = Base64.encodeToString(userPassword.getBytes(), flags);
try {
url = new URL(urlString);
// Open HttpURLConnection
httpConnection = (HttpURLConnection) url.openConnection();
// Append authorization string to HTTP request header
httpConnection.setRequestProperty("Authorization", "Basic " + encoding);
/*
* From open Tutorials example, using DGTech solution
httpConnection.setRequestMethod("GET");
httpConnection.connect();
*/
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
return stream;
}Example 41
| Project: react-native-sidemenu-master File: ImageStoreManager.java View source code |
@Override
protected void doInBackgroundGuarded(Void... params) {
try {
ContentResolver contentResolver = getReactApplicationContext().getContentResolver();
Uri uri = Uri.parse(mUri);
InputStream is = contentResolver.openInputStream(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
try {
while ((bytesRead = is.read(buffer)) > -1) {
b64os.write(buffer, 0, bytesRead);
}
mSuccess.invoke(baos.toString());
} catch (IOException e) {
mError.invoke(e.getMessage());
} finally {
closeQuietly(is);
// this also closes baos
closeQuietly(b64os);
}
} catch (FileNotFoundException e) {
mError.invoke(e.getMessage());
}
}Example 42
| Project: ReactNativeApp-master File: ImageStoreManager.java View source code |
@Override
protected void doInBackgroundGuarded(Void... params) {
try {
ContentResolver contentResolver = getReactApplicationContext().getContentResolver();
Uri uri = Uri.parse(mUri);
InputStream is = contentResolver.openInputStream(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
try {
while ((bytesRead = is.read(buffer)) > -1) {
b64os.write(buffer, 0, bytesRead);
}
mSuccess.invoke(baos.toString());
} catch (IOException e) {
mError.invoke(e.getMessage());
} finally {
closeQuietly(is);
// this also closes baos
closeQuietly(b64os);
}
} catch (FileNotFoundException e) {
mError.invoke(e.getMessage());
}
}Example 43
| Project: remote-desktop-clients-master File: PubkeyUtils.java View source code |
/** Recovers the key-pair from the private key (and passphrase if provided).
*
* @param sshPrivKey private key base64 encoded.
* @param passphrase passphrase as a plain string.
* @return true if successful and false otherwise
* @author Iordan K. Iordanov
*/
public static KeyPair decryptAndRecoverKeyPair(String sshPrivKey, String passphrase) {
KeyPair kp = null;
if (sshPrivKey == null) {
Log.e(TAG, "SSH private key is null.");
return null;
} else if (sshPrivKey.length() == 0) {
Log.i(TAG, "SSH private key is empty, not recovering");
return null;
}
if (passphrase == null)
passphrase = new String("");
try {
if (passphrase.length() != 0) {
Log.i(TAG, "Passphrase not empty, trying to decrypt key.");
// Try decrypting key with passphrase entered by user.
byte[] decrypted = PubkeyUtils.decrypt(android.util.Base64.decode(sshPrivKey, android.util.Base64.DEFAULT), passphrase);
kp = PubkeyUtils.recoverKeyPair(decrypted);
} else {
Log.i(TAG, "Passphrase empty, recovering directly.");
// There was no passphrase entered, so key is probably not encrypted.
kp = PubkeyUtils.recoverKeyPair(android.util.Base64.decode(sshPrivKey, android.util.Base64.DEFAULT));
}
} catch (Exception e) {
Log.i(TAG, "Either key is not encrypted and we were given passphrase, or the passphrase is wrong," + "or the key is corrupt.");
e.printStackTrace();
return null;
}
return kp;
}Example 44
| Project: Sgk-Saglik-Provizyon-App-master File: JsObject.java View source code |
@JavascriptInterface
public void showBase64Image(String base64Image) {
String cleanBase64Image = base64Image.replace("data:image/png;base64,", "");
try {
mDecodedString = android.util.Base64.decode(cleanBase64Image, android.util.Base64.DEFAULT);
if (mDecodedString.length == 0)
return;
if (mResultHandler != null)
mResultHandler.onConvertComplete(mDecodedString);
} catch (Exception e) {
Toast.makeText(mContext, "Byte Çevirimde Hata \n" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}Example 45
| Project: 2015-SMSGateway-master File: SmapRawRequest.java View source code |
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
String usr = GatewayApp.getPreferenceWrapper().getUserName();
String psw = GatewayApp.getPreferenceWrapper().getPassword();
String creds = String.format("%s:%s", usr, psw);
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
}Example 46
| Project: an2linuxclient-master File: RsaHelper.java View source code |
static void initialiseRsaKeyAndCert(Context c) {
try {
SharedPreferences deviceKeyPref = c.getSharedPreferences(c.getString(R.string.device_key_and_cert), MODE_PRIVATE);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(4096);
KeyPair keyPair = kpg.generateKeyPair();
deviceKeyPref.edit().putString(c.getString(R.string.privatekey), Base64.encodeToString(keyPair.getPrivate().getEncoded(), Base64.NO_WRAP)).apply();
Log.d("RsaHelper", "Generated new keypair successfully");
TlsHelper.initialiseCertificate(c, keyPair);
} catch (Exception e) {
Log.e("RsaHelper", "initialiseRsaKeyAndCert");
Log.e("StackTrace", Log.getStackTraceString(e));
}
}Example 47
| Project: buddycloud-android-master File: VersionUtils.java View source code |
/**
* Get the unique app hashKey
*
* @param context
* @return
* @throws NameNotFoundException
*/
public static String getAppHashKey(Context context) {
String hashKey = null;
try {
PackageInfo manager = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : manager.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
hashKey = Base64.encodeToString(md.digest(), Base64.DEFAULT);
}
} catch (NameNotFoundException e) {
Logger.info(TAG, e.getLocalizedMessage());
} catch (NoSuchAlgorithmException e) {
Logger.info(TAG, e.getLocalizedMessage());
}
return hashKey;
}Example 48
| Project: conekta-android-master File: Connection.java View source code |
protected String doInBackground(Void... params) {
String result;
HttpClient http = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(Conekta.getBaseUri() + endPoint);
String encoding = Base64.encodeToString(Conekta.getPublicKey().getBytes(), Base64.NO_WRAP);
try {
httpRequest.setHeader("Accept", "application/vnd.conekta-v" + Conekta.getApiVersion() + "+json");
httpRequest.setHeader("Accept-Language", Conekta.getLanguage());
httpRequest.setHeader("Conekta-Client-User-Agent", "{\"agent\": \"Conekta Android SDK\"}");
httpRequest.setHeader("Authorization", "Basic " + encoding);
httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = http.execute(httpRequest);
result = EntityUtils.toString(response.getEntity());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return result;
}Example 49
| Project: CryptoNFC-master File: EncryptionUtils.java View source code |
public static String encrypt(SecretKey key, String stringToEncrypt) throws BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
Cipher ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
// Encode the string into bytes using utf-8
byte[] utf8 = stringToEncrypt.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return Base64.encodeToString(enc, Base64.DEFAULT);
}Example 50
| Project: Cyllell-master File: Digester.java View source code |
public String hash_string(String str) {
MessageDigest md = null;
byte[] sha1hash = new byte[40];
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
md.update(str.getBytes("iso-8859-1"), 0, str.length());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
sha1hash = md.digest();
return Base64.encodeToString(sha1hash, Base64.NO_WRAP);
}Example 51
| Project: dreamDroid-master File: MainActivity.java View source code |
@Override
protected HttpURLConnection openConnection(Uri path) throws IOException {
HttpURLConnection connection = super.openConnection(path);
String userinfo = path.getUserInfo();
if (!userinfo.isEmpty()) {
connection.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(userinfo.getBytes(), Base64.NO_WRAP));
}
return connection;
}Example 52
| Project: fablab-android-master File: UserModel.java View source code |
public void getUser(String username, String password) {
final String credentials = username + ":" + password;
mRestAdapterBuilder.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
// create Base64 encodet string
String string = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader("Authorization", string);
request.addHeader("Accept", "application/json");
}
});
mUserApi = mRestAdapterBuilder.build().create(UserApi.class);
mUserApi.getUserInfo(mUserCallback);
}Example 53
| Project: fanshawe-connect-master File: SecretKeyGenerator.java View source code |
/*package*/
static char[] getSecretKey() {
return new String(Base64.decode("AAAAB3NzaC1yc2EAAAABJQAAAQEAxY/wxbgH6s8J1PzMa3upDvxOd13g7oo+Yski4" + "t672WGGUV4vcFZuiR2znxOT4ebmZ7KfVE6kT6rHmMwsLlWxQ3oMTj8xsPHx7NR1Pt" + "RCarLUztS8vONw5UoL6hSlrANKRd6pPL/Q9QD05z+9IWtsfs2e3FGEVv75L7Ibv1j" + "1/H98lTotulqkulmQD3qd/iZIoLHI6qMPpZaG79++Mg+9WVQIKUZQ/+nMSdojpJaj" + "WqOMhj4Vltk1hBr/sQQh5mEteNL3rkX8P3+lKEyq7FlPSwb67yeYs6mkgBwVNy+u6" + "ht84DKmoDl60B+oXs/cqQaWu8Bvu+tTIQmt0x8SRB7jLQ==", Base64.DEFAULT)).toCharArray();
}Example 54
| Project: gdg-sacramento-master File: HttpRequestArgs.java View source code |
public String getBasicAuth() {
String encodedBasicAuth = null;
if (null != userId && null != password && !"".equals(userId) && !"".equals(password)) {
StringBuilder basicAuth = new StringBuilder(userId);
basicAuth.append(":");
basicAuth.append(password);
encodedBasicAuth = Base64.encodeToString(basicAuth.toString().getBytes(), Base64.NO_WRAP);
}
return encodedBasicAuth;
}Example 55
| Project: GitClub-master File: GithubAuthRetrofit.java View source code |
@Override
public Response intercept(Chain chain) throws IOException {
// https://developer.github.com/v3/auth/#basic-authentication
// https://developer.github.com/v3/oauth/#non-web-application-flow
String userCredentials = userName + ":" + password;
String basicAuth = "Basic " + new String(Base64.encode(userCredentials.getBytes(), Base64.DEFAULT));
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder().header("Authorization", basicAuth.trim());
Request request = requestBuilder.build();
return chain.proceed(request);
}Example 56
| Project: GithubAndroidSdk-master File: GetReadmeContentsClient.java View source code |
@Override
protected Observable<String> getApiObservable(RestAdapter restAdapter) {
RepoService repoService = restAdapter.create(RepoService.class);
Observable<Content> contentObservable;
if (getBranch() == null) {
contentObservable = repoService.readme(getOwner(), getRepo());
} else {
contentObservable = repoService.readme(getOwner(), getRepo(), getBranch());
}
return contentObservable.filter( content -> content != null && !TextUtils.isEmpty(content.content)).filter( content -> "base64".equals(content.encoding)).map( content -> {
byte[] data = Base64.decode(content.content, Base64.DEFAULT);
try {
content.content = new String(data, "UTF-8");
return content.content;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}).filter( s -> !TextUtils.isEmpty(s)).map( s -> {
RequestMarkdownDTO requestMarkdownDTO = new RequestMarkdownDTO();
requestMarkdownDTO.text = s;
return requestMarkdownDTO;
}).flatMap( requestMarkdownDTO -> new GetMarkdownClient(requestMarkdownDTO).observable());
}Example 57
| Project: Gitskarios-master File: ReadmeCloudDataSource.java View source code |
@Override
protected Observable<SdkItem<String>> execute(SdkItem<ReadmeInfo> request, RestWrapper service) {
RepositoryReadmeService repositoryReadmeService = restWrapper.get();
ReadmeInfo readmeInfo = request.getK();
return Observable.defer(() -> {
Call<Content> call;
if (readmeInfo.getRepoInfo().branch == null) {
call = repositoryReadmeService.readme(readmeInfo.getRepoInfo().owner, readmeInfo.getRepoInfo().name);
} else {
call = repositoryReadmeService.readme(readmeInfo.getRepoInfo().owner, readmeInfo.getRepoInfo().name, readmeInfo.getRepoInfo().branch);
}
try {
Response<Content> contentResponse = call.execute();
if (contentResponse.isSuccessful()) {
return Observable.just(contentResponse.body());
} else {
return Observable.error(new Exception(contentResponse.errorBody().string()));
}
} catch (IOException e) {
return Observable.error(e);
}
}).map(Content::getContent).flatMap( content -> Observable.fromCallable(() -> {
byte[] data = Base64.decode(content, Base64.DEFAULT);
return new String(data, "UTF-8");
})).map( s -> {
if (readmeInfo.isTruncate()) {
return trimString(s, 300, true);
} else {
return s;
}
}).map(SdkItem::new);
}Example 58
| Project: GreenBits-master File: PinData.java View source code |
public static PinData fromMnemonic(final String pinIdentifier, final String mnemonic, final byte[] password) {
final byte[] salt = CryptoHelper.randomBytes(16);
final byte[] seed = CryptoHelper.mnemonic_to_seed(mnemonic);
final Map<String, Object> json = new HashMap<>();
json.put("mnemonic", mnemonic);
json.put("seed", Wally.hex_from_bytes(seed));
final byte[] encryptedJSON = CryptoHelper.encryptJSON(new JSONMap(json), password, Base64.encode(salt, Base64.NO_WRAP));
return new PinData(pinIdentifier, salt, encryptedJSON, seed, mnemonic);
}Example 59
| Project: infotainment-master File: StreamToBase64String.java View source code |
/**
* Takes the inputstream given and creates a base64 string from it.
* @param filename
* @return the base64 representation of the stream
*/
public String getBase64StringFromStream(InputStream is) {
int readBytes;
int bufferSize = 1024;
byte byteArray[] = new byte[bufferSize];
ByteArrayOutputStream ba = new ByteArrayOutputStream();
try {
while ((readBytes = is.read(byteArray, 0, bufferSize)) >= 0) {
ba.write(byteArray, 0, readBytes);
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(ba.toByteArray(), Base64.DEFAULT);
}Example 60
| Project: ion-master File: SpdyTests.java View source code |
public void testAppEngineSpdy() throws Exception {
// Ion.getDefault(getContext())
// .getConscryptMiddleware().enable(false);
// Security.insertProviderAt(new OpenSSLProvider("MyNameBlah"), 1);
String uploadUrl = Ion.with(getContext()).load("https://ion-test.appspot.com/upload_url").asString().get();
byte[] random = new byte[100000];
new Random(39548394).nextBytes(random);
String b64 = Base64.encodeToString(random, 0);
File file = getContext().getFileStreamPath("testData");
StreamUtility.writeFile(file, b64);
String data = Ion.with(getContext()).load(uploadUrl).setLogging("test", Log.VERBOSE).setMultipartFile("file", file).asString().get();
assertEquals(b64, data);
}Example 61
| Project: IoTgo_Android_App-master File: SendingTask.java View source code |
@Override
public void execute(JSONArray args, CallbackContext ctx) {
try {
int id = args.getInt(0);
String data = args.getString(1);
boolean binaryString = args.getBoolean(2);
Connection conn = _map.get(id);
if (conn != null) {
if (binaryString) {
byte[] binary = Base64.decode(data, Base64.NO_WRAP);
conn.sendMessage(binary, 0, binary.length);
} else {
conn.sendMessage(data);
}
}
} catch (Exception e) {
ctx.error("send");
}
}Example 62
| Project: jnrain-android-master File: KBSRegisterResult.java View source code |
@JsonIgnore
public Drawable getCaptchaDrawable() {
if (captcha != null) {
byte[] captchaImgData = Base64.decode(captcha, Base64.DEFAULT);
ByteArrayInputStream captchaStream = new ByteArrayInputStream(captchaImgData);
try {
return BitmapDrawable.createFromStream(captchaStream, "src");
} finally {
try {
captchaStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}Example 63
| Project: Kore-master File: BasicAuthUrlConnectionDownloader.java View source code |
@Override
protected HttpURLConnection openConnection(android.net.Uri uri) throws java.io.IOException {
HttpURLConnection urlConnection = super.openConnection(uri);
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
String creds = username + ":" + password;
urlConnection.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP));
}
return urlConnection;
}Example 64
| Project: ListenerMusicPlayer-master File: LyricUtil.java View source code |
public static String decryptBASE64(String str) {
if (str == null || str.length() == 0) {
return null;
}
try {
byte[] encode = str.getBytes("UTF-8");
// base64 解密
return new String(Base64.decode(encode, 0, encode.length, Base64.DEFAULT), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}Example 65
| Project: mage-android-sdk-master File: PasswordUtility.java View source code |
public static boolean equal(String password, String hash) throws Exception {
if (hash == null || password == null) {
return false;
}
String[] saltAndPass = hash.split("\\$");
if (saltAndPass.length != 2) {
throw new IllegalStateException("The stored password have the form 'salt$hash'");
}
String hashOfInput = hash(password, Base64.decode(saltAndPass[0], Base64.NO_WRAP));
return hashOfInput.equals(saltAndPass[1]);
}Example 66
| Project: MiBandDecompiled-master File: SaltGenerate.java View source code |
public static String getKeyFromParams(List list) {
Collections.sort(list, new a());
StringBuilder stringbuilder = new StringBuilder();
Iterator iterator = list.iterator();
for (boolean flag = true; iterator.hasNext(); flag = false) {
NameValuePair namevaluepair = (NameValuePair) iterator.next();
if (!flag) {
stringbuilder.append("&");
}
stringbuilder.append(namevaluepair.getName()).append("=").append(namevaluepair.getValue());
}
stringbuilder.append("&").append("8007236f-");
stringbuilder.append("a2d6-4847-ac83-");
stringbuilder.append("c49395ad6d65");
return MD5.getMd5Digest(Base64.encodeToString(a(stringbuilder.toString()), 2));
}Example 67
| Project: momock-android-master File: BundleHelper.java View source code |
public static String toBase64(Bundle in) {
if (in == null)
return null;
Parcel parcel = Parcel.obtain();
String serialized = null;
try {
in.writeToParcel(parcel, 0);
serialized = Base64.encodeToString(parcel.marshall(), 0);
} catch (Exception e) {
Logger.error(e);
} finally {
parcel.recycle();
}
return serialized;
}Example 68
| Project: Moxy-master File: SignInPresenter.java View source code |
public void signIn(String email, String password) {
Integer emailError = null;
Integer passwordError = null;
getViewState().hideFormError();
if (TextUtils.isEmpty(email)) {
emailError = R.string.error_field_required;
}
if (TextUtils.isEmpty(password)) {
passwordError = R.string.error_invalid_password;
}
if (emailError != null || passwordError != null) {
getViewState().showFormError(emailError, passwordError);
return;
}
getViewState().startSignIn();
String credentials = String.format("%s:%s", email, password);
final String token = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
Subscription subscription = mGithubService.signIn(token).doOnNext( user -> AuthUtils.setToken(token)).compose(Utils.applySchedulers()).subscribe( user -> {
getViewState().finishSignIn();
getViewState().successSignIn();
}, exception -> {
getViewState().finishSignIn();
getViewState().failedSignIn(exception.getMessage());
});
unsubscribeOnDestroy(subscription);
}Example 69
| Project: ohmagePhone-master File: AdminDialogFragment.java View source code |
@Override
public void onClick(TrigTextInput ti, int which) {
if (which == TrigTextInput.BUTTON_POSITIVE) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
digest.update(SALT.getBytes());
byte[] input = digest.digest(String.valueOf(ti.getText()).getBytes("UTF-8"));
mSuccess = MessageDigest.isEqual(Base64.encode(input, 0), ADMIN_CODE.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (!mSuccess) {
Toast.makeText(getActivity(), R.string.admin_dialog_invalid_pin, Toast.LENGTH_SHORT).show();
}
}
}Example 70
| Project: Onions-Android-master File: OCSecurity.java View source code |
public static String encryptedText(String text, String password) {
// Set up
AES256JNCryptor cryptor = ocCryptor(defaultPBKDFRounds);
String encryptedText = null;
// Encrypt
try {
byte[] ciphertext = cryptor.encryptData(text.getBytes(), password.toCharArray());
encryptedText = Base64.encodeToString(ciphertext, Base64.NO_WRAP);
} catch (CryptorException e) {
e.printStackTrace();
}
// Return it
return encryptedText;
}Example 71
| Project: org.numixproject.hermes-master File: Gitty.java View source code |
@Override
public void init(Bundle savedInstanceState) {
String token = "ZTdjZDJjMmJkODIwNjQ5MjE3NjBlMGU1OTg2OTBiYzgzMWEwZDI3MQ==";
byte[] data1 = Base64.decode(token, Base64.DEFAULT);
String decodedToken = token;
try {
decodedToken = new String(data1, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Set where Gitty will send issues.
// (username, repository name);
setTargetRepository("numixproject", "org.numixproject.hermes");
// Set Auth token to open issues if user doesn't have a GitHub account
// For example, you can register a bot account on GitHub that will open bugs for you.
setGuestOAuth2Token(decodedToken);
// OPTIONAL METHODS
// Set if User can send bugs with his own GitHub account (default: true)
// If false, Gitty will always use your Auth token
enableUserGitHubLogin(true);
// Set if Gitty can use your Auth token for users without a GitHub account (default: true)
// If false, Gitty will redirect non registred users to github.com/join
enableGuestGitHubLogin(true);
PackageInfo pInfo = null;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String version = pInfo != null ? pInfo.versionName : null;
// Include other relevant info in your bug report (like custom variables).
setExtraInfo("Hermes version: " + version);
}Example 72
| Project: Pin-Fever-Android-master File: SpdyTests.java View source code |
public void testAppEngineSpdy() throws Exception {
// Ion.getDefault(getContext())
// .getConscryptMiddleware().enable(false);
// Security.insertProviderAt(new OpenSSLProvider("MyNameBlah"), 1);
String uploadUrl = Ion.with(getContext()).load("https://ion-test.appspot.com/upload_url").asString().get();
byte[] random = new byte[100000];
new Random(39548394).nextBytes(random);
String b64 = Base64.encodeToString(random, 0);
File file = getContext().getFileStreamPath("testData");
StreamUtility.writeFile(file, b64);
String data = Ion.with(getContext()).load(uploadUrl).setLogging("test", Log.VERBOSE).setMultipartFile("file", file).asString().get();
assertEquals(b64, data);
}Example 73
| Project: platform_packages_apps_im-master File: StandardPasswordDigest.java View source code |
public String digest(String schema, String nonce, String password) throws ImException {
byte[] digestBytes;
byte[] inputBytes;
try {
inputBytes = (nonce + password).getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException e) {
throw new ImException(e);
}
try {
if ("SHA".equals(schema))
schema = "SHA-1";
MessageDigest md = MessageDigest.getInstance(schema);
digestBytes = md.digest(inputBytes);
} catch (NoSuchAlgorithmException e) {
throw new ImException("Unsupported schema: " + schema);
}
return Base64.encodeToString(digestBytes, Base64.NO_WRAP);
}Example 74
| Project: QuarkUpto29May-master File: SplashScreenActivity.java View source code |
private void showHashCode() {
try {
PackageInfo info = getPackageManager().getPackageInfo("com.cmcdelhi.guffyfbandyapp", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("GUFRAN", Base64.encodeToString(md.digest(), Base64.DEFAULT));
Toast.makeText(getApplicationContext(), "" + Base64.encodeToString(md.digest(), Base64.DEFAULT), Toast.LENGTH_SHORT).show();
}
} catch (NameNotFoundException e) {
Log.d("GUFRAN", "Name Not Found Exception");
} catch (NoSuchAlgorithmException e) {
Log.d("GUFRAN", "No Such ALGO Exception");
}
}Example 75
| Project: RAVA-Voting-master File: Utils.java View source code |
/**
* Print hash key
*/
public static void printHashKey(Context context) {
try {
String TAG = "com.sromku.simple.fb.example";
PackageInfo info = context.getPackageManager().getPackageInfo(TAG, PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String keyHash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
Log.d(TAG, "keyHash: " + keyHash);
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}Example 76
| Project: robospice-master File: DefaultKeySanitizer.java View source code |
// ----------------------------------
// API
// ----------------------------------
@Override
public Object sanitizeKey(Object cacheKey) throws KeySanitationExcepion {
if (!(cacheKey instanceof String)) {
throw new KeySanitationExcepion(DefaultKeySanitizer.class.getSimpleName() + " can only be used with Strings cache keys.");
}
try {
return Base64.encodeToString(((String) cacheKey).getBytes(UTF8_CHARSET_NAME), BASE64_FLAGS);
} catch (UnsupportedEncodingException e) {
throw new KeySanitationExcepion(e);
}
}Example 77
| Project: shopnc-app-master File: ServiceGenerator.java View source code |
public static <S> S createService(Class<S> serviceClass, String baseUrl, String username, String password) {
// set endpoint url and use OkHTTP as HTTP client
RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(baseUrl).setClient(new OkClient(new OkHttpClient()));
if (username != null && password != null) {
// concatenate username and password with colon for authentication
final String credentials = username + ":" + password;
builder.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestInterceptor.RequestFacade request) {
// create Base64 encodet string
request.addHeader("Accept", "application/json");
}
});
}
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}Example 78
| Project: TestingStuff-master File: TestBase64.java View source code |
public void testBase64encode() {
try {
byte[] testData = new byte[64 * 1024 + 7];
for (int i = 0; i < testData.length; ++i) {
testData[i] = (byte) (i % 256);
}
InputStream in = new ByteArrayInputStream(testData);
StringBuilder sb = new StringBuilder();
XmlUtil.streamToBase64(in, sb);
String base64 = sb.toString();
in.close();
byte[] raw = Base64.decode(base64, Base64.DEFAULT);
Assert.assertEquals("decoded data wrong length", testData.length, raw.length);
for (int i = 0; i < raw.length; ++i) {
Assert.assertEquals("conversion wrong", testData[i], raw[i]);
}
} catch (IOException e) {
e.printStackTrace();
Assert.fail("testBase64encode failed");
}
}Example 79
| Project: tikal_share_android-master File: YouTubeDataCacher.java View source code |
public void cacheThis(String cache_id, Object obj) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
String jsonStr = Base64.encodeToString(baos.toByteArray(), 0);
String objClass = obj.getClass().getName();
this.myStore.store(cache_id, jsonStr, objClass);
}Example 80
| Project: TLSDemo-master File: PEMTrustManager.java View source code |
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
boolean ok = false;
for (X509Certificate cert : chain) {
Log.e(TAG, "sigAlgName: " + cert.getSigAlgName() + "; SigAlgOID: " + cert.getSigAlgOID());
try {
Log.e(TAG, "public key algorithm: " + mCert.getPublicKey().getAlgorithm() + "; form: " + mCert.getPublicKey().getFormat() + "; key: " + mCert.getPublicKey().toString());
Log.e(TAG, "public key base64: " + Base64.encodeToString(mCert.getPublicKey().getEncoded(), Base64.DEFAULT));
cert.verify(mCert.getPublicKey());
ok = true;
break;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
}
}
if (!ok) {
throw new CertificateException();
}
}Example 81
| Project: tum-campus-master File: RSASigner.java View source code |
/**
* Sign the message given as the parameter and return it as a base64 encoded
* {@link String}.
*
* @param message The message to be encoded
* @return A base64 encoded signature
*/
public String sign(String message) {
Signature signer = getSignatureInstance();
try {
signer.initSign(privateKey);
} catch (InvalidKeyException e) {
Utils.log(e);
return null;
}
byte[] messageBytes = message.getBytes(Charsets.UTF_8);
try {
signer.update(messageBytes);
} catch (SignatureException e) {
Utils.log(e);
return null;
}
byte[] signature;
try {
signature = signer.sign();
} catch (SignatureException e) {
Utils.log(e);
return null;
}
return Base64.encodeToString(signature, Base64.DEFAULT);
}Example 82
| Project: TumCampusApp-master File: RSASigner.java View source code |
/**
* Sign the message given as the parameter and return it as a base64 encoded
* {@link String}.
*
* @param message The message to be encoded
* @return A base64 encoded signature
*/
public String sign(String message) {
Signature signer = getSignatureInstance();
try {
signer.initSign(privateKey);
} catch (InvalidKeyException e) {
Utils.log(e);
return null;
}
byte[] messageBytes = message.getBytes(Charsets.UTF_8);
try {
signer.update(messageBytes);
} catch (SignatureException e) {
Utils.log(e);
return null;
}
byte[] signature;
try {
signature = signer.sign();
} catch (SignatureException e) {
Utils.log(e);
return null;
}
return Base64.encodeToString(signature, Base64.DEFAULT);
}Example 83
| Project: wearscript-android-master File: SpeechManager.java View source code |
public void onEvent(ActivityResultEvent event) {
int requestCode = event.getRequestCode(), resultCode = event.getResultCode();
Intent intent = event.getIntent();
if (requestCode == 1002) {
Log.d(TAG, "Spoken Text Result");
if (resultCode == Activity.RESULT_OK) {
List<String> results = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String spokenText = results.get(0);
Log.d(TAG, "Spoken Text: " + spokenText);
spokenText = Base64.encodeToString(spokenText.getBytes(), Base64.NO_WRAP);
makeCall(SPEECH, String.format("\"%s\"", spokenText));
} else if (resultCode == Activity.RESULT_CANCELED) {
}
}
}Example 84
| Project: WebSocket-for-Android-master File: SendingTask.java View source code |
@Override
public void execute(String rawArgs, CallbackContext ctx) {
try {
String args = new JSONArray(rawArgs).getString(0);
Connection conn = _map.get(Integer.parseInt(args.substring(0, 8), 16));
if (conn != null) {
if (args.charAt(8) == '1') {
byte[] binary = Base64.decode(args.substring(args.indexOf(',') + 1), Base64.NO_WRAP);
conn.sendMessage(binary, 0, binary.length);
} else {
conn.sendMessage(args.substring(9));
}
} else {
}
} catch (Exception e) {
if (!ctx.isFinished()) {
PluginResult result = new PluginResult(Status.ERROR);
result.setKeepCallback(true);
ctx.sendPluginResult(result);
}
}
}Example 85
| Project: Android-kakaologin-gradle-sample-master File: Utility.java View source code |
public static String getKeyHash(final Context context) {
PackageInfo packageInfo = getPackageInfo(context, PackageManager.GET_SIGNATURES);
if (packageInfo == null)
return null;
for (Signature signature : packageInfo.signatures) {
try {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
return android.util.Base64.encodeToString(md.digest(), android.util.Base64.NO_WRAP);
} catch (NoSuchAlgorithmException e) {
Log.w(TAG, "Unable to get MessageDigest. signature=" + signature, e);
}
}
return null;
}Example 86
| Project: AndroidAsync-master File: NetworkEventReporterWrapper.java View source code |
public DataEmitter interpretResponseEmitter(final String requestId, @Nullable DataEmitter body, final boolean b64Encode) {
final NetworkPeerManager peerManager = getPeerManagerIfEnabled();
if (peerManager == null)
return null;
final WritableByteChannel channel;
try {
if (b64Encode) {
final Base64OutputStream b64out = new Base64OutputStream(peerManager.getResponseBodyFileManager().openResponseBodyFile(requestId, false), Base64.DEFAULT);
channel = Channels.newChannel(b64out);
} else {
channel = ((FileOutputStream) peerManager.getResponseBodyFileManager().openResponseBodyFile(requestId, false)).getChannel();
}
} catch (IOException e) {
return null;
}
FilteredDataEmitter ret = new FilteredDataEmitter() {
ByteBufferList pending = new ByteBufferList();
@Override
protected void report(Exception e) {
super.report(e);
StreamUtility.closeQuietly(channel);
if (e == null)
responseReadFinished(requestId);
else
responseReadFailed(requestId, e.toString());
}
@Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
int amount = bb.remaining();
ByteBuffer[] original = bb.getAllArray();
ByteBuffer[] copy = new ByteBuffer[original.length];
for (int i = 0; i < original.length; i++) {
copy[i] = original[i].duplicate();
}
try {
for (ByteBuffer c : copy) {
channel.write(c);
}
} catch (IOException ignored) {
StreamUtility.closeQuietly(channel);
}
pending.addAll(original);
dataReceived(requestId, amount, amount);
super.onDataAvailable(emitter, pending);
}
};
ret.setDataEmitter(body);
return ret;
}Example 87
| Project: CodenameOne-master File: Security.java View source code |
/**
* Generates a PublicKey instance from a string containing the
* Base64-encoded public key.
*
* @param encodedPublicKey Base64-encoded public key
* @throws IllegalArgumentException if encodedPublicKey is invalid
*/
public static PublicKey generatePublicKey(String encodedPublicKey) {
try {
byte[] decodedKey = Base64.decode(encodedPublicKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
Log.e(TAG, "Invalid key specification.");
throw new IllegalArgumentException(e);
} catch (Base64DecoderException e) {
Log.e(TAG, "Base64 decoding failed.");
throw new IllegalArgumentException(e);
}
}Example 88
| Project: kaa-master File: AndroidHttpClient.java View source code |
private byte[] getResponseBody(HttpResponse response, boolean verifyResponse) throws IOException, GeneralSecurityException {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
byte[] body = toByteArray(resEntity);
consume(resEntity);
if (verifyResponse) {
Header signatureHeader = response.getFirstHeader(CommonEpConstans.SIGNATURE_HEADER_NAME);
if (signatureHeader == null) {
throw new IOException("can't verify message");
}
byte[] signature;
if (signatureHeader.getValue() != null) {
signature = android.util.Base64.decode(signatureHeader.getValue().getBytes(Charsets.UTF_8), android.util.Base64.DEFAULT);
} else {
signature = new byte[0];
}
return verifyResponse(body, signature);
} else {
return body;
}
} else {
throw new IOException("can't read message");
}
}Example 89
| Project: LEHomeMobile_android-master File: FileUtil.java View source code |
public static String FileToBase64(File srcFile) {
//You can get an inputStream using any IO API
InputStream inputStream = null;
try {
inputStream = new FileInputStream(srcFile.getAbsolutePath());
} catch (FileNotFoundException e) {
return null;
}
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
return null;
}
try {
output64.close();
} catch (IOException e) {
return null;
}
return output.toString();
}Example 90
| Project: Roid-Library-master File: RLFileUtil.java View source code |
/**
*
* @param file
* @return
*/
public static String fileToBase64(String file) {
String result = null;
try {
FileInputStream fis = new FileInputStream(new File(file));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Base64OutputStream base64out = new Base64OutputStream(baos, Base64.NO_WRAP);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) >= 0) {
base64out.write(buffer, 0, len);
}
base64out.flush();
base64out.close();
/*
* Why should we close Base64OutputStream before processing the data:
* http://stackoverflow.com/questions/24798745/android-file-to-base64-using-streaming-sometimes-missed-2-bytes
*/
result = new String(baos.toByteArray(), "UTF-8");
baos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}Example 91
| Project: stetho-master File: ScreencastDispatcher.java View source code |
@Override
public void run() {
if (!mIsRunning || mBitmap == null) {
return;
}
int width = mBitmap.getWidth();
int height = mBitmap.getHeight();
mStream.reset();
Base64OutputStream base64Stream = new Base64OutputStream(mStream, Base64.DEFAULT);
// request format is either "jpeg" or "png"
Bitmap.CompressFormat format = Bitmap.CompressFormat.valueOf(mRequest.format.toUpperCase());
mBitmap.compress(format, mRequest.quality, base64Stream);
mEvent.data = mStream.toString();
mMetadata.pageScaleFactor = 1;
mMetadata.deviceWidth = width;
mMetadata.deviceHeight = height;
mEvent.metadata = mMetadata;
mPeer.invokeMethod("Page.screencastFrame", mEvent, null);
mMainHandler.postDelayed(mEndAction, FRAME_DELAY);
}Example 92
| Project: android-15-master File: ManifestDigest.java View source code |
static ManifestDigest fromAttributes(Attributes attributes) {
if (attributes == null) {
return null;
}
String encodedDigest = null;
for (int i = 0; i < DIGEST_TYPES.length; i++) {
final String value = attributes.getValue(DIGEST_TYPES[i]);
if (value != null) {
encodedDigest = value;
break;
}
}
if (encodedDigest == null) {
return null;
}
final byte[] digest = Base64.decode(encodedDigest, Base64.DEFAULT);
return new ManifestDigest(digest);
}Example 93
| Project: android-beacon-library-master File: EddystoneTelemetryAccessor.java View source code |
/**
* Extracts the raw Eddystone telemetry bytes from the extra data fields of an associated beacon
* and base64 encodes them. This is useful for passing the telemetry to Google's backend
* services.
* @param beacon
* @return base64 encoded telemetry bytes
*/
@TargetApi(Build.VERSION_CODES.FROYO)
public String getBase64EncodedTelemetry(Beacon beacon) {
byte[] bytes = getTelemetryBytes(beacon);
if (bytes != null) {
String base64EncodedTelemetry = Base64.encodeToString(bytes, Base64.DEFAULT);
// 12-21 00:17:18.844 20180-20180/? D/EddystoneTLMAccessor: Rehydrated telemetry bytes are :20 00 00 00 88 29 18 4d 00 00 18 4d 00 00
// 12-21 00:17:18.844 20180-20180/? D/EddystoneTLMAccessor: Base64 telemetry bytes are :IAAAAIgpGE0AABhNAAA=
Log.d(TAG, "Base64 telemetry bytes are :" + base64EncodedTelemetry);
return base64EncodedTelemetry;
} else {
return null;
}
}Example 94
| Project: AndroidProjectTemplate-master File: MainActivityFragment.java View source code |
@Background
void getTweets() {
AppApplication appApplication = (AppApplication) getActivity().getApplication();
TwitterService twitterService = appApplication.getTwitterService();
try {
String urlApiKey = URLEncoder.encode(BuildConfig.TWITTER_USER_API_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(BuildConfig.TWITTER_USER_API_SECRET, "UTF-8");
String combined = urlApiKey + ":" + urlApiSecret;
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
Token credentials = twitterService.getToken("Basic " + base64Encoded, "application/x-www-form-urlencoded;charset=UTF-8", "client_credentials");
TweetList tweets = twitterService.getTweets("Bearer " + credentials.getAccess_token(), "application/json");
populateRecycleView(tweets.getStatuses());
} catch (Exception e) {
Snackbar.make(getView(), "OOPS, Something was wrong on tweet load", Snackbar.LENGTH_LONG).show();
e.printStackTrace();
}
}Example 95
| Project: c84-android-master File: ComplexPreferencesSampleActivity.java View source code |
public String toBase64(Object object) {
// try-with-resources����ーー��
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
byte[] base64 = Base64.encode(bytes, Base64.NO_WRAP);
return new String(base64);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (oos != null) {
oos.close();
}
if (baos != null) {
baos.close();
}
} catch (Exception e) {
}
}
return null;
}Example 96
| Project: commcare-master File: UpdatePromptHelper.java View source code |
/**
* @return an UpdateToPrompt that has been stored in SharedPreferences and is still relevant
* (i.e. the user hasn't updated to or past this version since we stored it)
*/
public static UpdateToPrompt getCurrentUpdateToPrompt(boolean forApkUpdate) {
CommCareApp currentApp = CommCareApplication.instance().getCurrentApp();
if (currentApp != null) {
String prefsKey = forApkUpdate ? UpdateToPrompt.KEY_APK_UPDATE_TO_PROMPT : UpdateToPrompt.KEY_CCZ_UPDATE_TO_PROMPT;
String serializedUpdate = currentApp.getAppPreferences().getString(prefsKey, "");
if (!"".equals(serializedUpdate)) {
byte[] updateBytes = Base64.decode(serializedUpdate, Base64.DEFAULT);
UpdateToPrompt update;
try {
update = SerializationUtil.deserialize(updateBytes, UpdateToPrompt.class);
} catch (Exception e) {
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "Error encountered while de-serializing saved UpdateToPrompt: " + e.getMessage());
wipeStoredUpdate(forApkUpdate);
return null;
}
if (update.isNewerThanCurrentVersion(currentApp)) {
return update;
} else {
// The update we had stored is no longer relevant, so wipe it and return nothing
wipeStoredUpdate(forApkUpdate);
return null;
}
}
}
return null;
}Example 97
| Project: conversation-master File: JinglePacket.java View source code |
public void addChecksum(byte[] sha1Sum, String namespace) {
this.checksum = new Element("checksum", namespace);
checksum.setAttribute("creator", "initiator");
checksum.setAttribute("name", "a-file-offer");
Element hash = checksum.addChild("file").addChild("hash", "urn:xmpp:hashes:2");
hash.setAttribute("algo", "sha-1").setContent(Base64.encodeToString(sha1Sum, Base64.NO_WRAP));
}Example 98
| Project: Conversations-master File: JinglePacket.java View source code |
public void addChecksum(byte[] sha1Sum, String namespace) {
this.checksum = new Element("checksum", namespace);
checksum.setAttribute("creator", "initiator");
checksum.setAttribute("name", "a-file-offer");
Element hash = checksum.addChild("file").addChild("hash", "urn:xmpp:hashes:2");
hash.setAttribute("algo", "sha-1").setContent(Base64.encodeToString(sha1Sum, Base64.NO_WRAP));
}Example 99
| Project: dashclock-gerrit-master File: GerritPreferences.java View source code |
private static String getSecurePreferencesKey(Context context) {
String securePreferencesKey = getSharedPreferences(context).getString(SECURE_KEY, null);
if (securePreferencesKey == null) {
SecretKey key = generateKey();
if (key != null) {
String generatedKey = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
securePreferencesKey = generatedKey;
SharedPreferences prefs = getSharedPreferences(context);
prefs.edit().putString(SECURE_KEY, securePreferencesKey).commit();
}
}
if (securePreferencesKey == null) {
return DEFAULT_SECURE_PREFERENCES_KEY;
}
return securePreferencesKey + DEFAULT_SECURE_PREFERENCES_KEY;
}Example 100
| Project: domodroid-master File: httpsUrl.java View source code |
//todo add tracerengine here too handle log.
public static HttpsURLConnection setUpHttpsConnection(String urlString, String login, String password) {
try {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@SuppressLint("TrustAllX509TrustManager")
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@SuppressLint("TrustAllX509TrustManager")
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
// Install the all-trusting trust manager
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
@SuppressLint("BadHostnameVerifier")
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL(urlString);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setHostnameVerifier(allHostsValid);
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
final String basicAuth = "Basic " + Base64.encodeToString((login + ":" + password).getBytes(), Base64.NO_WRAP);
urlConnection.setRequestProperty("Authorization", basicAuth);
return urlConnection;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}Example 101
| Project: effective_android_sample-master File: ComplexPreferencesSampleActivity.java View source code |
public String toBase64(Object object) {
// try-with-resources����ーー��
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
byte[] base64 = Base64.encode(bytes, Base64.NO_WRAP);
return new String(base64);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (oos != null) {
oos.close();
}
if (baos != null) {
baos.close();
}
} catch (Exception e) {
}
}
return null;
}