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:br.com.hotforms.FacebookHash.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return                  True if the action was valid, false otherwise.
 *//*from   ww w . java 2 s.  c o  m*/
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
        throws JSONException {
    Log.v(TAG, "Executing action: " + action);
    final Activity activity = this.cordova.getActivity();
    final Window window = activity.getWindow();

    if ("getHash".equals(action)) {
        try {
            String packageName = activity.getClass().getPackage().getName();
            PackageManager packageManager = activity.getPackageManager();
            PackageInfo info = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                String hash = Base64.encodeToString(md.digest(), Base64.DEFAULT);

                String result = String.format("{ FacebookHash : \"%s\", PackageName : \"%s\"}", hash.trim(),
                        packageName);
                callbackContext.success(result);
            }
        } catch (NameNotFoundException e) {
            callbackContext.error(e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            callbackContext.error(e.getMessage());
        }
        return true;
    }

    return false;
}

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

public JSONObject mergeRaw(JSONObject objData, byte[] raw) {
    try {//from  w w  w.ja  v  a 2s  .  c o m
        if (raw != null)
            objData = objData.put(DATA, Base64.encodeToString(raw, Base64.DEFAULT));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return objData;
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle arguments = getArguments();/*from w  ww .j ava2  s .c  o  m*/

    if (arguments == null) {
        throw new IllegalArgumentException("arguments is not set");
    }

    mConsumerKey = arguments.getString("consumerKey");
    mConsumerSecret = arguments.getString("consumerSecret");
    if (TextUtils.isEmpty(mConsumerKey) || TextUtils.isEmpty(mConsumerSecret)) {
        throw new IllegalArgumentException("both consumerKey and consumerSecret is required");
    }

    SharedPreferences preferences = getActivity().getSharedPreferences("twitter", Activity.MODE_PRIVATE);
    if (preferences.contains("access_token_str")) {
        String ats = preferences.getString("access_token_str", "");
        if (!TextUtils.isEmpty(ats)) {
            byte[] decode = Base64.decode(ats, Base64.DEFAULT);
            mAccessToken = SerializationUtils.deserialize(decode);
        }
    }

}

From source file:com.amazonaws.mobileconnectors.kinesis.kinesisrecorder.JSONRecordAdapter.java

/**
 * @param source the PutRecordRequest to that will be stored
 * @return JSONObject the json representation of the request
 *//*from w w  w  .  j av  a  2  s  .  c om*/
public JSONObject translateFromRecord(PutRecordRequest source) {
    if (null == source) {
        LOGGER.warn("The Record provided was null");
        return null;
    }
    if (source.getData() == null || source.getPartitionKey() == null || source.getPartitionKey().isEmpty()
            || source.getStreamName() == null || source.getStreamName().isEmpty()) {
        throw new AmazonClientException("RecordRequests must specify a partition key, stream name, and data");
    }
    if (!source.getData().hasArray()) {
        throw new AmazonClientException("ByteBuffer must be based on array for proper storage");
    }
    final JSONObject recordJson = new JSONObject();
    try {
        recordJson.put(DATA_FIELD_KEY, Base64.encodeToString(source.getData().array(), Base64.DEFAULT));
        recordJson.put(STREAM_NAME_FIELD, source.getStreamName());
        recordJson.put(PARTITION_KEY_FIELD, source.getPartitionKey());
        recordJson.putOpt(EXPLICIT_HASH_FIELD, source.getExplicitHashKey());
        recordJson.putOpt(SEQUENCE_NUMBER_FIELD, source.getSequenceNumberForOrdering());
    } catch (final JSONException e) {
        throw new AmazonClientException("Unable to convert KinesisRecord to JSON " + e.getMessage());
    }

    return recordJson;
}

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 a2  s.co  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:com.idean.atthack.network.RequestHelper.java

public Result login(Bundle params) {
    String username = params.getString(Param.username.name());
    String vin = params.getString(Param.vin.name());
    String pin = params.getString(Param.pin.name());
    if (username == null || vin == null || pin == null) {
        return new Result(400);
    }// ww  w . j  a v  a2 s .  c  om

    HttpURLConnection conn = null;
    try {
        URL url = new URL(getUrlBase() + "remoteservices/v1/vehicle/login/" + vin);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(HttpVerb.POST.name());
        String auth = username + ":" + pin;
        String encoded = Base64.encodeToString(auth.getBytes(), Base64.DEFAULT);
        conn.setRequestProperty("Authorization", "Basic " + encoded);

        conn.connect();
        // Closes input stream afterwards
        String body = readStream(conn.getInputStream());
        return new Result(conn.getResponseCode(), body);

    } catch (IOException e) {
        Log.w(TAG, "Unable to login " + e.getMessage(), e);
        return new Result("Unable to login: " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

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

/**
 * Encrypts a message.//w w w.ja v a  2s. c  o  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: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);// ww  w  .ja  v  a2  s  .co m
    return new Pair<JSONObject, byte[]>(json, raw);
}

From source file:com.klinker.android.spotify.loader.OAuthTokenRefresher.java

/**
 * Add an auth header to request//  w ww. j  a va 2s.co m
 */
protected HttpUriRequest addAuthHeader(HttpUriRequest request) {
    byte[] base64 = Base64.encode((getClientId() + ":" + getClientSecret()).getBytes(), Base64.DEFAULT);
    String authorization = new String(base64).replace("\n", "").replace(" ", "");
    request.addHeader("Authorization", "Basic " + authorization);
    request.addHeader("Content-Type", "application/x-www-form-urlencoded"); // need this or we get xml returned
    return request;
}

From source file:com.yanzhenjie.nohttp.cache.CacheEntity.java

/**
 * @param data the data to set.
 */
public void setDataBase64(String data) {
    this.data = Base64.decode(data, Base64.DEFAULT);
}