Example usage for android.util Base64 encode

List of usage examples for android.util Base64 encode

Introduction

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

Prototype

public static byte[] encode(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated byte[] with the result.

Usage

From source file:org.apache.cordova.core.FileUtils.java

/**
 * Read the contents of a file./*  w  w  w  . java 2  s  .  c om*/
 * This is done in a background thread; the result is sent to the callback.
 *
 * @param filename          The name of the file.
 * @param start             Start position in the file.
 * @param end               End position to stop at (exclusive).
 * @param callbackContext   The context through which to send the result.
 * @param encoding          The encoding to return contents as.  Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets)
 * @param resultType        The desired type of data to send to the callback.
 * @return                  Contents of file.
 */
public void readFileAs(final String filename, final int start, final int end,
        final CallbackContext callbackContext, final String encoding, final int resultType) {
    this.cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            try {
                byte[] bytes = readAsBinaryHelper(filename, start, end);

                PluginResult result;
                switch (resultType) {
                case PluginResult.MESSAGE_TYPE_STRING:
                    result = new PluginResult(PluginResult.Status.OK, new String(bytes, encoding));
                    break;
                case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
                    result = new PluginResult(PluginResult.Status.OK, bytes);
                    break;
                case PluginResult.MESSAGE_TYPE_BINARYSTRING:
                    result = new PluginResult(PluginResult.Status.OK, bytes, true);
                    break;
                default: // Base64.
                    String contentType = FileHelper.getMimeType(filename, cordova);
                    byte[] base64 = Base64.encode(bytes, Base64.DEFAULT);
                    String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
                    result = new PluginResult(PluginResult.Status.OK, s);
                }

                callbackContext.sendPluginResult(result);
            } catch (FileNotFoundException e) {
                callbackContext
                        .sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR));
            } catch (IOException e) {
                Log.d(LOG_TAG, e.getLocalizedMessage());
                callbackContext
                        .sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
            }
        }
    });
}

From source file:com.cordova.photo.CameraLauncher.java

/**
 * Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript.
 *
 * @param bitmap/* w  w w .j  a  v a 2s .  co m*/
 */
public void processPicture(Bitmap bitmap) {
    ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
    try {
        if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) {
            byte[] code = jpeg_data.toByteArray();
            byte[] output = Base64.encode(code, Base64.NO_WRAP);
            String js_out = new String(output);
            this.callbackContext.success(js_out);
            js_out = null;
            output = null;
            code = null;
        }
    } catch (Exception e) {
        this.failPicture("Error compressing image.");
    }
    jpeg_data = null;
}

From source file:self.philbrown.droidQuery.AjaxOptions.java

/**
 * As a security feature, this class will not allow queries of authentication passwords. This
 * method will instead encode the security credentials (username and password) using
 * Base64-encryption, and return the encrypted data as a byte array.
 * @return the encrypted credentials//w  ww. j  av  a  2 s.  com
 * @see #username()
 * @see #password(String)
 */
public byte[] getEncodedCredentials() {
    StringBuilder auth = new StringBuilder();
    if (username != null) {
        auth.append(username);
    }
    if (password != null) {
        auth.append(":").append(password);
    }
    return Base64.encode(auth.toString().getBytes(), Base64.NO_WRAP);
}

From source file:csh.cryptonite.Cryptonite.java

public static String encrypt(String value, Context context) throws RuntimeException {

    try {/*  w w w. j  a va2  s  . co m*/
        final byte[] bytes = value != null ? value.getBytes("utf-8") : new byte[0];
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(jniFullPw().toCharArray()));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key,
                new PBEParameterSpec(Settings.Secure
                        .getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes("utf-8"),
                        20));
        return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), "utf-8");

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.remobile.file.FileUtils.java

/**
 * Read the contents of a file.//from   www .  j  a v  a  2s . com
 * This is done in a background thread; the result is sent to the callback.
 *
 * @param start             Start position in the file.
 * @param end               End position to stop at (exclusive).
 * @param callbackContext   The context through which to send the result.
 * @param encoding          The encoding to return contents as.  Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets)
 * @param resultType        The desired type of data to send to the callback.
 * @return                  Contents of file.
 */
public void readFileAs(final String srcURLstr, final int start, final int end,
        final CallbackContext callbackContext, final String encoding, final int resultType)
        throws MalformedURLException {
    try {
        LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
        Filesystem fs = this.filesystemForURL(inputURL);
        if (fs == null) {
            throw new MalformedURLException("No installed handlers for this URL");
        }

        fs.readFileAtURL(inputURL, start, end, new Filesystem.ReadFileCallback() {
            public void handleData(InputStream inputStream, String contentType) {
                try {
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    final int BUFFER_SIZE = 8192;
                    byte[] buffer = new byte[BUFFER_SIZE];

                    for (;;) {
                        int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);

                        if (bytesRead <= 0) {
                            break;
                        }
                        os.write(buffer, 0, bytesRead);
                    }

                    PluginResult result;
                    switch (resultType) {
                    case PluginResult.MESSAGE_TYPE_STRING:
                        result = new PluginResult(PluginResult.Status.OK, os.toString(encoding));
                        break;
                    case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
                        result = new PluginResult(PluginResult.Status.OK, os.toByteArray());
                        break;
                    case PluginResult.MESSAGE_TYPE_BINARYSTRING:
                        result = new PluginResult(PluginResult.Status.OK, os.toByteArray(), true);
                        break;
                    default: // Base64.
                        byte[] base64 = Base64.encode(os.toByteArray(), Base64.NO_WRAP);
                        String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
                        result = new PluginResult(PluginResult.Status.OK, s);
                    }

                    callbackContext.sendPluginResult(result);
                } catch (IOException e) {
                    Log.d(LOG_TAG, e.getLocalizedMessage());
                    callbackContext.sendPluginResult(
                            new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
                }
            }
        });

    } catch (IllegalArgumentException e) {
        throw new MalformedURLException("Unrecognized filesystem URL");
    } catch (FileNotFoundException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR));
    } catch (IOException e) {
        Log.d(LOG_TAG, e.getLocalizedMessage());
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
    }
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

private GBDeviceEvent[] decodeDictToJSONAppMessage(UUID uuid, ByteBuffer buf) throws JSONException {
    buf.order(ByteOrder.LITTLE_ENDIAN);
    byte dictSize = buf.get();
    if (dictSize == 0) {
        LOG.info("dict size is 0, ignoring");
        return null;
    }/*  w  ww  .ja  v a 2  s.c  o  m*/
    JSONArray jsonArray = new JSONArray();
    while (dictSize-- > 0) {
        JSONObject jsonObject = new JSONObject();
        Integer key = buf.getInt();
        byte type = buf.get();
        short length = buf.getShort();
        jsonObject.put("key", key);
        if (type == TYPE_CSTRING) {
            length--;
        }
        jsonObject.put("length", length);
        switch (type) {
        case TYPE_UINT:
            jsonObject.put("type", "uint");
            if (length == 1) {
                jsonObject.put("value", buf.get() & 0xff);
            } else if (length == 2) {
                jsonObject.put("value", buf.getShort() & 0xffff);
            } else {
                jsonObject.put("value", buf.getInt() & 0xffffffffL);
            }
            break;
        case TYPE_INT:
            jsonObject.put("type", "int");
            if (length == 1) {
                jsonObject.put("value", buf.get());
            } else if (length == 2) {
                jsonObject.put("value", buf.getShort());
            } else {
                jsonObject.put("value", buf.getInt());
            }
            break;
        case TYPE_BYTEARRAY:
        case TYPE_CSTRING:
            byte[] bytes = new byte[length];
            buf.get(bytes);
            if (type == TYPE_BYTEARRAY) {
                jsonObject.put("type", "bytes");
                jsonObject.put("value", new String(Base64.encode(bytes, Base64.NO_WRAP)));
            } else {
                jsonObject.put("type", "string");
                jsonObject.put("value", new String(bytes));
                buf.get(); // skip null-termination;
            }
            break;
        default:
            LOG.info("unknown type in appmessage, ignoring");
            return null;
        }
        jsonArray.put(jsonObject);
    }

    GBDeviceEventSendBytes sendBytesAck = null;
    if (mAlwaysACKPebbleKit) {
        // this is a hack we send an ack to the Pebble immediately because somebody said it helps some PebbleKit apps :P
        sendBytesAck = new GBDeviceEventSendBytes();
        sendBytesAck.encodedBytes = encodeApplicationMessageAck(uuid, last_id);
    }
    GBDeviceEventAppMessage appMessage = new GBDeviceEventAppMessage();
    appMessage.appUUID = uuid;
    appMessage.id = last_id & 0xff;
    appMessage.message = jsonArray.toString();
    return new GBDeviceEvent[] { appMessage, sendBytesAck };
}