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.amanmehara.programming.android.adapters.LanguageAdapter.java

private Consumer<String> getLogoResponseCallback(String url, boolean cacheHit, String languageName,
        ViewHolder viewHolder) {//w  ww .  ja  v  a 2 s . co  m
    return response -> {
        try {
            if (!cacheHit) {
                sharedPreferences.edit().putString(url, response).apply();
            }
            JSONObject icon = new JSONObject(response);
            byte[] imageBlob = Base64.decode(icon.getString("content"), Base64.DEFAULT);
            int imageBlobLength = imageBlob.length;
            Bitmap logo = BitmapFactory.decodeByteArray(imageBlob, 0, imageBlobLength);
            logos.put(languageName, imageBlob);
            viewHolder.languageImageView.setImageBitmap(logo);
        } catch (JSONException e) {
            Log.e(TAG, e.getMessage());
            if (cacheHit) {
                sharedPreferences.edit().remove(url).apply();
            }
            viewHolder.languageImageView.setImageResource(R.drawable.ic_circle_logo);
        }
    };
}

From source file:jp.alessandro.android.iab.Security.java

/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key.//from w  w  w  .j  a  va 2  s .  com
 *
 * @param encodedPublicKey rsa public key generated by Google Play Developer Console
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
protected PublicKey generatePublicKey(String encodedPublicKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException {

    byte[] decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
}

From source file:enterprayz.megatools.Tools.java

public static String decodeBase64(String base64Format) {
    byte[] authEncBytes = Base64.decode(base64Format.getBytes(), Base64.DEFAULT);
    return new String(authEncBytes);
}

From source file:com.microsoft.aad.adal.IdToken.java

private HashMap<String, String> parseJWT(final String idtoken) throws AuthenticationException {
    final String idbody = extractJWTBody(idtoken);
    // URL_SAFE: Encoder/decoder flag bit to use
    // "URL and filename safe" variant of Base64
    // (see RFC 3548 section 4) where - and _ are used in place of +
    // and /.//from   w  w  w. j av  a  2  s.co  m
    final byte[] data = Base64.decode(idbody, Base64.URL_SAFE);

    try {
        final String decodedBody = new String(data, "UTF-8");
        final HashMap<String, String> responseItems = extractJsonObjects(decodedBody);
        return responseItems;
    } catch (UnsupportedEncodingException exception) {
        Logger.e(TAG, "The encoding is not supported.", "", ADALError.ENCODING_IS_NOT_SUPPORTED, exception);
        throw new AuthenticationException(ADALError.ENCODING_IS_NOT_SUPPORTED, exception.getMessage(),
                exception);
    } catch (JSONException exception) {
        Logger.e(TAG, "Failed to parse the decoded body into JsonObject.", "", ADALError.JSON_PARSE_ERROR,
                exception);
        throw new AuthenticationException(ADALError.JSON_PARSE_ERROR, exception.getMessage(), exception);
    }
}

From source file:com.kik.phonegap.plugin.messenger.KikMessengerPlugin.java

@Override
public PluginResult execute(String action, JSONArray arg1, String arg2) {
    // Here we are going to basically going to read the json object and proccess the response

    Log.d("KikMessangerPlugin", "Plugin Called");
    if (action.equals(ACTION)) {

        try {//from ww w.  j a v a 2s .  c o m
            // The first argument is the string containing the JSONObject
            // that we will have to parse out
            String messageString = arg1.getString(0);
            System.out.println(messageString);
            JSONObject messageObject = new JSONObject(messageString);
            String title = messageObject.getString(TITLE);
            String desription = messageObject.getString(DESCRIPTION);
            JSONArray gen_urls = messageObject.getJSONArray(GENERICURIS);
            JSONArray ios_urls = messageObject.getJSONArray(IPHONEURIS);
            JSONArray android_urls = messageObject.getJSONArray(ANDROIDURIS);
            String preview = messageObject.getString(PREVIEW);
            String fileLocation = messageObject.getString(FILELOCATION);
            String previewURL = messageObject.getString(PREVIEWURL);

            KikMessage message = new KikMessage(_appID);
            message.setText(desription);
            message.setTitle(title);

            if (fileLocation.length() != 0) {
                try {
                    File file = new File(fileLocation);
                    message.setFile(file);
                } catch (IOException e) {
                    return new PluginResult(PluginResult.Status.ERROR, "Error Attaching File");
                }
            }
            if (preview.length() != 0) {
                byte[] data_bytes = Base64.decode(preview, 0);
                message.setImage(
                        new BitmapDrawable(BitmapFactory.decodeByteArray(data_bytes, 0, data_bytes.length)));
            } else if (previewURL.length() != 0) {
                BitmapDrawable drawable = new BitmapDrawable(previewURL);
                message.setImage(drawable);
            }

            for (int i = 0; i < ios_urls.length(); i++) {
                message.setIphoneDownloadUri(ios_urls.getString(i));
            }

            for (int i = 0; i < gen_urls.length(); i++) {
                message.setFallbackUri(gen_urls.getString(i));
            }

            for (int i = 0; i < android_urls.length(); i++) {
                message.setAndroidDownloadUri(android_urls.getString(i));
            }

            try {
                final KikMessage _messageToSend = message;
                // These will be key value pairs that we will use
                this.ctx.runOnUiThread(new Runnable() {
                    public void run() {
                        KikClient.sendMessage(ctx, _messageToSend);
                    }
                });
                return new PluginResult(Status.OK);
            } catch (Exception e) {
                return new PluginResult(PluginResult.Status.ERROR, "Error passing message to UI thread");
            }

        } catch (JSONException e) {
            // If there is an issue parsing the JSON object then
            // we will return a bad result
            return new PluginResult(PluginResult.Status.ERROR,
                    "Invalid JSON input, expected JSONObject as first item");
        }
        // If we want to initialize the context
    } else if (action.equals(INIT_ACTION)) {
        try {
            String appID = arg1.getString(2);
            // We just want to take the AppId from this
            _appID = appID;
            if (_appID.length() == 0) {
                return new PluginResult(PluginResult.Status.ERROR, "Invalid App ID");
            } else {
                return new PluginResult(PluginResult.Status.OK);
            }
        } catch (JSONException e) {
            // If there is an issue parsing the JSON object then
            // we will return a bad result
            return new PluginResult(PluginResult.Status.ERROR,
                    "Invalid JSON input, expected JSONObject as first item");
        }

    } else if (action.equals(HAS_MESSAGE)) {
        Intent i = this.ctx.getIntent();
        KikData data = KikClient.getDataFromIntent(i);
        if (data.getType() == KikData.TYPE_PICK || data.getType() == KikData.TYPE_VIEW) {
            // We will only write back the javascript 
            // if its a valid KikData object
            String output = "setTimeout(function() { KikAPIClient.message_ready( '" + SerializeKikData(data)
                    + "'); }, 0 );";
            super.sendJavascript(output);
        }
        return new PluginResult(PluginResult.Status.OK);
    }
    // This should not really occur
    return new PluginResult(PluginResult.Status.INVALID_ACTION, "INVALID COMMAND");
}

From source file:no.digipost.android.authentication.OAuth.java

private static void verifyAuthentication(final String id_token, final Context context)
        throws DigipostApiException {
    String split_by = ".";
    int splitindex = id_token.indexOf(split_by);

    String signature_enc = id_token.substring(0, splitindex);
    String token_value_enc = id_token.substring(splitindex + split_by.length(), id_token.length());
    String signature_dec = new String(Base64.decode(signature_enc.getBytes(), Base64.DEFAULT));

    if (!encryptHmacSHA256(token_value_enc).equals(signature_dec)) {
        throw new DigipostApiException(context.getString(R.string.error_digipost_api));
    }//from w  w  w. j  ava2s.co  m

    TokenValue data = (TokenValue) JSONUtilities.processJackson(TokenValue.class,
            new String(Base64.decode(token_value_enc.getBytes(), Base64.DEFAULT)));
    String aud = data.getAud();

    if (!aud.equals(Secret.CLIENT_ID)) {
        throw new DigipostApiException(context.getString(R.string.error_digipost_api));
    }
}

From source file:com.microsoft.graph.connect.AuthenticationManager.java

public JSONObject getClaims(String idToken) {
    JSONObject retValue = null;/*w w  w .  ja v a 2 s  .  c o  m*/
    String payload = idToken.split("[.]")[1];

    try {
        // The token payload is in the 2nd element of the JWT
        String jsonClaims = new String(Base64.decode(payload, Base64.DEFAULT), "UTF-8");
        retValue = new JSONObject(jsonClaims);
    } catch (JSONException | IOException e) {
        Log.e(TAG, "Couldn't decode id token: " + e.getMessage());
    }
    return retValue;
}

From source file:com.andernity.launcher2.InstallShortcutReceiver.java

private static ArrayList<PendingInstallShortcutInfo> getAndClearInstallQueue(SharedPreferences sharedPrefs) {
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (strings == null) {
            return new ArrayList<PendingInstallShortcutInfo>();
        }/*from   w  w  w.  j a va  2s .  com*/
        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("InstallShortcutReceiver", "Exception reading shortcut to add: " + e);
            } catch (java.net.URISyntaxException e) {
                Log.d("InstallShortcutReceiver", "Exception reading shortcut to add: " + e);
            }
        }
        sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>()).commit();
        return infos;
    }
}

From source file:mobisocial.musubi.identity.AphidIdentityProvider.java

public AphidIdentityProvider(Context context) {
    mContext = context;//from   w  w w.  jav a 2s .c  o  m
    mEncryptionScheme = new IBEncryptionScheme(Base64.decode(ENCRYPTION_PUBLIC_PARAMETERS, Base64.DEFAULT));
    mSignatureScheme = new IBSignatureScheme(Base64.decode(SIGNATURE_PUBLIC_PARAMETERS, Base64.DEFAULT));
    mIdentitiesManager = new IdentitiesManager(App.getDatabaseSource(mContext));
    mPendingIdentityManager = new PendingIdentityManager(App.getDatabaseSource(mContext));
    mKnownTokens = new HashMap<Pair<Authority, String>, String>();
}

From source file:br.com.thinkti.android.filechooserfrag.fragFileChooserQuizlet.java

public void initfragFileChooserQuizlet(final MainActivity main, final String username,
        final String searchPhrase) {
    this.username = username;
    this.searchPhrase = searchPhrase;
    this._main = main;
    //String passwd = lib.InputBox(_main,"password","password","",false).input;
    QUIZLET_CLIENT_ID = new String(Base64.decode(Data.QuizletClientID, Base64.DEFAULT));
    browseApiUrl = "https://api.quizlet.com/2.0/search/sets?client_id=" + QUIZLET_CLIENT_ID
            + "&time_format=fuzzy_date";
    getSetApiUrl = "https://api.quizlet.com/2.0/sets?client_id=" + QUIZLET_CLIENT_ID + "&set_ids=";
    blnAdapterInvalid = true;//from  ww w .  j a v a2  s . c  o m
}