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:android.webkit.cts.TestWebServer.java

/**
 * Sets a base64 encoded response to be returned when a particular request path is passed
 * in (with the option to specify additional headers).
 *
 * @param requestPath The path to respond to.
 * @param base64EncodedResponse The response body that is base64 encoded. The actual server
 *                              response will the decoded binary form.
 * @param responseHeaders Any additional headers that should be returned along with the
 *                        response (null is acceptable).
 * @return The full URL including the path that should be requested to get the expected
 *         response./*from  ww  w  . ja  v a2  s.com*/
 */
public String setResponseBase64(String requestPath, String base64EncodedResponse,
        List<Pair<String, String>> responseHeaders) {
    return setResponseInternal(requestPath, Base64.decode(base64EncodedResponse, Base64.DEFAULT),
            responseHeaders, null, RESPONSE_STATUS_NORMAL);
}

From source file:nl.creativeskills.cordova.imageresize.ImageResize.java

@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
    PluginResult result = null;//from w  ww .  j  a  v a2 s .c  o m
    LOG.d(TAG, action.toString());
    LOG.d(TAG, TAG + ": " + Environment.getDataDirectory().toString());

    JSONObject params;
    String imageData;
    String imageDataType;
    String format;
    Bitmap bmp;
    try {
        //parameters (forst object of the json array)
        params = data.getJSONObject(0);
        //image data, either base64 or url
        imageData = params.getString("data");
        //which data type is that, defaults to base64
        imageDataType = params.has("imageDataType") ? params.getString("imageDataType")
                : DEFAULT_IMAGE_DATA_TYPE;
        LOG.d(TAG, action.toString() + ".imageDataType: " + imageDataType + ": "
                + params.getString("imageDataType"));
        //which format should be used, defaults to jpg
        format = params.has("format") ? params.getString("format") : DEFAULT_FORMAT;
        //create the Bitmap object, needed for all functions
        bmp = getBitmap(imageData, imageDataType);

    } catch (JSONException e) {
        LOG.d(TAG, action.toString() + ": " + e.getMessage());
        callbackContext.sendPluginResult(new PluginResult(Status.JSON_EXCEPTION, e.getMessage()));
        return false;
    } catch (IOException e) {
        LOG.d(TAG, action.toString() + ": " + e.getMessage());
        callbackContext.sendPluginResult(new PluginResult(Status.ERROR, e.getMessage()));
        return false;
    }
    //resize the image
    if (action.equals("resizeImage")) {
        try {
            LOG.d(TAG, "action.equals(" + action.toString() + ")");
            double widthFactor;
            double heightFactor;

            //compression quality
            int quality = params.getInt("quality");

            //Pixels or Factor resize
            String resizeType = params.getString("resizeType");

            //Get width and height parameters
            double width = params.getDouble("width");
            double height = params.getDouble("height");

            //return object
            JSONObject res = new JSONObject();

            LOG.d(TAG, "action.equals(" + action.toString() + "): params converted");

            if (resizeType.equals(RESIZE_TYPE_PIXEL)) {
                widthFactor = width / ((double) bmp.getWidth());
                heightFactor = height / ((double) bmp.getHeight());
            } else {
                widthFactor = width;
                heightFactor = height;
            }

            LOG.d(TAG, "action.equals(" + action.toString() + "): start resize");

            Bitmap resized = getResizedBitmap(bmp, (float) widthFactor, (float) heightFactor);

            if (imageDataType.equals(IMAGE_DATA_TYPE_BASE64)) {

                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                if (format.equals(FORMAT_PNG)) {
                    resized.compress(Bitmap.CompressFormat.PNG, quality, baos);
                } else {
                    resized.compress(Bitmap.CompressFormat.JPEG, quality, baos);
                }

                byte[] b = baos.toByteArray();
                String returnString = Base64.encodeToString(b, Base64.DEFAULT);

                res.put("imageData", returnString);

                LOG.d(TAG, "action.equals(" + action.toString() + "):base64 encode the resized Image");
            } else {
                // Obligatory Parameters, throw JSONException if not found
                String filename = params.getString("filename");
                //filename = (filename.contains(".")) ? filename : filename + "." + format;
                String directory = params.getString("directory");
                if (directory.startsWith("file:")) {
                    directory = directory.replace("file://", "");
                } else {
                    directory = directory.startsWith("/") ? directory : "/" + directory;
                    directory = Environment.getExternalStorageDirectory().toString() + directory;
                }

                LOG.d(TAG, "action.equals(" + action.toString() + "): resized Image and save to " + directory
                        + filename);

                OutputStream outStream;
                //store the file locally using the external storage directory
                File file = new File(directory, filename);

                try {
                    outStream = new FileOutputStream(file);
                    if (format.equals(FORMAT_PNG)) {
                        bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream);
                    } else {
                        bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
                    }
                    outStream.flush();
                    outStream.close();

                    res.put("url", "file://" + file.getAbsolutePath());
                    res.put("size", file.length());

                } catch (IOException e) {
                    result = new PluginResult(Status.ERROR, e.getMessage());
                    callbackContext.sendPluginResult(result);

                    return false;
                }
            }

            res.put("width", resized.getWidth());
            res.put("height", resized.getHeight());

            LOG.d(TAG, action.toString() + ": Should be successfull");

            result = new PluginResult(Status.OK, res);
            callbackContext.sendPluginResult(result);

            return true;
        } catch (JSONException e) {
            LOG.d(TAG, action.toString() + ": " + e.getMessage());
            result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
            callbackContext.sendPluginResult(result);

            return false;
        }
    } else if (action.equals("imageSize")) {
        try {

            JSONObject res = new JSONObject();
            res.put("width", bmp.getWidth());
            res.put("height", bmp.getHeight());

            result = new PluginResult(Status.OK, res);
            callbackContext.sendPluginResult(result);

            return true;
        } catch (JSONException e) {
            result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
            callbackContext.sendPluginResult(result);

            return false;
        }
    } else if (action.equals("storeImage")) {
        try {
            // Obligatory Parameters, throw JSONException if not found
            String filename = params.getString("filename");
            filename = (filename.contains(".")) ? filename : filename + "." + format;
            String directory = params.getString("directory");
            directory = directory.startsWith("/") ? directory : "/" + directory;
            int quality = params.getInt("quality");

            OutputStream outStream;
            //store the file locally using the external storage directory
            File file = new File(Environment.getExternalStorageDirectory().toString() + directory, filename);
            try {
                outStream = new FileOutputStream(file);
                if (format.equals(FORMAT_PNG)) {
                    bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream);
                } else {
                    bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
                }
                outStream.flush();
                outStream.close();
                JSONObject res = new JSONObject();
                res.put("url", "file://" + file.getAbsolutePath());
                res.put("size", file.length());

                result = new PluginResult(Status.OK, res);
                callbackContext.sendPluginResult(result);

                return true;
            } catch (IOException e) {
                result = new PluginResult(Status.ERROR, e.getMessage());
                callbackContext.sendPluginResult(result);

                return false;
            }
        } catch (JSONException e) {
            result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
            callbackContext.sendPluginResult(result);

            return false;
        }
    } else if (action.equals("storePDF")) {
        try {
            // Obligatory Parameters, throw JSONException if not found
            String filename = params.getString("filename");
            filename = (filename.contains(".")) ? filename : filename + "." + format;
            String directory = params.getString("directory");
            directory = directory.startsWith("/") ? directory : "/" + directory;

            OutputStream outStream;
            //store the file locally using the external storage directory
            File file = new File(Environment.getExternalStorageDirectory().toString() + directory, filename);
            try {
                byte[] pdfAsBytes = Base64.decode(imageData.toString(), 0);
                outStream = new FileOutputStream(file);

                outStream.write(pdfAsBytes);
                outStream.flush();
                outStream.close();
                JSONObject res = new JSONObject();
                res.put("url", "file://" + file.getAbsolutePath());

                result = new PluginResult(Status.OK, res);
                callbackContext.sendPluginResult(result);

                return true;
            } catch (IOException e) {
                result = new PluginResult(Status.ERROR, e.getMessage());
                callbackContext.sendPluginResult(result);

                return false;
            }
        } catch (JSONException e) {
            result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
            callbackContext.sendPluginResult(result);

            return false;
        }
    } else {
        callbackContext.sendPluginResult(new PluginResult(Status.ERROR));

        return false;
    }

}

From source file:com.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java

/**
 * Given some data and a signature, uses the key pair stored in the Android Key Store to verify
 * that the data was signed by this application, using that key pair.
 * @param input The data to be verified.
 * @param signatureStr The signature provided for the data.
 * @return A boolean value telling you whether the signature is valid or not.
 *///w  ww . j a va 2s. c om
public boolean verifyData(String input, String signatureStr)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException,
        UnrecoverableEntryException, InvalidKeyException, SignatureException {
    byte[] data = input.getBytes();
    byte[] signature;
    // BEGIN_INCLUDE(decode_signature)

    // Make sure the signature string exists.  If not, bail out, nothing to do.

    if (signatureStr == null) {
        Log.w(TAG, "Invalid signature.");
        Log.w(TAG, "Exiting verifyData()...");
        return false;
    }

    try {
        // The signature is going to be examined as a byte array,
        // not as a base64 encoded string.
        signature = Base64.decode(signatureStr, Base64.DEFAULT);
    } catch (IllegalArgumentException e) {
        // signatureStr wasn't null, but might not have been encoded properly.
        // It's not a valid Base64 string.
        return false;
    }
    // END_INCLUDE(decode_signature)

    KeyStore ks = KeyStore.getInstance("AndroidKeyStore");

    // Weird artifact of Java API.  If you don't have an InputStream to load, you still need
    // to call "load", or it'll crash.
    ks.load(null);

    // Load the key pair from the Android Key Store
    KeyStore.Entry entry = ks.getEntry(mAlias, null);

    if (entry == null) {
        Log.w(TAG, "No key found under alias: " + mAlias);
        Log.w(TAG, "Exiting verifyData()...");
        return false;
    }

    if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
        Log.w(TAG, "Not an instance of a PrivateKeyEntry");
        return false;
    }

    // This class doesn't actually represent the signature,
    // just the engine for creating/verifying signatures, using
    // the specified algorithm.
    Signature s = Signature.getInstance(SecurityConstants.SIGNATURE_SHA256withRSA);

    // BEGIN_INCLUDE(verify_data)
    // Verify the data.
    s.initVerify(((KeyStore.PrivateKeyEntry) entry).getCertificate());
    s.update(data);
    return s.verify(signature);
    // END_INCLUDE(verify_data)
}

From source file:jog.my.memory.gcm.ServerUtilities.java

public static Bitmap convertStringRepToPhoto(String s) {
    byte[] b = Base64.decode(s, Base64.DEFAULT);
    ByteArrayInputStream bis = new ByteArrayInputStream(b);
    Bitmap bmp = BitmapFactory.decodeStream(bis);
    return bmp;//from   w  w  w. j  a va  2s.co  m
}

From source file:com.cyanogenmod.account.util.CMAccountUtils.java

public static byte[] getHmacSecret(AccountManager accountManager, Account account) {
    if (account == null) {
        if (CMAccount.DEBUG)
            Log.d(TAG, "No CMAccount configured!");
        return null;
    }/*from   ww  w  .  j  a  v a 2 s.  c o m*/
    return Base64.decode(accountManager.getUserData(account, CMAccount.ACCOUNT_EXTRA_HMAC_SECRET),
            Base64.NO_WRAP);
}

From source file:de.appplant.cordova.emailcomposer.EmailComposerImpl.java

/**
 * The URI for a base64 encoded content.
 *
 * @param content//from   w w  w. ja  v a2s .c o  m
 * The given base64 encoded content.
 * @param ctx
 * The application context.
 * @return
 * The URI including the given content.
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
private Uri getUriForBase64Content(String content, Context ctx) {
    String resName = content.substring(content.indexOf(":") + 1, content.indexOf("//"));
    String resData = content.substring(content.indexOf("//") + 2);
    File dir = ctx.getExternalCacheDir();
    byte[] bytes;

    try {
        bytes = Base64.decode(resData, 0);
    } catch (Exception ignored) {
        Log.e("EmailComposer", "Invalid Base64 string");
        return Uri.EMPTY;
    }

    if (dir == null) {
        Log.e("EmailComposer", "Missing external cache dir");
        return Uri.EMPTY;
    }

    String storage = dir.toString() + ATTACHMENT_FOLDER;
    File file = new File(storage, resName);

    new File(storage).mkdir();

    try {
        FileOutputStream outStream = new FileOutputStream(file);

        outStream.write(bytes);
        outStream.flush();
        outStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return Uri.fromFile(file);
}

From source file:com.ledger.android.u2f.bridge.MainActivity.java

private U2FContext parseU2FContextSign(JSONObject json) {
    try {/*from  w  w  w  . j  a  va2 s  .co m*/
        String appId = json.getString(TAG_JSON_APPID);
        byte[] challenge = Base64.decode(json.getString(TAG_JSON_CHALLENGE), Base64.URL_SAFE);
        int requestId = json.getInt(TAG_JSON_REQUESTID);
        JSONArray array = json.getJSONArray(TAG_JSON_REGISTERED_KEYS);
        Vector<byte[]> keyHandles = new Vector<byte[]>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject keyHandleItem = array.getJSONObject(i);
            if (!keyHandleItem.getString(TAG_JSON_VERSION).equals(VERSION_U2F_V2)) {
                Log.e(TAG, "Invalid handle version");
                return null;
            }
            byte[] keyHandle = Base64.decode(keyHandleItem.getString(TAG_JSON_KEYHANDLE), Base64.URL_SAFE);
            keyHandles.add(keyHandle);
        }
        return new U2FContext(appId, challenge, keyHandles, requestId, true);
    } catch (JSONException e) {
        Log.e(TAG, "Error decoding request");
        return null;
    }
}

From source file:org.telegram.android.MessagesController.java

public MessagesController() {
    ImageLoader.getInstance();/*from  ww  w  .j  a  va 2s. co  m*/
    MessagesStorage.getInstance();
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidUpload);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailUpload);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByServer);
    addSupportUser();
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications",
            Activity.MODE_PRIVATE);
    enableJoined = preferences.getBoolean("EnableContactJoined", true);

    preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig",
            Activity.MODE_PRIVATE);
    maxGroupCount = preferences.getInt("maxGroupCount", 200);
    maxBroadcastCount = preferences.getInt("maxBroadcastCount", 100);
    groupBigSize = preferences.getInt("groupBigSize", 10);
    fontSize = preferences.getInt("fons_size", AndroidUtilities.isTablet() ? 18 : 16);
    String disabledFeaturesString = preferences.getString("disabledFeatures", null);
    if (disabledFeaturesString != null && disabledFeaturesString.length() != 0) {
        try {
            byte[] bytes = Base64.decode(disabledFeaturesString, Base64.DEFAULT);
            if (bytes != null) {
                SerializedData data = new SerializedData(bytes);
                int count = data.readInt32(false);
                for (int a = 0; a < count; a++) {
                    TLRPC.TL_disabledFeature feature = TLRPC.TL_disabledFeature.TLdeserialize(data,
                            data.readInt32(false), false);
                    if (feature != null && feature.feature != null && feature.description != null) {
                        disabledFeatures.add(feature);
                    }
                }
            }
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    }
}

From source file:com.phonemetra.account.util.AccountUtils.java

public static byte[] getHmacSecret(AccountManager accountManager, Account account) {
    if (account == null) {
        if (Account.DEBUG)
            Log.d(TAG, "No Account configured!");
        return null;
    }/*  w  w  w  .  ja  v  a2 s.co  m*/
    return Base64.decode(accountManager.getUserData(account, Account.ACCOUNT_EXTRA_HMAC_SECRET),
            Base64.NO_WRAP);
}

From source file:nl.creativeskills.cordova.imageresize.ImageResize.java

private Bitmap getBitmap(String imageData, String imageDataType) throws IOException {
    Bitmap bmp;/*from w w  w. ja v  a 2s  .  co  m*/
    LOG.d(TAG, "getBitmap called: imageDataType: " + imageDataType);
    if (imageDataType.equals(IMAGE_DATA_TYPE_BASE64)) {
        LOG.d(TAG, IMAGE_DATA_TYPE_BASE64 + " called");
        byte[] blob = Base64.decode(imageData, Base64.DEFAULT);
        LOG.d(TAG, IMAGE_DATA_TYPE_BASE64 + " still going");
        bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);
        LOG.d(TAG, IMAGE_DATA_TYPE_BASE64 + " still going 2");
    } else {

        if (imageData.startsWith("file:")) {
            imageData = imageData.replace("file://", "");
        } else {
            imageData = imageData.startsWith("/") ? imageData : "/" + imageData;
            imageData = Environment.getExternalStorageDirectory().toString() + imageData;
        }

        LOG.d(TAG, "imageFile: " + imageData);

        File imagefile = new File(imageData);
        FileInputStream fis = new FileInputStream(imagefile);
        bmp = BitmapFactory.decodeStream(fis);
    }

    return bmp;
}