Example usage for android.util Base64 decode

List of usage examples for android.util Base64 decode

Introduction

In this page you can find the example usage for android.util Base64 decode.

Prototype

public static byte[] decode(byte[] input, int flags) 

Source Link

Document

Decode the Base64-encoded data in input and return the data in a new byte array.

Usage

From source file:im.whistle.crypt.Crypt.java

/**
 * Decrypts a message./* ww  w  .  j  av a  2 s.com*/
 * @param args Arguments: enc, privateKey, sig, publicKey
 * @param callback Callback
 */
public static void decrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        // Get the arguments
        String enc = args.getString(0);
        String key = args.getString(1);
        String sig = null;
        String pub = null;
        if (args.length() == 4) {
            sig = args.getString(2);
            pub = args.getString(3);
        }
        Boolean ver = null;

        // Convert everything into byte arrays
        byte[] encRaw = Base64.decode(enc, Base64.DEFAULT);
        byte[] keyRaw = Base64.decode(stripKey(key), Base64.DEFAULT);

        // Verify signature
        if (sig != null && pub != null) {
            try {
                byte[] sigRaw = Base64.decode(sig, Base64.DEFAULT);
                byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);
                X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
                KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
                Signature s = Signature.getInstance("SHA1withRSA", "BC");
                s.initVerify(kf.generatePublic(publicKeySpec));
                s.update(encRaw);
                ver = s.verify(sigRaw);
            } catch (Exception ex) {
                Log.i("whistle", "Verification failed: " + ex.getMessage());
                ver = false;
            }
        }

        // Split enc into encrypted aes data and remaining enc
        byte[] encSplit = encRaw;
        byte[] aesRaw = new byte[RSA_BYTES];
        System.arraycopy(encSplit, 0, aesRaw, 0, aesRaw.length);
        encRaw = new byte[encSplit.length - RSA_BYTES];
        System.arraycopy(encSplit, RSA_BYTES, encRaw, 0, encRaw.length);

        // Decrypt encrypted aes data using RSAES-OAEP
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        Cipher c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding");
        c.init(Cipher.DECRYPT_MODE, kf.generatePrivate(privateKeySpec));
        aesRaw = c.doFinal(aesRaw);

        // Decrypted enc using AES-CBC
        byte[] aesKey = new byte[AES_BYTES];
        byte[] aesIv = new byte[aesRaw.length - aesKey.length];
        System.arraycopy(aesRaw, 0, aesKey, 0, aesKey.length);
        System.arraycopy(aesRaw, aesKey.length, aesIv, 0, aesIv.length);
        c = Cipher.getInstance("AES/CBC/PKCS7Padding");
        c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));
        byte[] dec = c.doFinal(encRaw);

        JSONArray res = new JSONArray();
        res.put(new String(dec, "utf-8"));
        res.put(ver);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Decrypt error:" + ex.getMessage(), ex);
        callback.error(ex);
    }
}

From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java

/**
 * Load a saved password for a file/*from w ww.  ja  v a  2  s. c om*/
 */
public String loadSavedPassword(Uri fileUri, Cipher cipher)
        throws IOException, BadPaddingException, IllegalBlockSizeException {
    String keyName = getPrefsKey(fileUri);
    SharedPreferences prefs = getPrefs();
    String encStr = prefs.getString(keyName, null);
    if (TextUtils.isEmpty(encStr)) {
        throw new IOException(itsContext.getString(R.string.password_not_found, fileUri));
    }

    byte[] enc = Base64.decode(encStr, Base64.NO_WRAP);
    byte[] decPassword = cipher.doFinal(enc);
    return new String(decPassword, "UTF-8");
}

From source file:org.n52.geoar.newdata.PluginLoader.java

/**
 * Restores the state of plugins from {@link SharedPreferences}. If an error
 * occurs, e.g. if a previously selected plugin got removed, this function
 * will quit silently./* w  w w . j  a v  a 2 s  . com*/
 */
private static void restoreState() {
    try {
        SharedPreferences preferences = GeoARApplication.applicationContext
                .getSharedPreferences(GeoARApplication.PREFERENCES_FILE, Context.MODE_PRIVATE);

        byte[] data = Base64.decode(preferences.getString(PLUGIN_STATE_PREF, ""), Base64.DEFAULT);
        PluginStateInputStream objectInputStream = new PluginStateInputStream(new ByteArrayInputStream(data));

        int stateVersion = objectInputStream.readInt();
        if (stateVersion != PLUGIN_STATE_VERSION) {
            // Do not read state if preferences contains old/invalid state
            // information
            return;
        }

        // Restore plugin state
        int count = objectInputStream.readInt();
        for (int i = 0; i < count; i++) {

            InstalledPluginHolder plugin = getPluginByIdentifier(objectInputStream.readUTF());
            if (plugin == null) {
                return;
            }
            try {
                plugin.restoreState(objectInputStream);
                plugin.postConstruct();
            } catch (IOException e) {
                LOG.warn("Exception while restoring state of plugin " + plugin.getName(), e);
            }
        }
        objectInputStream.close();
    } catch (Exception e) {
        LOG.error("Exception while restoring state ", e);
        // TODO
    }
}

From source file:com.ericrgon.postmark.BaseFragmentActivity.java

protected String decrypt(SecretKey key, String destinationPreference) {
    SharedPreferences preferences = getSharedPreferences(CREDENTIALS_PREF_FILE, MODE_PRIVATE);
    String encryptedValue = preferences.getString(destinationPreference, "");
    return SecurityUtil.decrypt(key, Base64.decode(encryptedValue, Base64.DEFAULT));
}

From source file:cc.flydev.launcher.InstallShortcutReceiver.java

private static ArrayList<PendingInstallShortcutInfo> getAndClearInstallQueue(SharedPreferences sharedPrefs) {
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (DBG)/*  w w  w .  j  a v  a 2  s.co  m*/
            Log.d(TAG, "Getting and clearing APPS_PENDING_INSTALL: " + strings);
        if (strings == null) {
            return new ArrayList<PendingInstallShortcutInfo>();
        }
        ArrayList<PendingInstallShortcutInfo> infos = new ArrayList<PendingInstallShortcutInfo>();
        for (String json : strings) {
            try {
                JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                Intent data = Intent.parseUri(object.getString(DATA_INTENT_KEY), 0);
                Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                String name = object.getString(NAME_KEY);
                String iconBase64 = object.optString(ICON_KEY);
                String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
                String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
                if (iconBase64 != null && !iconBase64.isEmpty()) {
                    byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
                    Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
                } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
                    Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
                    iconResource.resourceName = iconResourceName;
                    iconResource.packageName = iconResourcePackageName;
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
                }
                data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
                PendingInstallShortcutInfo info = new PendingInstallShortcutInfo(data, name, launchIntent);
                infos.add(info);
            } catch (org.json.JSONException e) {
                Log.d(TAG, "Exception reading shortcut to add: " + e);
            } catch (java.net.URISyntaxException e) {
                Log.d(TAG, "Exception reading shortcut to add: " + e);
            }
        }
        sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>()).commit();
        return infos;
    }
}

From source file:com.aegiswallet.utils.WalletUtils.java

/**
 * This file will check the password provided when importing a backup file. If the password is correct,
 * it will return true, if not, false.//from  ww  w .j a va2  s  .c  om
 *
 * @param fileName
 * @param password
 * @return
 */
public static boolean checkPasswordForBackupFile(String fileName, String password) {
    boolean result = false;

    try {
        if (Constants.WALLET_BACKUP_DIRECTORY.exists() && Constants.WALLET_BACKUP_DIRECTORY.isDirectory()) {

            File file = new File(Constants.WALLET_BACKUP_DIRECTORY, fileName);

            FileInputStream fileInputStream = new FileInputStream(file);
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(fileInputStream, Constants.UTF_8));

            while (true) {
                final String line = in.readLine();
                if (line == null)
                    break; // eof

                if (line.startsWith("#X2:")) {

                    String[] splitStr = line.split(":");
                    String x2Base64 = splitStr[1];

                    String x2Encrypted = new String(Base64.decode(x2Base64.getBytes(), Base64.NO_WRAP));
                    String x2Decrypted = WalletUtils.decryptString(x2Encrypted, password);
                    x2Decrypted = x2Decrypted.split(":")[1];

                    if (x2Decrypted != null) {
                        return true;
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IO Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "some other exception: " + e.getMessage());
    }

    return result;
}

From source file:com.primitive.applicationmanager.ApplicationManager.java

/**
 * ApplicationSummary??????//from   w w  w.  j  a  va2s .com
 * @return ApplicationSummary
 * @throws ApplicationManagerException
 */
private ApplicationSummary requestApplicationSummary() throws ApplicationManagerException {
    Logger.start();
    final String url = this.config.buildServerURL(ApplicationManager.ApplicationURI);
    final Map<String, String> params = new HashMap<String, String>();
    params.put("id", this.applicationID);
    final JSONObject json = this.requestToResponse(url, params);
    try {
        final boolean success = json.getBoolean("sucess");
        if (!success) {
            return this.beforeSummary;
        }
        final String hash = json.getString("hash");
        final String result = json.getString("result");
        final String passphrase = HashMacHelper.getHMACBase64(HashMacHelper.Algorithm.HmacSHA256,
                hash.getBytes("UTF-8"), this.config.passPhrase.getBytes("UTF-8"));

        byte[] passPhraseBytes = new byte[256 / 8];
        System.arraycopy(passphrase.getBytes(), 0, passPhraseBytes, 0, 256 / 8);

        final byte[] decriptDataByte = CipherHelper.decrypt(CipherHelper.Algorithm.AES, Mode.CBC,
                Padding.PKCS7Padding, Base64.decode(result.getBytes("UTF-8"), Base64.DEFAULT),
                hash.getBytes("UTF-8"), passPhraseBytes);

        final String decriptData = new String(decriptDataByte, "UTF-8");

        final JSONObject decript = new JSONObject(decriptData);
        final ApplicationSummary summary = new ApplicationSummary(decript);
        if (this.isUpgrade(summary)) {
            this.beforeSummary = summary;
        }
        this.beforeSummary = summary;
    } catch (final JSONException ex) {
        Logger.err(ex);
    } catch (final UnsupportedEncodingException ex) {
        Logger.err(ex);
    } catch (CipherException ex) {
        Logger.err(ex);
    }
    return this.beforeSummary;
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public void resultAnalyst(String restr, int delaynum, int speednum, String targetoutputfolder)
        throws IOException {

    String[] tempgetudplist = restr.split("sickjohnsisick1122356l112355iaaaoss");

    //     System.out.println(tempgetudplist[1]);

    String[] tempstrs = tempgetudplist[0].split("\\r\\n");

    for (int i = 10; i < tempstrs.length; i++) {

        String[] tempstrsxxxx = tempstrs[i].split(",");
        //vpn539246233|182.216.181.220|508611|35|41230804|Korea Republic of|KR|13|
        //#HostName|IP|Score|Ping|Speed|CountryLong|CountryShort|NumVpnSessions|Uptime|TotalUsers|TotalTraffic|LogType|Operator|Message|OpenVPN_ConfigData_Base64|\

        if (tempstrsxxxx.length > 14) {
            //Base64 decoder = new Base64();

            byte[] decodedBytes = Base64.decode(tempstrsxxxx[14], Base64.DEFAULT);
            tempstrsxxxx[14] = new String(decodedBytes, "UTF-8");
            tempstrsxxxx[14] = tempstrsxxxx[14].replaceAll("#.+?\r\n", "");

            // System.out.println
            log.info(tempstrsxxxx[0] + "|" + tempstrsxxxx[1] + "|" + tempstrsxxxx[2] + "|" + tempstrsxxxx[3]
                    + "|" + tempstrsxxxx[4] + "|" + tempstrsxxxx[5] + "|" + tempstrsxxxx[6] + "|"
                    + tempstrsxxxx[7] + "|" + tempstrsxxxx[8] + "|" + tempstrsxxxx[9] + "|" + tempstrsxxxx[10]
                    + "|" + tempstrsxxxx[11] + "|" + tempstrsxxxx[12] + "|" + tempstrsxxxx[13] + "|"
            // +udplist.get(tempudpportnum+1)+"|" //+tempstrsxxxx[14]
            );/*ww  w  .  j a v  a 2  s .c  o m*/

            if (isNumericInt(tempstrsxxxx[7]) && isNumericInt(tempstrsxxxx[3]) && isNumericInt(tempstrsxxxx[4])
                    &&
                    //tempstrsxxxx[14].indexOf("proto udp")!=-1 &&
                    // Integer.valueOf(tempstrsxxxx[7])>0        &&
                    Integer.valueOf(tempstrsxxxx[3]) < delaynum
                    && Integer.valueOf(tempstrsxxxx[4]) > speednum) {

                //  tempgetudplist[1].split(",");
                List<String> udplist = Arrays.asList(tempgetudplist[1].split(","));

                int tempudpportnum = udplist.indexOf(tempstrsxxxx[0]);

                if (tempudpportnum != -1) {

                    tempstrsxxxx[14] = tempstrsxxxx[14].replace("proto tcp", "proto udp");
                    tempstrsxxxx[14] = tempstrsxxxx[14].replaceFirst(
                            "remote [0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+ [0-9]+",
                            "remote " + tempstrsxxxx[1] + " " + udplist.get(tempudpportnum + 1));

                    int performrank = Integer.valueOf(tempstrsxxxx[2]) / 10000;

                    File tempfile = new File(targetoutputfolder + tempstrsxxxx[1] + "_" + tempstrsxxxx[6]
                            + "_udp_" + "Rank" + performrank + ".ovpn");
                    FileOutputStream osss = new FileOutputStream(tempfile);
                    osss.write(tempstrsxxxx[14].getBytes("UTF-8"));
                    osss.close();

                    //System.out.println
                    log.info(tempfile.getAbsoluteFile().toString());
                    tempfile = null;

                }
                //+tempstrsxxxx[14]+"|");
            }

        }

    }

}

From source file:com.securekey.sdk.sample.VerifyQuickCodeActivity.java

/**
 * Implements VerifyQuickCodeListener.verifyQuickCodeComplete
 * <p>/*  w  w  w. j  av  a2s . co m*/
 * If successful, will forward received txnId for final verification by the RP Server
 * 
 */
@Override
public void verifyQuickCodeComplete(int status, String transactionId) {
    if (status == Briidge.STATUS_OK) {
        if (this.jwsExpected) {
            // The JWT should be provide to a third party to be verify
            // It could be parse to see what's inside 

            dismissProgressDialog();
            String[] jwtSegment = getJWSSegments(transactionId);
            try {
                final StringBuilder message = new StringBuilder();
                message.append(new String(Base64.decode(jwtSegment[0], Base64.NO_WRAP), "UTF-8") + "\n");
                message.append(new String(Base64.decode(jwtSegment[1], Base64.NO_WRAP), "UTF-8") + "\n\n\n");
                showDialog(message.toString());

                verifyJWT(transactionId);
            } catch (UnsupportedEncodingException e) {
                Log.e(VerifyQuickCodeActivity.class.toString(), e.getMessage());
            }

        } else {

            rpQuickCodeVerify(transactionId);
        }
    } else if (status == Briidge.STATUS_TRY_LATER_TOO_MANY_INVALID_ATTEMPTS) {
        showDialog("User suspended!");
    } else if (status == Briidge.STATUS_WRONG_CODE) {
        showDialog("Invalid code!");
    } else {
        dismissProgressDialog();
        showDialog("Failed during verification process.");
    }

}

From source file:com.marekscholtz.bluetify.utilities.BluetoothChatService.java

private synchronized void connected(BluetoothSocket socket) {
    if (mAcceptThread != null) {
        mAcceptThread.cancel();/*from   www.j ava  2s  . com*/
        mAcceptThread = null;
    }
    if (mConnectThread != null) {
        mConnectThread.cancel();
        mConnectThread = null;
    }
    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();
    BluetoothAdapter bluetoothAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE))
            .getAdapter();

    if (mSharedPreferences == null) {
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    }

    byte[] usernameBytes = ("&u" + mSharedPreferences.getString("username", bluetoothAdapter.getName()) + "&p")
            .getBytes();
    if (mSharedPreferences.getString("profile_photo", null) == null) {
        write(usernameBytes);
    } else {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            outputStream.write(usernameBytes);
            outputStream
                    .write(Base64.decode(mSharedPreferences.getString("profile_photo", null), Base64.DEFAULT));
        } catch (IOException e) {
            e.printStackTrace();
        }
        write(outputStream.toByteArray());
    }
}