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:bluemurder.miner.MinerTask.java

void EncodeAuth() {
    byte[] enc;//from   w  ww .j  av  a2s . c  om
    // build authentication pair with base64("user:pass")
    authPair = new String(activity.rpcuser + ":" + activity.rpcpass);
    enc = authPair.getBytes();
    enc = Base64.encode(enc, 0);
    authPair = "Basic " + new String(enc);
    // Remove newline
    authPair = authPair.replaceAll("[\n\r]", "");
}

From source file:com.playhaven.android.req.PlayHavenRequest.java

protected static String convertToBase64(byte[] in) throws UnsupportedEncodingException {
    if (in == null)
        return null;

    return new String(Base64.encode(in, Base64.URL_SAFE | Base64.NO_PADDING), "UTF8");
}

From source file:com.digicorp.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Convert results cursor to JSON string.
 *
 * @param cur/*www .  ja  va2 s  .  c o m*/
 *            Cursor into query results
 *
 * @return results in string form
 *
 */
@SuppressLint("NewApi")
private String results2string(Cursor cur) {
    String result = "[]";

    // If query result has rows
    if (cur.moveToFirst()) {
        JSONArray fullresult = new JSONArray();
        String key = "";
        int colCount = cur.getColumnCount();

        // Build up JSON result object for each row
        do {
            JSONObject row = new JSONObject();
            try {
                for (int i = 0; i < colCount; ++i) {
                    key = cur.getColumnName(i);

                    // for old Android SDK remove lines from HERE:
                    if (android.os.Build.VERSION.SDK_INT >= 11) {
                        switch (cur.getType(i)) {
                        case Cursor.FIELD_TYPE_NULL:
                            row.put(key, null);
                            break;
                        case Cursor.FIELD_TYPE_INTEGER:
                            row.put(key, cur.getInt(i));
                            break;
                        case Cursor.FIELD_TYPE_FLOAT:
                            row.put(key, cur.getFloat(i));
                            break;
                        case Cursor.FIELD_TYPE_STRING:
                            row.put(key, cur.getString(i));
                            break;
                        case Cursor.FIELD_TYPE_BLOB:
                            row.put(key, new String(Base64.encode(cur.getBlob(i), Base64.DEFAULT)));
                            break;
                        }
                    } else // to HERE.
                    {
                        row.put(key, cur.getString(i));
                    }
                }

                fullresult.put(row);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } while (cur.moveToNext());

        result = fullresult.toString();
    }

    return result;
}

From source file:com.orange.labs.sdk.session.AuthSession.java

/**
 * Static method to encode (UTF-8 + Base64)
 * @param key AppKey of service//from www. j a va 2s.  c  om
 * @param secret AppSecret of service
 * @return the encoded credentials
 */
public static String encodedCredentials(final String key, final String secret) {

    String credentials = key + ":" + secret;

    byte[] encodedBytes;
    encodedBytes = Base64.encode(credentials.getBytes(), 0);
    String result = "";
    try {
        result = new String(encodedBytes, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.android.email.mail.transport.Rfc822Output.java

/**
 * Write text (either as main body or inside a multipart), preceded by appropriate headers.
 *
 * Note this always uses base64, even when not required.  Slightly less efficient for
 * US-ASCII text, but handles all formats even when non-ascii chars are involved.  A small
 * optimization might be to prescan the string for safety and send raw if possible.
 *
 * @param writer the output writer//from   w w  w .j a v a2  s  . c  o  m
 * @param out the output stream inside the writer (used for byte[] access)
 * @param text The original text of the message
 */
private static void writeTextWithHeaders(Writer writer, OutputStream out, String text) throws IOException {
    writeHeader(writer, "Content-Type", "text/plain; charset=utf-8");
    writeHeader(writer, "Content-Transfer-Encoding", "base64");
    writer.write("\r\n");
    byte[] bytes = text.getBytes("UTF-8");
    writer.flush();
    out.write(Base64.encode(bytes, Base64.CRLF));
}

From source file:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Convert results cursor to JSON string.
 *
 * @param cur/*from ww w.  ja  va 2  s .c o  m*/
 *            Cursor into query results
 *
 * @return results in string form
 *
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private String results2string(Cursor cur) {
    String result = "[]";

    // If query result has rows
    if (cur.moveToFirst()) {
        JSONArray fullresult = new JSONArray();
        String key = "";
        int colCount = cur.getColumnCount();

        // Build up JSON result object for each row
        do {
            JSONObject row = new JSONObject();
            try {
                for (int i = 0; i < colCount; ++i) {
                    key = cur.getColumnName(i);

                    // for old Android SDK remove lines from HERE:
                    if (android.os.Build.VERSION.SDK_INT >= 11) {
                        switch (cur.getType(i)) {
                        case Cursor.FIELD_TYPE_NULL:
                            row.put(key, null);
                            break;
                        case Cursor.FIELD_TYPE_INTEGER:
                            row.put(key, cur.getInt(i));
                            break;
                        case Cursor.FIELD_TYPE_FLOAT:
                            row.put(key, cur.getFloat(i));
                            break;
                        case Cursor.FIELD_TYPE_STRING:
                            row.put(key, cur.getString(i));
                            break;
                        case Cursor.FIELD_TYPE_BLOB:
                            //row.put(key, cur.getBlob(i));
                            row.put(key, new String(Base64.encode(cur.getBlob(i), Base64.DEFAULT)));
                            break;
                        }
                    } else // to HERE.
                    {
                        row.put(key, cur.getString(i));
                    }
                }

                fullresult.put(row);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } while (cur.moveToNext());

        result = fullresult.toString();
    }

    return result;
}

From source file:io.realm.TypeBasedNotificationsTests.java

@Test
@RunTestInLooperThread// w w w . j a v a 2s.c o m
public void callback_should_trigger_for_createObjectFromJson_from_JSONObject() {
    final Realm realm = looperThread.realm;
    realm.addChangeListener(new RealmChangeListener() {
        @Override
        public void onChange() {
            if (globalCommitInvocations.incrementAndGet() == 1) {
                realm.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        assertEquals(1, typebasedCommitInvocations.get());
                        looperThread.testComplete();
                    }
                });
            }
        }
    });

    try {
        JSONObject json = new JSONObject();
        json.put("columnString", "String");
        json.put("columnLong", 1L);
        json.put("columnFloat", 1.23f);
        json.put("columnDouble", 1.23d);
        json.put("columnBoolean", true);
        json.put("columnBinary", new String(Base64.encode(new byte[] { 1, 2, 3 }, Base64.DEFAULT)));

        realm.beginTransaction();
        final AllTypes objectFromJson = realm.createObjectFromJson(AllTypes.class, json);
        realm.commitTransaction();

        objectFromJson.addChangeListener(new RealmChangeListener() {
            @Override
            public void onChange() {
                assertEquals("ObjectFromJson", objectFromJson.getColumnString());
                assertEquals(1L, objectFromJson.getColumnLong());
                assertEquals(1.23F, objectFromJson.getColumnFloat(), 0F);
                assertEquals(1.23D, objectFromJson.getColumnDouble(), 0D);
                assertEquals(true, objectFromJson.isColumnBoolean());
                assertArrayEquals(new byte[] { 1, 2, 3 }, objectFromJson.getColumnBinary());
                typebasedCommitInvocations.incrementAndGet();
            }
        });

        realm.beginTransaction();
        objectFromJson.setColumnString("ObjectFromJson");
        realm.commitTransaction();

    } catch (JSONException e) {
        fail(e.getMessage());
    }
}

From source file:OAUTHnesia.java

private static String sha1(String s, String keyString)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {

    SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(key);/*from  w w w .j  a  v a2 s.  c  o  m*/

    byte[] bytes = mac.doFinal(s.getBytes("UTF-8"));

    return new String(Base64.encode(bytes, Base64.DEFAULT));
}

From source file:com.ca.mas.cordova.storage.MASStoragePlugin.java

private JSONObject getResultJson(Object result) throws Exception {
    JSONObject response = new JSONObject();
    if (result == null) {
        response.put("mime", "text/plain");
        response.put("value", "");
        return response;
    }/*from w w  w. ja va  2s .c  o  m*/
    DataMarshaller marshaller = StorageDataMarshaller.findMarshaller(result);
    String mime = marshaller.getTypeAsString();

    byte[] bytes = null;
    try {
        response.put("mime", mime);
        bytes = marshaller.marshall(result);
        String b64 = new String(Base64.encode(bytes, 0), "UTF-8");
        StringBuilder base64String = new StringBuilder();
        base64String.append(b64);
        if (base64String.lastIndexOf(System.getProperty("line.separator")) != -1) {
            base64String.deleteCharAt(base64String.lastIndexOf(System.getProperty("line.separator")));
        }
        if (base64String.lastIndexOf("\r") != -1) {
            base64String.deleteCharAt(base64String.lastIndexOf("\r"));
        }
        response.put("value", base64String.toString());
        return response;
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.playhaven.android.req.PlayHavenRequest.java

protected void validateSignatures(Context context, String xPhDigest, String json) throws SignatureException {
    // If sigMac isn't setup... then createUrl wasn't called which means we're probably doing mock calls
    if (sigMac == null)
        return;//w w w . j ava2s .  c  om

    /**
     * Step 1: Validate X-PH-DIGEST
     */

    // X-PH-DIGEST are required when coming from the server
    if (xPhDigest == null)
        throw new SignatureException(SignatureException.Type.Digest, "No digest found");

    // If json is null, there is nothing to validate against
    if (json == null)
        throw new SignatureException(SignatureException.Type.Digest, "No JSON found");

    // Valid X-PH-DIGEST against sigMac
    try {
        sigMac.update(json.getBytes(UTF8));
        byte[] bytes = sigMac.doFinal();
        String derived = new String(Base64.encode(bytes, Base64.URL_SAFE), UTF8).trim();
        if (!xPhDigest.equals(derived)) {
            PlayHaven.v("Signature error. Received: %s != Derived: %s", xPhDigest, derived);
            throw new SignatureException(SignatureException.Type.Digest, "Signature mismatch");
        }
    } catch (UnsupportedEncodingException e) {
        throw new SignatureException(e, SignatureException.Type.Digest, "Error decoding signature");
    }

    SharedPreferences pref = PlayHaven.getPreferences(context);

    /**
     * Step 2: Validate any Rewards
     */
    try {
        JSONArray rewards = JsonUtil.getPath(json, "$.response.context.content.*.parameters.rewards");
        if (rewards != null) {
            for (int i = 0; i < rewards.size(); i++) {
                JSONObject reward = (JSONObject) rewards.get(i);
                String body = concat(":", getString(pref, DeviceId), JsonUtil.asString(reward, "$.reward"),
                        JsonUtil.asString(reward, "$.quantity"), JsonUtil.asString(reward, "$.receipt"));
                String mac = createHmac(pref, body, true);
                String sig = JsonUtil.<String>getPath(reward, "$.sig4");
                if (!mac.equals(sig))
                    throw new SignatureException(SignatureException.Type.Reward, "Signature does not match.");
            }
        }
    } catch (SignatureException se) {
        throw se;
    } catch (Exception e) {
        throw new SignatureException(e, SignatureException.Type.Reward);
    }

    /**
     * Step 3: Validate any Purchases
     */
    try {
        JSONArray purchases = JsonUtil.getPath(json, "$.response.context.content.*.parameters.purchases");
        if (purchases != null) {
            for (int i = 0; i < purchases.size(); i++) {
                JSONObject purchase = (JSONObject) purchases.get(i);
                String body = concat(":", getString(pref, DeviceId), JsonUtil.asString(purchase, "$.product"),
                        JsonUtil.asString(purchase, "$.name"), JsonUtil.asString(purchase, "$.quantity"),
                        JsonUtil.asString(purchase, "$.receipt"));
                String mac = createHmac(pref, body, true);
                String sig = JsonPath.<String>read(purchase, "$.sig4");
                if (!mac.equals(sig))
                    throw new SignatureException(SignatureException.Type.Purchase, "Signature does not match.");
            }
        }
    } catch (SignatureException se) {
        throw se;
    } catch (Exception e) {
        throw new SignatureException(e, SignatureException.Type.Purchase);
    }
}