Example usage for android.util Base64 DEFAULT

List of usage examples for android.util Base64 DEFAULT

Introduction

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

Prototype

int DEFAULT

To view the source code for android.util Base64 DEFAULT.

Click Source Link

Document

Default values for encoder/decoder flags.

Usage

From source file:org.akvo.flow.api.FlowApi.java

private String getAuthorization(String query) {
    String authorization = null;// www  .  jav a 2 s . c  o  m
    try {
        SecretKeySpec signingKey = new SecretKeySpec(API_KEY.getBytes(), "HmacSHA1");

        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        byte[] rawHmac = mac.doFinal(query.getBytes());

        authorization = Base64.encodeToString(rawHmac, Base64.DEFAULT);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, e.getMessage());
    } catch (InvalidKeyException e) {
        Log.e(TAG, e.getMessage());
    }

    return authorization;
}

From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java

@Override
public void open(@NonNull final Callback callback) {
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(mConsumerKey)
            .setOAuthConsumerSecret(mConsumerSecret).build();

    final Twitter instance = new TwitterFactory(configuration).getInstance();
    if (mAccessToken != null) {
        instance.setOAuthAccessToken(mAccessToken);
    }//www .  ja v  a  2s  .  c o  m

    doValidate(mAccessToken, instance).continueWithTask(new Continuation<User, Task<AccessToken>>() {
        @Override
        public Task<AccessToken> then(Task<User> task) throws Exception {
            if (task.isFaulted()) {
                SharedPreferences preferences = getActivity().getSharedPreferences("twitter",
                        Activity.MODE_PRIVATE);
                preferences.edit().clear().apply();

                mAccessToken = null;
                instance.setOAuthAccessToken(null);
                return doGetAuthenticationURL(instance)
                        .onSuccessTask(new Continuation<RequestToken, Task<Bundle>>() {
                            @Override
                            public Task<Bundle> then(Task<RequestToken> task) throws Exception {
                                return doDialogAuthentication(task.getResult());
                            }
                        }).onSuccessTask(new Continuation<Bundle, Task<AccessToken>>() {
                            @Override
                            public Task<AccessToken> then(Task<Bundle> task) throws Exception {
                                return doGetAccessToken(instance, task.getResult());
                            }
                        }).continueWith(new Continuation<AccessToken, AccessToken>() {
                            @Override
                            public AccessToken then(Task<AccessToken> task) throws Exception {
                                if (task.isFaulted()) {
                                    Log.d(BuildConfig.DEBUG_TAG, "Failed", task.getError());
                                    //                                Toast.makeText(getActivity(), task.getError().getMessage(), Toast.LENGTH_LONG).show();
                                    callback.onCancelled();
                                } else if (task.isCompleted()) {
                                    AccessToken accessToken = task.getResult();
                                    String serialized = Base64.encodeToString(
                                            SerializationUtils.serialize(accessToken), Base64.DEFAULT);

                                    SharedPreferences preferences = getActivity()
                                            .getSharedPreferences("twitter", Activity.MODE_PRIVATE);
                                    preferences.edit().putString("access_token_str", serialized).apply();
                                    callback.onSessionOpened(accessToken);
                                    mAccessToken = accessToken;

                                    return accessToken;
                                }

                                return null;
                            }
                        });
            } else {
                callback.onSessionOpened(mAccessToken);
                return Task.forResult(mAccessToken);
            }
        }
    });
}

From source file:com.codebutler.farebot.card.felica.FelicaCard.java

public static FelicaCard fromXml(byte[] tagId, Date scannedAt, Element element) {
    Element systemsElement = (Element) element.getElementsByTagName("systems").item(0);

    NodeList systemElements = systemsElement.getElementsByTagName("system");

    FeliCaLib.IDm idm = new FeliCaLib.IDm(
            Base64.decode(element.getElementsByTagName("idm").item(0).getTextContent(), Base64.DEFAULT));
    FeliCaLib.PMm pmm = new FeliCaLib.PMm(
            Base64.decode(element.getElementsByTagName("pmm").item(0).getTextContent(), Base64.DEFAULT));

    FelicaSystem[] systems = new FelicaSystem[systemElements.getLength()];

    for (int x = 0; x < systemElements.getLength(); x++) {
        Element systemElement = (Element) systemElements.item(x);

        int systemCode = Integer.parseInt(systemElement.getAttribute("code"));

        Element servicesElement = (Element) systemElement.getElementsByTagName("services").item(0);

        NodeList serviceElements = servicesElement.getElementsByTagName("service");

        FelicaService[] services = new FelicaService[serviceElements.getLength()];

        for (int y = 0; y < serviceElements.getLength(); y++) {
            Element serviceElement = (Element) serviceElements.item(y);
            int serviceCode = Integer.parseInt(serviceElement.getAttribute("code"));

            Element blocksElement = (Element) serviceElement.getElementsByTagName("blocks").item(0);

            NodeList blockElements = blocksElement.getElementsByTagName("block");

            FelicaBlock[] blocks = new FelicaBlock[blockElements.getLength()];

            for (int z = 0; z < blockElements.getLength(); z++) {
                Element blockElement = (Element) blockElements.item(z);
                byte address = Byte.parseByte(blockElement.getAttribute("address"));
                byte[] data = Base64.decode(blockElement.getTextContent(), Base64.DEFAULT);

                blocks[z] = new FelicaBlock(address, data);
            }// www .  ja  v a2  s .  co m

            services[y] = new FelicaService(serviceCode, blocks);
        }

        systems[x] = new FelicaSystem(systemCode, services);
    }

    return new FelicaCard(tagId, scannedAt, idm, pmm, systems);
}

From source file:com.orange.oidc.secproxy_service.MySecureProxy.java

public String getClientSecretBasic() {

    String bearer = (SECURE_PROXY_client_id + ":" + SECURE_PROXY_secret);
    return Base64.encodeToString(bearer.getBytes(), Base64.DEFAULT);
}

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

/**
 * Decrypts a message.//from w  w  w  .j  av a2 s .  c  om
 * @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.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: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./*from   w ww .j  a  va  2 s .co  m*/
 */
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: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  .  ja  v a  2  s. c  om*/
            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.ntsync.android.sync.client.ClientKeyHelper.java

/**
 * /*from   w ww  .  j av a2s  .c om*/
 * @param account
 * @param accountManager
 * @param keyPwd
 *            Password for Key
 * @param salt
 * @param existingSalt
 * @param pwdCheck
 *            null for new Key otherwise used to Check if it is the right
 *            Password.
 * @return
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 */
public static SecretKey createKey(Account account, AccountManager accountManager, String keyPwd, byte[] salt,
        boolean existingSalt, byte[] pwdCheck) throws InvalidKeyException, UnsupportedEncodingException {

    KeyGenerator keyGen = new KeyGenerator();
    SecretKey skey = keyGen.generateKey(keyPwd, salt);

    byte[] raw = skey.getEncoded();
    String keyValue = Base64.encodeToString(raw, Base64.DEFAULT);
    String saltStr = Base64.encodeToString(salt, Base64.DEFAULT);

    assert (existingSalt ? pwdCheck != null : true);

    byte[] check = pwdCheck;
    if (existingSalt && pwdCheck != null) {
        // Validate new Passwort
        validateKey(check, skey);

    } else if (!existingSalt) {
        check = createPwdCheck(skey);
    }
    String pwdCheckStr = check != null ? Base64.encodeToString(check, Base64.DEFAULT) : null;

    accountManager.setUserData(account, PRIVATE_KEY_SALTSAVED, existingSalt ? "true" : "false");
    accountManager.setUserData(account, PRIVATE_KEYSALT, saltStr);
    accountManager.setUserData(account, PRIVATE_PWDCHECK, pwdCheckStr);
    accountManager.setUserData(account, PRIVATE_PWD, keyPwd);
    accountManager.setUserData(account, PRIVATE_KEY, keyValue);
    return skey;
}

From source file:com.prad.yahooweather.YahooWeatherActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
        pendingAction = PendingAction.valueOf(name);
    }/*www  . j  a v a 2 s .c om*/

    setContentView(R.layout.weather_layout);
    mImageView = (ImageView) findViewById(R.id.feed_image);

    // Add code to print out the key hash
    try {
        PackageInfo info = getPackageManager().getPackageInfo("com.prad.yahooweather",
                PackageManager.GET_SIGNATURES);
        // 9Q4TYYAtIO1mNDFa+Y57Ausm5lE=

        // Yahoo Weather
        // App ID: 612655528781332
        // App Secret: c6ae83d7cf1aeba1c01045bd37f1db31

        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (Exception e) {

    }

    View f = (View) findViewById(R.id.resultTable);
    f.setVisibility(View.GONE);

    searchText = (EditText) findViewById(R.id.searchText);
    searchButton = (Button) findViewById(R.id.search_button);
    radioGroup = (RadioGroup) findViewById(R.id.searchTypeRadioGroup);

    mImageView.setLongClickable(true);
    mImageView.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            Session session = Session.getActiveSession();
            if (session != null) {
                session.closeAndClearTokenInformation();
            } else {
                Session session2 = Session.openActiveSession(YahooWeatherActivity.this, false, null);
                if (session2 != null)
                    session2.closeAndClearTokenInformation();
            }

            return true;
        }
    });

    searchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String searchType = "";
            boolean isValidInput = false;
            hideKeyboard();
            String searchString = searchText.getText().toString();

            if (searchString == null || "".equals(searchString)) {
                Toast.makeText(YahooWeatherActivity.this, "Text field is empty. Please enter zip or city name.",
                        Toast.LENGTH_SHORT).show();
            } else {

                if (checkIfValidZip(searchString)) {
                    searchType = "zip";
                    isValidInput = true;
                } else {
                    if (checkIfValidCity(searchString)) {
                        searchType = "city";
                        isValidInput = true;
                    }
                }

            }

            if (isValidInput) {

                new GetJSON().execute(searchString, searchType, getTempTyep());
            }

        }
    });

    postStatusUpdateButton = (TextView) findViewById(R.id.current_weather);
    postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            pendingAction = PendingAction.CURRENT_WEATHER;

            showFacebookshareDialog("Post Current Weather");

        }
    });

    postPhotoButton = (TextView) findViewById(R.id.weather_forecast);
    postPhotoButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            pendingAction = PendingAction.WEATHER_FORECAST;

            showFacebookshareDialog("Post Weather Forecast");

        }
    });

    canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,
            FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
    canPresentShareDialog = true;
}