android.util.Base64 Java Examples

The following examples show how to use android.util.Base64. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: QRCodeGenerator.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 9 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 #2
Source File: IIntakeData.java    From CameraV with 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 #3
Source File: RCTSodiumModule.java    From react-native-sodium with 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 #4
Source File: Storage.java    From beacons-android with 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 #5
Source File: SecureCredentialsManagerTest.java    From Auth0.Android with 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 #6
Source File: TgVoip.java    From Telegram-FOSS with 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 #7
Source File: SsManifestParser.java    From Telegram with 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 #8
Source File: DatabaseBackend.java    From Pix-Art-Messenger with 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 #9
Source File: Settings.java    From andOTP with 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 #10
Source File: PebbleDictionary.java    From pebble-android-sdk with 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 #11
Source File: MyService.java    From BetterAndroRAT with 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 #12
Source File: VpnProfile.java    From Cake-VPN with 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 #13
Source File: GroupChannelListAdapter.java    From SendBird-Android with 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 #14
Source File: AndroidChannelPreferences.java    From android-chromium with 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 #15
Source File: VpnProfile.java    From SimpleOpenVpn-Android with 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 #16
Source File: AmiiboFile.java    From amiibo with 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 #17
Source File: SsManifestParser.java    From MediaSDK with 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 #18
Source File: AdActivity.java    From imsdk-android with 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 #19
Source File: OFileManager.java    From hr with 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 #20
Source File: CrashReportActivity.java    From LaunchTime with 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 #21
Source File: CordovaResourceApi.java    From reader with 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 #22
Source File: AndroidTamperingProtection.java    From AndroidTampering with 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 #23
Source File: RCTSodiumModule.java    From react-native-sodium with 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 #24
Source File: KcUtils.java    From GotoBrowser with 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 #25
Source File: KeyChainSnapshotSerializer.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static void writePropertyTag(
        XmlSerializer xmlSerializer, String propertyName, byte[] propertyValue)
        throws IOException {
    xmlSerializer.startTag(NAMESPACE, propertyName);
    xmlSerializer.text(Base64.encodeToString(propertyValue, /*flags=*/ Base64.DEFAULT));
    xmlSerializer.endTag(NAMESPACE, propertyName);
}
 
Example #26
Source File: Base64Utils.java    From Android-IM with Apache License 2.0 5 votes vote down vote up
public static String getFromBase64(String str) {
    String result = "";
    if (str != null) {
        try {
            result = new String(Base64.decode(str, Base64.NO_WRAP), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    return result;
}
 
Example #27
Source File: KeyStoreHelper.java    From xmrwallet with 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);
}
 
Example #28
Source File: AESCrypto.java    From android-auth-manager with 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 #29
Source File: LyricUtil.java    From RetroMusicPlayer with 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 #30
Source File: PinData.java    From green_android with 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;
}