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:com.jbirdvegas.mgerrit.dialogs.DiffDialog.java

private String workAroundBadBase(String baseString) {
    if (baseString == null) {
        return getContext().getString(R.string.return_was_null);
    }//w w  w . j  av  a2  s  .com
    String failMessage = "Failed to decode Base64 using: ";
    try {
        return new String(ApacheBase64.decodeBase64(baseString));
    } catch (IllegalArgumentException badBase) {
        Log.e(TAG, failMessage + "org.apache.commons.codec.binary.ApacheBase64", badBase);
    }
    try {
        return new String(Base64.decode(baseString.getBytes(), Base64.URL_SAFE | Base64.NO_PADDING));
    } catch (IllegalArgumentException badBase) {
        Log.e(TAG, failMessage + "android.util.Base64", badBase);
    }
    try {
        return new String(Base64Coder.decode(baseString));
    } catch (IllegalArgumentException badBase) {
        Log.e(TAG, failMessage + "com.jbirdvegas.mgerrit.helpers.Base64Coder", badBase);
    }
    return getContext().getString(R.string.failed_to_decode_base64);
}

From source file:com.trail.octo.Identity.java

public void loaddata() {
    byte[] decodedString;
    String encodedmessage = "";

    encodedmessage = sharedPreferences.getString("pancard", "Empty");
    if (!(encodedmessage.equals("Empty") || encodedmessage.isEmpty())) {
        decodedString = Base64.decode(encodedmessage, Base64.DEFAULT);
        pan_card = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }/*from w ww . j a v a 2  s .  c  o  m*/

    encodedmessage = sharedPreferences.getString("drivinglicense", "Empty");
    if (!(encodedmessage.equals("Empty") || encodedmessage.isEmpty())) {
        decodedString = Base64.decode(encodedmessage, Base64.DEFAULT);
        driving_license = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }

    encodedmessage = sharedPreferences.getString("voterid", "Empty");
    if (!(encodedmessage.equals("Empty") || encodedmessage.isEmpty())) {
        decodedString = Base64.decode(encodedmessage, Base64.DEFAULT);
        voter_id = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }

    encodedmessage = sharedPreferences.getString("aadharcard", "Empty");
    if (!(encodedmessage.equals("Empty") || encodedmessage.isEmpty())) {
        decodedString = Base64.decode(encodedmessage, Base64.DEFAULT);
        aadhar_card = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }

    encodedmessage = sharedPreferences.getString("passport", "Empty");
    if (!(encodedmessage.equals("Empty") || encodedmessage.isEmpty())) {
        decodedString = Base64.decode(encodedmessage, Base64.DEFAULT);
        passport = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    }
}

From source file:org.kde.kdeconnect.Helpers.SecurityHelpers.RsaHelper.java

public static NetworkPackage decrypt(NetworkPackage np, PrivateKey privateKey)
        throws GeneralSecurityException, JSONException {

    JSONArray chunks = np.getJSONArray("data");

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    String decryptedJson = "";
    for (int i = 0; i < chunks.length(); i++) {
        byte[] encryptedChunk = Base64.decode(chunks.getString(i), Base64.NO_WRAP);
        String decryptedChunk = new String(cipher.doFinal(encryptedChunk));
        decryptedJson += decryptedChunk;
    }//from   w  w w.j  av a 2  s.  c  om

    NetworkPackage decrypted = NetworkPackage.unserialize(decryptedJson);
    decrypted.setPayload(np.getPayload(), np.getPayloadSize());
    return decrypted;
}

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

private byte[] getSalt() {
    SharedPreferences preferences = getSharedPreferences(CREDENTIALS_PREF_FILE, MODE_PRIVATE);
    byte[] salt;/*from  ww w .ja v a2s. c  om*/
    if (preferences.contains(SALT_PREF)) {
        salt = Base64.decode(preferences.getString(SALT_PREF, ""), Base64.DEFAULT);
    } else {
        //Generate a new salt if one doesn't exist.
        salt = SecurityUtil.generateSalt().getEncoded();
        SharedPreferences.Editor editor = preferences.edit().putString(SALT_PREF,
                Base64.encodeToString(salt, Base64.DEFAULT));
        editor.apply();
    }

    return salt;
}

From source file:com.tapcentive.sdk.touchpoint.nfc.SEManager.java

/**
 * Do tapcentive interaction./*from www. j  a va2  s . c o m*/
 *
 * @param storage the storage
 * @return the interaction response
 * @throws TapcentiveException the tapcentive exception
 */
public InteractionResponse doTapcentiveInteraction(ProfileStorage storage) throws TapcentiveException {
    long time1 = SystemClock.uptimeMillis();

    @SuppressWarnings("unused")
    String prof = storage.getProfile();

    byte[] profile = Base64.decode(storage.getProfile(), Base64.DEFAULT);
    byte[] informationCommand = new byte[5 + profile.length];

    System.arraycopy(informationHeader, 0, informationCommand, 0, 5);
    System.arraycopy(profile, 0, informationCommand, 5, profile.length);

    informationCommand[4] = (byte) (profile.length);

    byte[] responseBuffer = sendAndReceive(informationCommand);

    long time2 = SystemClock.uptimeMillis();
    Log.d(TAG, "TIME: doTapcentiveIngeraction:sendAndReceive: " + (time2 - time1));

    InteractionResponse iResponse = new InteractionResponse(responseBuffer);
    long time3 = SystemClock.uptimeMillis();
    Log.d(TAG, "TIME: do TapcentiveInteraction:new InteractionResponse: " + (time3 - time2));

    return iResponse;
}

From source file:com.mhise.util.MHISEUtil.java

public static boolean saveImportedCertificateToDevice(String certificate, String password, Context ctx,
        String certName) {/* w w  w  . j a  v  a2s  . c  om*/
    boolean isPasswordCorrect = false;

    byte[] certificatebytes = null;

    try {
        certificatebytes = Base64.decode(certificate, Base64.DEFAULT);
    } catch (IllegalArgumentException e) {
        // TODO: handle exception
        Logger.debug("MHISEUtil-->saveImportedCertificateToDevice", "" + e);
    }
    KeyStore localTrustStore = null;
    try {
        localTrustStore = KeyStore.getInstance("PKCS12");
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream is = new ByteArrayInputStream(certificatebytes);
    try {
        localTrustStore.load(is, password.toCharArray());
        isPasswordCorrect = true;

    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }

    OutputStream fos = null;
    try {
        //<<<<<<< .mine
        //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE);
        //String  storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null);

        File _mobiusDirectory = new File(Constants.defaultP12StorePath);

        if (!_mobiusDirectory.exists()) {
            _mobiusDirectory.mkdir();
        }

        File file = new File(Constants.defaultP12StorePath + certName);
        fos = new FileOutputStream(file);
        //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE);
        localTrustStore.store(fos, MHISEUtil.getStrongPassword(certName).toCharArray());
        /*//=======
                    //SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,Context.MODE_PRIVATE);
                    //String  storeName =sharedPreferences.getString(Constants.KEY_CERT_NAME, null);
                            
                            
                    File file = new File(Constants.defaultP12StorePath+certName);
                     fos = new FileOutputStream(file);
                    //fos = ctx.openFileOutput(Constants.defaultP12StoreName, Context.MODE_PRIVATE);
                    localTrustStore.store(fos,MHISEUtil.getStrongPassword(certName).toCharArray());
        >>>>>>> .r4477*/
        fos.close();

        Enumeration<String> aliases = null;
        try {
            aliases = localTrustStore.aliases();
        } catch (KeyStoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //boolean isInstalledCertificateValid = false;

        while (aliases.hasMoreElements()) {

            String alias = aliases.nextElement();
            java.security.cert.X509Certificate cert = null;
            try {
                cert = (X509Certificate) localTrustStore.getCertificate(alias);
            } catch (KeyStoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            SharedPreferences sharedPreferences1 = ctx.getSharedPreferences(Constants.PREFS_NAME,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences1.edit();

            Log.i("Imported certificate serial number", "" + cert.getSerialNumber().toString(16));
            editor.putString(Constants.KEY_SERIAL_NUMBER, "" + cert.getSerialNumber().toString(16));
            editor.commit();

        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return isPasswordCorrect;
}

From source file:org.microg.gms.auth.AuthManagerServiceImpl.java

@Override
public Bundle getToken(String accountName, String scope, Bundle extras) throws RemoteException {
    String packageName = extras.getString(KEY_ANDROID_PACKAGE_NAME);
    if (packageName == null || packageName.isEmpty())
        packageName = extras.getString(KEY_CLIENT_PACKAGE_NAME);
    int callerUid = extras.getInt(KEY_CALLER_UID, 0);
    PackageUtils.checkPackageUid(context, packageName, callerUid, getCallingUid());
    boolean notify = extras.getBoolean(KEY_HANDLE_NOTIFICATION, false);

    Log.d(TAG, "getToken: account:" + accountName + " scope:" + scope + " extras:" + extras + ", notify: "
            + notify);//from   www  .j  av  a 2s. c om

    /*
     * TODO: This scope seems to be invalid (according to https://developers.google.com/oauthplayground/),
     * but is used in some applications anyway. Removing it is unlikely a good solution, but works for now.
     */
    scope = scope.replace("https://www.googleapis.com/auth/identity.plus.page.impersonation ", "");

    AuthManager authManager = new AuthManager(context, accountName, packageName, scope);
    Bundle result = new Bundle();
    result.putString(KEY_ACCOUNT_NAME, accountName);
    result.putString(KEY_ACCOUNT_TYPE, authManager.getAccountType());
    try {
        AuthResponse res = authManager.requestAuth(false);
        if (res.auth != null) {
            Log.d(TAG, "getToken: " + res);
            result.putString(KEY_AUTHTOKEN, res.auth);
            Bundle details = new Bundle();
            details.putParcelable("TokenData",
                    new TokenData(res.auth, res.expiry, scope.startsWith("oauth2:"), getScopes(scope)));
            result.putBundle("tokenDetails", details);
            result.putString(KEY_ERROR, "OK");
        } else {
            result.putString(KEY_ERROR, "NeedPermission");
            Intent i = new Intent(context, AskPermissionActivity.class);
            i.putExtras(extras);
            i.putExtra(KEY_ANDROID_PACKAGE_NAME, packageName);
            i.putExtra(KEY_ACCOUNT_TYPE, authManager.getAccountType());
            i.putExtra(KEY_ACCOUNT_NAME, accountName);
            i.putExtra(KEY_AUTHTOKEN, scope);
            try {
                if (res.consentDataBase64 != null)
                    i.putExtra(EXTRA_CONSENT_DATA, Base64.decode(res.consentDataBase64, Base64.URL_SAFE));
            } catch (Exception e) {
                Log.w(TAG, "Can't decode consent data: ", e);
            }
            if (notify) {
                NotificationManager nm = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                nm.notify(packageName.hashCode(),
                        new NotificationCompat.Builder(context)
                                .setContentIntent(PendingIntent.getActivity(context, 0, i, 0))
                                .setContentTitle(context.getString(R.string.auth_notification_title))
                                .setContentText(context.getString(R.string.auth_notification_content,
                                        getPackageLabel(packageName, context.getPackageManager())))
                                .setSmallIcon(android.R.drawable.stat_notify_error).build());
            }
            result.putParcelable(KEY_USER_RECOVERY_INTENT, i);
        }
    } catch (IOException e) {
        Log.w(TAG, e);
        result.putString(KEY_ERROR, "NetworkError");
    }
    return result;
}

From source file:com.wordsbaking.cordova.wechat.WeChat.java

private void share(JSONArray args, CallbackContext callbackContext) throws JSONException, NullPointerException {
    // check if installed
    if (!api.isWXAppInstalled()) {
        callbackContext.error(ERR_WECHAT_NOT_INSTALLED);
        return;/* w w w .j ava2s.  c o  m*/
    }

    JSONObject params = args.getJSONObject(0);

    if (params == null) {
        callbackContext.error(ERR_INVALID_OPTIONS);
        return;
    }

    SendMessageToWX.Req request = new SendMessageToWX.Req();

    request.transaction = String.valueOf(System.currentTimeMillis());

    int paramScene = params.getInt("scene");

    switch (paramScene) {
    case SCENE_SESSION:
        request.scene = SendMessageToWX.Req.WXSceneSession;
        break;
    // wechat android sdk does not support chosen by user
    case SCENE_CHOSEN_BY_USER:
    case SCENE_TIMELINE:
    default:
        request.scene = SendMessageToWX.Req.WXSceneTimeline;
        break;
    }

    WXMediaMessage message = null;

    String text = null;
    JSONObject messageOptions = null;

    if (!params.isNull("text")) {
        text = params.getString("text");
    }

    if (!params.isNull("message")) {
        messageOptions = params.getJSONObject("message");
    }

    if (messageOptions != null) {
        String url = null;
        String data = null;

        if (!messageOptions.isNull("url")) {
            url = messageOptions.getString("url");
        }

        if (!messageOptions.isNull("data")) {
            data = messageOptions.getString("data");
        }

        int type = SHARE_TYPE_WEBPAGE;

        if (!messageOptions.isNull("type")) {
            type = messageOptions.getInt("type");
        }

        switch (type) {
        case SHARE_TYPE_APP:
            break;
        case SHARE_TYPE_EMOTION:
            break;
        case SHARE_TYPE_FILE:
            break;
        case SHARE_TYPE_IMAGE:
            WXImageObject imageObject = new WXImageObject();
            if (url != null) {
                imageObject.imageUrl = url;
            } else if (data != null) {
                imageObject.imageData = Base64.decode(data, Base64.DEFAULT);
            } else {
                callbackContext.error(ERR_INVALID_OPTIONS);
                return;
            }
            message = new WXMediaMessage(imageObject);
            break;
        case SHARE_TYPE_MUSIC:
            break;
        case SHARE_TYPE_VIDEO:
            break;
        case SHARE_TYPE_WEBPAGE:
        default:
            WXWebpageObject webpageObject = new WXWebpageObject();
            webpageObject.webpageUrl = url;
            message = new WXMediaMessage(webpageObject);
            break;
        }

        if (message == null) {
            callbackContext.error(ERR_UNSUPPORTED_MEDIA_TYPE);
            return;
        }

        if (!messageOptions.isNull("title")) {
            message.title = messageOptions.getString("title");
        }

        if (!messageOptions.isNull("description")) {
            message.description = messageOptions.getString("description");
        }

        if (!messageOptions.isNull("thumbData")) {
            String thumbData = messageOptions.getString("thumbData");
            message.thumbData = Base64.decode(thumbData, Base64.DEFAULT);
        }
    } else if (text != null) {
        WXTextObject textObject = new WXTextObject();
        textObject.text = text;

        message = new WXMediaMessage(textObject);
        message.description = text;
    } else {
        callbackContext.error(ERR_INVALID_OPTIONS);
        return;
    }

    request.message = message;

    try {
        boolean success = api.sendReq(request);
        if (!success) {
            callbackContext.error(ERR_UNKNOWN);
            return;
        }
    } catch (Exception e) {
        callbackContext.error(e.getMessage());
        return;
    }

    currentCallbackContext = callbackContext;
}

From source file:com.facebook.login.LoginMethodHandler.java

private static String getUserIDFromSignedRequest(String signedRequest) throws FacebookException {
    if (signedRequest == null || signedRequest.isEmpty()) {
        throw new FacebookException("Authorization response does not contain the signed_request");
    }//  w w  w .j a  va 2s. c om

    try {
        String[] signatureAndPayload = signedRequest.split("\\.");
        if (signatureAndPayload.length == 2) {
            byte[] data = Base64.decode(signatureAndPayload[1], Base64.DEFAULT);
            String dataStr = new String(data, "UTF-8");
            JSONObject jsonObject = new JSONObject(dataStr);
            return jsonObject.getString("user_id");
        }
    } catch (UnsupportedEncodingException ex) {
    } catch (JSONException ex) {
    }
    throw new FacebookException("Failed to retrieve user_id from signed_request");
}

From source file:com.grarak.kerneladiutor.utils.Utils.java

public static String decodeString(String text) {
    try {/*w ww . jav  a2  s .  c  o m*/
        return new String(Base64.decode(text, Base64.DEFAULT), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}