Example usage for android.util Base64 NO_PADDING

List of usage examples for android.util Base64 NO_PADDING

Introduction

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

Prototype

int NO_PADDING

To view the source code for android.util Base64 NO_PADDING.

Click Source Link

Document

Encoder flag bit to omit the padding '=' characters at the end of the output (if any).

Usage

From source file:com.google.samples.apps.abelana.AbelanaThings.java

public AbelanaThings(Context ctx, String phint) {
    final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    final HttpTransport httpTransport = new NetHttpTransport();
    Resources r = ctx.getResources();
    byte[] android, server;
    byte[] password = new byte[32];

    android = Base64.decode("vW7CmbQWdPjpdfpBU39URsjHQV50KEKoSfafHdQPSh8",
            Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP);
    server = Base64.decode(phint, Base64.URL_SAFE);

    int i = 0;/* ww w.j av  a 2 s. c  om*/
    for (byte b : android) {
        password[i] = (byte) (android[i] ^ server[i]);
        i++;
    }
    byte[] pw = Base64.encode(password, Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP);
    String pass = new String(pw);

    if (storage == null) {
        try {
            KeyStore keystore = KeyStore.getInstance("PKCS12");
            keystore.load(r.openRawResource(R.raw.abelananew), pass.toCharArray());

            credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
                    .setServiceAccountId(r.getString(R.string.service_account))
                    .setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL))
                    .setServiceAccountPrivateKey((PrivateKey) keystore.getKey("privatekey", pass.toCharArray()))
                    .build();

            storage = new Storage.Builder(httpTransport, jsonFactory, credential)
                    .setApplicationName(r.getString(R.string.app_name) + "/1.0").build();

        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("loaded");
    }
}

From source file:com.distimo.sdk.Utils.java

@SuppressLint({ "NewApi", "InlinedApi" })
static String base64Encode(byte[] data) {
    String result = null;//ww w . j  ava 2 s.c om

    if (Build.VERSION.SDK_INT < 8) { //Build.VERSION.FROYO
        try {
            result = OldBase64.encodeBytes(data, OldBase64.URL_SAFE).replace("=", "");
        } catch (final IOException ioe) {
            if (Utils.DEBUG) {
                ioe.printStackTrace();
            }
        }
    } else {
        result = Base64.encodeToString(data, Base64.NO_PADDING | Base64.URL_SAFE | Base64.NO_WRAP);
    }

    return result;
}

From source file:org.andstatus.app.net.http.HttpConnectionBasic.java

/**
 * Get the HTTP digest authentication. Uses Base64 to encode credentials.
 * //from  www.  j  av a2s .co  m
 * @return String
 */
private String getCredentials() {
    return Base64.encodeToString((data.accountUsername + ":" + mPassword).getBytes(Charset.forName("UTF-8")),
            Base64.NO_WRAP + Base64.NO_PADDING);
}

From source file:org.riksa.syncmute.ParseTools.java

/**
 * Get channel name. Channel name is a salted SHA-256 hash of username+channename (from settings)
 *
 * @return Base64 encoded SHA-256 salted hash
 *///from   w  ww.jav  a  2  s .c o  m
protected String getChannel() {
    try {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String userName = preferences.getString("preferences_username", "DEFAULT");
        String channelName = preferences.getString("preferences_channel", "DEFAULT");
        Log.d(TAG, "hashing username=" + userName);
        Log.d(TAG, "hashing channelName=" + channelName);

        byte[] digest = doHash(DIGEST_ALGORITHM, SALT, userName.getBytes("UTF-8"),
                channelName.getBytes("UTF-8"));
        // Base64 encode without padding. Padded channel name is invalid (alphanumerics only)
        String base64Digest = Base64.encodeToString(digest, Base64.NO_WRAP | Base64.NO_PADDING);
        Log.d(TAG, "base64Digest=" + base64Digest);

        return base64Digest;
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, e.getMessage(), e);
    }
    return "DEFAULT";
}

From source file:com.jbirdvegas.mgerrit.dialogs.DiffDialog.java

private String workAroundBadBase(String baseString) {
    if (baseString == null) {
        return getContext().getString(R.string.return_was_null);
    }/*from  ww w  .  j  a  v a2 s. c o m*/
    String failMessage = "Failed to decode Base64 using: ";
    try {
        return new String(ApacheBase64.decodeBase64(baseString));
    } catch (IllegalArgumentException badBase) {
        Log.e(TAG, failMessage + "org.apache.commons.codec.binary.ApacheBase64", badBase);
    }
    try {
        return new String(Base64.decode(baseString.getBytes(), Base64.URL_SAFE | Base64.NO_PADDING));
    } catch (IllegalArgumentException badBase) {
        Log.e(TAG, failMessage + "android.util.Base64", badBase);
    }
    try {
        return new String(Base64Coder.decode(baseString));
    } catch (IllegalArgumentException badBase) {
        Log.e(TAG, failMessage + "com.jbirdvegas.mgerrit.helpers.Base64Coder", badBase);
    }
    return getContext().getString(R.string.failed_to_decode_base64);
}

From source file:com.restswitch.controlpanel.MainActivity.java

private void sendDevice(String devid, String host, String msg, String pwdHash) {
    try {//from w  w  w.  j  a va  2  s . c o  m
        final long utcStart = System.currentTimeMillis();
        String b32UntilUtc = B32Coder.encodeDatetimeNow(8000); // valid for 8 sec
        String method = "PUT";
        String uri = ("/pub/" + devid);
        String val = (method + uri + msg + b32UntilUtc);

        String b64Hash = null;
        try {
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            hmacSha256.init(new javax.crypto.spec.SecretKeySpec(pwdHash.getBytes("utf-8"), "HmacSHA256"));
            byte[] hash = hmacSha256.doFinal(val.getBytes("UTF-8"));
            b64Hash = Base64.encodeToString(hash, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
        } catch (Exception ex) {
            alertError("Invalid password, verify app settings.");
            return;
        }

        Properties headers = new Properties();
        headers.setProperty("x-body", msg);
        headers.setProperty("x-auth1", b32UntilUtc);
        headers.setProperty("x-auth2", b64Hash);

        AjaxTask ajaxTask = new AjaxTask();
        ajaxTask.putAjaxEventHandler(this);
        //            // use to set a custom ca
        //            boolean rc = ajaxTask.putRootCaCert(rootCa, true);
        //            if(!rc) {
        //                alertError("Failed to initialize network task.");
        //                return;
        //            }
        AjaxTask.Data data = new AjaxTask.Data();
        data.param1 = devid;
        data.param2 = utcStart;
        ajaxTask.invoke("http", host, uri, method, headers, msg, data);
    } catch (Exception ex) {
        alertError(ex.getMessage());
    }
}

From source file:org.andstatus.app.net.HttpConnectionBasic.java

/**
 * Get the HTTP digest authentication. Uses Base64 to encode credentials.
 * //  w  w w.  ja va2s  .com
 * @return String
 */
private String getCredentials() {
    // TODO: since API9 we will use getBytes(Charset.forName("US-ASCII"))
    return Base64.encodeToString((data.accountUsername + ":" + mPassword).getBytes(),
            Base64.NO_WRAP + Base64.NO_PADDING);
}

From source file:com.jbirdvegas.mgerrit.dialogs.DiffDialog.java

private Request getDebugRequest(String url, String arg) {
    // seems a bug prevents the args from being respected???
    // See here://from w  w w.  j  a  va2 s. c  o  m
    // https://groups.google.com/forum/?fromgroups#!topic/repo-discuss/xmFCHbD4Z0Q
    String limiter = "&o=context:2";

    final String args = arg + limiter;
    final String weburl = url + args;
    Request debugRequest = new StringRequest(weburl, new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            Log.d(TAG,
                    "[DEBUG-MODE]\n" + "Decoded Response for args {" + args + '}' + "\n" + "url: " + weburl
                            + "\n==================================="
                            + new String(Base64.decode(s, Base64.URL_SAFE | Base64.NO_PADDING))
                            + "====================================");
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            Log.e(TAG, "Debuging Volley Failed!!!", volleyError);
        }
    });
    return debugRequest;
}

From source file:org.openmidaas.library.test.MIDaaSTest.java

@SmallTest
public void testAttributeBundle() {
    Map<String, AbstractAttribute<?>> map = new HashMap<String, AbstractAttribute<?>>();
    map.put("mock1", new MockAttribute());
    String bundleAsString = MIDaaS.getAttributeBundle(VALID_CLIENT_ID, null, map);
    Assert.assertNotNull(bundleAsString);
    String[] segments = bundleAsString.split("\\.");
    String header = segments[0];/*from  w w w  .ja v a2s  . c  o m*/
    byte[] headerBytes = Base64.decode(header, Base64.NO_PADDING + Base64.NO_WRAP);
    byte[] bodyBytes = Base64.decode(segments[1], Base64.NO_PADDING + Base64.NO_WRAP);
    try {
        String headerAsString = new String(headerBytes, "UTF-8");
        JSONObject object = new JSONObject(headerAsString);
        if (!object.getString("alg").equals("none")) {
            Assert.fail();
        }
        String bodyAsString = new String(bodyBytes, "UTF-8");
        JSONObject bodyObject = new JSONObject(bodyAsString);
        if (!object.getString("alg").equals("none")) {
            Assert.fail();
        }
        if (!bodyObject.getString("iss").equals("org.openmidaas.library")) {
            Assert.fail();
        }
        if (!bodyObject.getString("aud").equals(VALID_CLIENT_ID)) {
            Assert.fail();
        }
        if (bodyObject.isNull("attrs")) {
            Assert.fail();
        }
        JSONObject attributes = bodyObject.getJSONObject("attrs");
        Iterator<?> keys = attributes.keys();
        // parsing through the "attrs" field now.
        while (keys.hasNext()) {
            String key = (String) keys.next();
            if (attributes.get(key) != null) {
                if (!attributes.get(key).equals("MockAttribute")) {
                    Assert.fail();
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        Assert.fail();
    } catch (JSONException e) {
        Assert.fail();
    }

}

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");
}