Example usage for android.util Base64 URL_SAFE

List of usage examples for android.util Base64 URL_SAFE

Introduction

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

Prototype

int URL_SAFE

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

Click Source Link

Document

Encoder/decoder flag bit to indicate using the "URL and filename safe" variant of Base64 (see RFC 3548 section 4) where - and _ are used in place of + and / .

Usage

From source file:com.harshad.linconnectclient.NotificationUtilities.java

public static boolean sendData(Context c, Notification n, String packageName) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);

    ConnectivityManager connManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    // Check Wifi state, whether notifications are enabled globally, and
    // whether notifications are enabled for specific application
    if (prefs.getBoolean("pref_toggle", true) && prefs.getBoolean(packageName, true) && mWifi.isConnected()) {
        String ip = prefs.getString("pref_ip", "0.0.0.0:9090");

        // Magically extract text from notification
        ArrayList<String> notificationData = NotificationUtilities.getNotificationText(n);

        // Use PackageManager to get application name and icon
        final PackageManager pm = c.getPackageManager();
        ApplicationInfo ai;/*from www .  j  av  a  2s  .  c  o m*/
        try {
            ai = pm.getApplicationInfo(packageName, 0);
        } catch (final NameNotFoundException e) {
            ai = null;
        }

        String notificationBody = "";
        String notificationHeader = "";
        // Create header and body of notification
        if (notificationData.size() > 0) {
            notificationHeader = notificationData.get(0);
            if (notificationData.size() > 1) {
                notificationBody = notificationData.get(1);
            }
        } else {
            return false;
        }

        for (int i = 2; i < notificationData.size(); i++) {
            notificationBody += "\n" + notificationData.get(i);
        }

        // Append application name to body
        if (pm.getApplicationLabel(ai) != null) {
            if (notificationBody.isEmpty()) {
                notificationBody = "via " + pm.getApplicationLabel(ai);
            } else {
                notificationBody += " (via " + pm.getApplicationLabel(ai) + ")";
            }
        }

        // Setup HTTP request
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // If the notification contains an icon, use it
        if (n.largeIcon != null) {
            entity.addPart("notificon",
                    new InputStreamBody(ImageUtilities.bitmapToInputStream(n.largeIcon), "drawable.png"));
        }
        // Otherwise, use the application's icon
        else {
            entity.addPart("notificon",
                    new InputStreamBody(
                            ImageUtilities.bitmapToInputStream(
                                    ImageUtilities.drawableToBitmap(pm.getApplicationIcon(ai))),
                            "drawable.png"));
        }

        HttpPost post = new HttpPost("http://" + ip + "/notif");
        post.setEntity(entity);

        try {
            post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
        } catch (UnsupportedEncodingException e) {
            post.addHeader("notifheader",
                    Base64.encodeToString(notificationHeader.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription",
                    Base64.encodeToString(notificationBody.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        }

        // Send HTTP request
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        try {
            response = client.execute(post);
            String html = EntityUtils.toString(response.getEntity());
            if (html.contains("true")) {
                return true;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return false;
}

From source file:com.microsoft.aad.adal.IdToken.java

private HashMap<String, String> parseJWT(final String idtoken) throws AuthenticationException {
    final String idbody = extractJWTBody(idtoken);
    // URL_SAFE: Encoder/decoder flag bit to use
    // "URL and filename safe" variant of Base64
    // (see RFC 3548 section 4) where - and _ are used in place of +
    // and /.//from  www . ja v a 2s .c  o m
    final byte[] data = Base64.decode(idbody, Base64.URL_SAFE);

    try {
        final String decodedBody = new String(data, "UTF-8");
        final HashMap<String, String> responseItems = extractJsonObjects(decodedBody);
        return responseItems;
    } catch (UnsupportedEncodingException exception) {
        Logger.e(TAG, "The encoding is not supported.", "", ADALError.ENCODING_IS_NOT_SUPPORTED, exception);
        throw new AuthenticationException(ADALError.ENCODING_IS_NOT_SUPPORTED, exception.getMessage(),
                exception);
    } catch (JSONException exception) {
        Logger.e(TAG, "Failed to parse the decoded body into JsonObject.", "", ADALError.JSON_PARSE_ERROR,
                exception);
        throw new AuthenticationException(ADALError.JSON_PARSE_ERROR, exception.getMessage(), exception);
    }
}

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   w  w w.j  a  v a 2  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   www. j ava  2  s .  com
        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.microg.gms.auth.AuthManagerServiceImpl.java

@Override
public Bundle getToken(String accountName, String scope, Bundle extras) throws RemoteException {
    String packageName = extras.getString(KEY_ANDROID_PACKAGE_NAME);
    if (packageName == null || packageName.isEmpty())
        packageName = extras.getString(KEY_CLIENT_PACKAGE_NAME);
    int callerUid = extras.getInt(KEY_CALLER_UID, 0);
    PackageUtils.checkPackageUid(context, packageName, callerUid, getCallingUid());
    boolean notify = extras.getBoolean(KEY_HANDLE_NOTIFICATION, false);

    Log.d(TAG, "getToken: account:" + accountName + " scope:" + scope + " extras:" + extras + ", notify: "
            + notify);/*from  w  w  w .java  2 s  . co m*/

    /*
     * TODO: This scope seems to be invalid (according to https://developers.google.com/oauthplayground/),
     * but is used in some applications anyway. Removing it is unlikely a good solution, but works for now.
     */
    scope = scope.replace("https://www.googleapis.com/auth/identity.plus.page.impersonation ", "");

    AuthManager authManager = new AuthManager(context, accountName, packageName, scope);
    Bundle result = new Bundle();
    result.putString(KEY_ACCOUNT_NAME, accountName);
    result.putString(KEY_ACCOUNT_TYPE, authManager.getAccountType());
    try {
        AuthResponse res = authManager.requestAuth(false);
        if (res.auth != null) {
            Log.d(TAG, "getToken: " + res);
            result.putString(KEY_AUTHTOKEN, res.auth);
            Bundle details = new Bundle();
            details.putParcelable("TokenData",
                    new TokenData(res.auth, res.expiry, scope.startsWith("oauth2:"), getScopes(scope)));
            result.putBundle("tokenDetails", details);
            result.putString(KEY_ERROR, "OK");
        } else {
            result.putString(KEY_ERROR, "NeedPermission");
            Intent i = new Intent(context, AskPermissionActivity.class);
            i.putExtras(extras);
            i.putExtra(KEY_ANDROID_PACKAGE_NAME, packageName);
            i.putExtra(KEY_ACCOUNT_TYPE, authManager.getAccountType());
            i.putExtra(KEY_ACCOUNT_NAME, accountName);
            i.putExtra(KEY_AUTHTOKEN, scope);
            try {
                if (res.consentDataBase64 != null)
                    i.putExtra(EXTRA_CONSENT_DATA, Base64.decode(res.consentDataBase64, Base64.URL_SAFE));
            } catch (Exception e) {
                Log.w(TAG, "Can't decode consent data: ", e);
            }
            if (notify) {
                NotificationManager nm = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                nm.notify(packageName.hashCode(),
                        new NotificationCompat.Builder(context)
                                .setContentIntent(PendingIntent.getActivity(context, 0, i, 0))
                                .setContentTitle(context.getString(R.string.auth_notification_title))
                                .setContentText(context.getString(R.string.auth_notification_content,
                                        getPackageLabel(packageName, context.getPackageManager())))
                                .setSmallIcon(android.R.drawable.stat_notify_error).build());
            }
            result.putParcelable(KEY_USER_RECOVERY_INTENT, i);
        }
    } catch (IOException e) {
        Log.w(TAG, e);
        result.putString(KEY_ERROR, "NetworkError");
    }
    return result;
}

From source file:com.textuality.keybase.lib.prover.Prover.java

public boolean checkRawMessageBytes(InputStream in) {
    try {//from w ww  .j  av  a 2 s.  co m
        MessageDigest digester = MessageDigest.getInstance("SHA-256");
        byte[] buffer = new byte[8192];
        int byteCount;
        while ((byteCount = in.read(buffer)) > 0) {
            digester.update(buffer, 0, byteCount);
        }
        String digest = Base64.encodeToString(digester.digest(), Base64.URL_SAFE);
        if (!digest.startsWith(mShortenedMessageHash)) {
            mLog.add("Proof post doesnt contain correct encoded message.");
            return false;
        }
        return true;
    } catch (NoSuchAlgorithmException e) {
        mLog.add("SHA-256 not available");
    } catch (IOException e) {
        mLog.add("Error checking raw message: " + e.getLocalizedMessage());
    }
    return false;
}

From source file:org.ebayopensource.fidouafclient.op.Reg.java

private String getFinalChalenge(RegistrationRequest regRequest) {
    FinalChallengeParams fcParams = new FinalChallengeParams();
    fcParams.appID = regRequest.header.appID;
    Preferences.setSettingsParam("appID", fcParams.appID);
    fcParams.facetID = getFacetId();/* ww w .  ja v a  2 s .  c  o  m*/
    fcParams.challenge = regRequest.challenge;
    fcParams.channelBinding = new ChannelBinding();
    fcParams.channelBinding.cid_pubkey = "";
    fcParams.channelBinding.serverEndPoint = "";
    fcParams.channelBinding.tlsServerCertificate = "";
    fcParams.channelBinding.tlsUnique = "";
    return Base64.encodeToString(gson.toJson(fcParams).getBytes(), Base64.URL_SAFE);
}

From source file:com.hmsoft.libcommon.gopro.GoProController.java

private void logCommandAndResponse(String url, byte[] response) {
    String responseStr = Base64.encodeToString(response, 0, response.length > 512 ? 512 : response.length,
            Base64.NO_WRAP | Base64.URL_SAFE);

    Logger.info(TAG, removePassword(url) + " = " + responseStr);
}

From source file:no.digipost.android.authentication.OAuth.java

private static String getB64Auth() {
    String source = Secret.CLIENT_ID + ":" + Secret.CLIENT_SECRET;
    return ApiConstants.BASIC + Base64.encodeToString(source.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP);
}

From source file:com.afwsamples.testdpc.safetynet.SafetyNetFragment.java

private static JSONObject retrievePayloadFromJws(String jws) throws JSONException {
    String[] parts = jws.split("\\.");
    if (parts.length != 3) {
        throw new JSONException("Invalid JWS");
    }/*from  w  ww . ja v a  2 s  .  c  o m*/
    return new JSONObject(new String(Base64.decode(parts[1], Base64.URL_SAFE)));
}