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.hackeruproj.android.havatzfit.general_utilities.GenUtils.java

public static Bitmap string2Bitmap(String encodeString) {
    try {//  w  w w. ja  v a  2s.co m
        byte[] encodeByte = Base64.decode(encodeString, Base64.DEFAULT);
        Bitmap mBitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        return mBitmap;
    } catch (Exception e) {
        e.getMessage();
        return null;
    }
}

From source file:com.lillicoder.newsblurry.feeds.FeedParser.java

/**
 * Decodes the given base-64 favicon string into a {@link Favicon}.
 * @param encodedFavicon Base-64 encoded favicon to decode.
 * @return Decoded {@link Favicon},//from  w w  w.j a v a 2 s .  c  o m
 *          <code>null</code> if the encoded string could not be decoded.
 */
private Favicon decodeFavicon(String encodedFavicon) {
    Favicon favicon = null;

    if (!TextUtils.isEmpty(encodedFavicon)) {
        try {
            byte[] rawFavicon = Base64.decode(encodedFavicon, Base64.DEFAULT);
            Bitmap faviconImage = BitmapFactory.decodeByteArray(rawFavicon, 0, rawFavicon.length);

            if (faviconImage != null)
                favicon = new Favicon(faviconImage);
        } catch (IllegalArgumentException e) {
            Log.w(TAG, WARNING_FAILED_TO_DECODE_FAVICON, e);
        }
    }

    return favicon;
}

From source file:org.openmidaas.app.common.Utils.java

public static String getAttributeDetailsLabel(AbstractAttribute<?> attribute) {
    String message = "Name: " + attribute.getName() + "\n" + "Value: " + attribute.toString() + "\n";
    String[] jwsParams = null;/*from   w w w . j  a  v a  2s.  co  m*/
    JSONObject object = null;
    String audience = "";
    String issuer = "";
    String subject = "";
    if (attribute.getSignedToken() != null) {
        jwsParams = attribute.getSignedToken().split("\\.");
        try {
            object = new JSONObject(new String(Base64.decode(jwsParams[1], Base64.NO_WRAP), "UTF-8"));
            if (object != null) {
                if (object.getString("aud") != null)
                    audience = object.getString("aud");
                message += "Audience: " + audience + "\n";

                if (object.getString("iss") != null)
                    issuer = object.getString("iss");
                message += "Issuer: " + issuer + "\n";

                if (object.getString("sub") != null)
                    subject = object.getString("sub");
                message += "Subject: " + subject + "\n";

                message += "Signature: " + jwsParams[2];
            }
        } catch (Exception e) {
        }
    }
    return message;
}

From source file:com.samuelcastro.cordova.InstagramSharePlugin.java

private void shareImage(String imageString, String captionString) {
    if (imageString != null && imageString.length() > 0) {
        byte[] imageData = Base64.decode(imageString, 0);

        File file = null;//w  w w .  j  a  v a2s .  c om
        FileOutputStream os = null;

        File parentDir = this.webView.getContext().getExternalFilesDir(null);
        File[] oldImages = parentDir.listFiles(OLD_IMAGE_FILTER);
        for (File oldImage : oldImages) {
            oldImage.delete();
        }

        try {
            file = File.createTempFile("instagram", ".png", parentDir);
            os = new FileOutputStream(file, true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            os.write(imageData);
            os.flush();
            os.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file));
        shareIntent.putExtra(Intent.EXTRA_TEXT, captionString);
        shareIntent.setPackage("com.instagram.android");

        this.cordova.startActivityForResult((CordovaPlugin) this, shareIntent, 12345);

    } else {
        this.cbContext.error("Expected one non-empty string argument.");
    }
}

From source file:ca.uwaterloo.magic.goodhikes.ProfileActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);// w w w .j  a v a 2 s .  c  om
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    /** Define variables **/
    userManager = new UserManager(getApplicationContext());
    user = userManager.getUser();
    profile_image = (ImageView) findViewById(R.id.profile_image);
    profile_user_name = (TextView) findViewById(R.id.profile_user_name);
    profile_email = (TextView) findViewById(R.id.profile_email);
    upload_image = (Button) findViewById(R.id.upload_picture);

    profile_user_name.setText(user.getUsername());
    profile_email.setText(user.getEmail());
    image_str = user.getImage();
    if (image_str != "") {
        /** decode image string and set profile image **/
        byte[] image_arr = Base64.decode(image_str, 0);
        profile_image.setImageBitmap(BitmapFactory.decodeByteArray(image_arr, 0, image_arr.length));

    }

    upload_image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            uploadProfileImage();

        }
    });
}

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

/**
 * Encrypts a message.//from w  w w .  j  a  va2s.  co m
 * @param args Arguments: data, publicKey[, privateKey]
 * @param callback Callback
 */
public static void encrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        PRNGProvider.init(); // Ensure OpenSSL fix

        // Get the arguments
        String data = args.getString(0);
        String pub = args.getString(1);
        String priv = null;
        if (args.length() == 3) {
            priv = args.getString(2);
        }
        String sig = null;

        // Convert everything into byte arrays
        byte[] dataRaw = data.getBytes("utf-8");
        byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);

        // Generate random AES key and IV
        byte[] aesKey = new byte[AES_BYTES];
        new SecureRandom().nextBytes(aesKey);
        byte[] aesIv = new byte[16]; // Block size
        new SecureRandom().nextBytes(aesIv);
        Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));

        // Encrypt data with AES
        byte[] encData = c.doFinal(dataRaw);

        // Encrypt aes data with RSA
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, kf.generatePublic(publicKeySpec));
        c.update(aesKey);
        c.update(aesIv);
        byte[] encKey = c.doFinal();

        // Concatenate and transform
        byte[] encRaw = new byte[encKey.length + encData.length];
        System.arraycopy(encKey, 0, encRaw, 0, encKey.length);
        System.arraycopy(encData, 0, encRaw, encKey.length, encData.length);
        encKey = null;
        encData = null;
        String enc = new String(Base64.encode(encRaw /* needed for sign */, Base64.NO_WRAP), "utf-8");

        // Sign
        if (priv != null) {
            // Fail on error (no try-catch)
            byte[] privRaw = Base64.decode(stripKey(priv), Base64.DEFAULT);
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privRaw);
            Signature s = Signature.getInstance("SHA1withRSA", "BC");
            s.initSign(kf.generatePrivate(privateKeySpec));
            s.update(encRaw);
            sig = new String(Base64.encode(s.sign(), Base64.NO_WRAP), "utf-8");
        }

        JSONArray res = new JSONArray();
        res.put(enc);
        res.put(sig);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Encrypt error: " + ex.getMessage(), ex);
        callback.error(ex);
    }
}

From source file:org.apache.cordova.crypt.Crypt.java

public String decrypt(String data, String privatekey) throws IllegalBlockSizeException, BadPaddingException,
        InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
    privatekey = privatekey.replaceAll("(-+BEGIN PRIVATE KEY-+\\r?\\n|-+END PRIVATE KEY-+\\r?\\n?)", "");
    byte[] dataCipher = Base64.decode(data, Base64.DEFAULT);

    try {//from   w ww  .  j  a  va2 s . c  om
        byte[] privatekeyRaw = Base64.decode(privatekey, Base64.DEFAULT);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privatekeyRaw);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PrivateKey priv = fact.generatePrivate(keySpec);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, priv);
        byte[] decrypted = cipher.doFinal(dataCipher);
        Log.w("CRYPT", new String(decrypted, "UTF-8"));

        return new String(decrypted, "UTF-8");

    } catch (Exception e) {
        Log.w("CRYPT", e);
        return null;
    }

}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

@Override
public Pair<JSONObject, byte[]> splitRaw(JSONObject json) {
    byte[] raw = Base64.decode(json.optString(DATA), Base64.DEFAULT);
    json.remove(DATA);//from   w  w w  .  j  a v  a 2 s  .c om
    return new Pair<JSONObject, byte[]>(json, raw);
}

From source file:eu.codeplumbers.cosi.db.models.Contact.java

public Contact(JSONObject contactJson) throws JSONException {
    if (contactJson.has("n"))
        setN(contactJson.getString("n"));
    else/*from  w w w. j av  a2s .  c  om*/
        setN("");

    if (contactJson.has("fn"))
        setFn(contactJson.getString("fn"));
    else
        setFn("");

    if (contactJson.has("revision")) {
        setRevision(contactJson.getString("revision"));
    } else {
        setRevision(DateUtils.formatDate(new Date().getTime()));
    }

    if (contactJson.has("tags") && !contactJson.getString("tags").equalsIgnoreCase("")) {
        setTags(contactJson.getJSONArray("tags").toString());
    } else {
        setTags(new JSONArray().toString());
    }

    setPhotoBase64("");
    setAnniversary("");

    if (contactJson.has("deviceId")) {
        setDeviceId(contactJson.getString("deviceId"));
    }

    if (contactJson.has("systemId")) {
        setSystemId(contactJson.getString("systemId"));
    }

    setRemoteId(contactJson.getString("_id"));

    if (contactJson.has("_attachments")) {
        JSONObject attachment = contactJson.getJSONObject("_attachments");

        setAttachments(attachment.toString());

        if (attachment.has("picture")) {
            JSONObject picture = attachment.getJSONObject("picture");
            String attachmentName = new String(
                    Base64.decode(picture.getString("digest").replace("md5-", ""), Base64.DEFAULT));
            Log.d("Contact", attachmentName);
        }
    }

    save();

    if (contactJson.has("datapoints")) {
        JSONArray datapoints = contactJson.getJSONArray("datapoints");

        for (int i = 0; i < datapoints.length(); i++) {
            JSONObject datapoint = datapoints.getJSONObject(i);
            String value = datapoint.getString("value");
            ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(this, value);

            if (contactDataPoint == null && !value.isEmpty()) {
                contactDataPoint = new ContactDataPoint();
                contactDataPoint.setPref(false);
                contactDataPoint.setType(datapoint.getString("type"));
                contactDataPoint.setValue(value);
                contactDataPoint.setName(datapoint.getString("name"));
                contactDataPoint.setContact(this);
                contactDataPoint.save();
            }
        }
    }

}

From source file:fragments.ContextFragment.java

@Override
public void onSharedPreferenceChanged(final SharedPreferences sharedPreference, final String key) {
    if (key.equals(App.SETTINGS_FIRST_NAME) || key.equals(App.SETTINGS_LAST_NAME)) {
        mFirstLastView/*from w  ww  .  j  a va2s .c  om*/
                .setText(getString(R.string.welcome, App.getPrefs().getString(App.SETTINGS_FIRST_NAME, ""),
                        App.getPrefs().getString(App.SETTINGS_LAST_NAME, "")));
    } else if (key.equals(App.SETTINGS_PLATFORM_NAME)) {
        ((AppActivity) getActivity()).refreshUI();
    } else if (key.equals(App.SETTINGS_OFFICIAL_CODE)) {
        mNomaView.setText(App.getPrefs().getString(key, ""));
    } else if (key.equals(App.SETTINGS_INSTITUTION_NAME)) {
        ((AppActivity) getActivity()).refreshUI();
    } else if (key.equals(App.SETTINGS_USER_IMAGE)) {
        String pic64 = App.getPrefs().getString(App.SETTINGS_USER_IMAGE, "");
        if (!pic64.equals("")) {
            byte[] pic = Base64.decode(pic64, Base64.DEFAULT);
            mUserPicture.setImageBitmap(BitmapFactory.decodeByteArray(pic, 0, pic.length));
        } else {
            mUserPicture.setImageResource(R.drawable.nopicture);
        }
    }
}