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:org.quantumbadger.redreader.reddit.api.RedditOAuth.java

private static FetchRefreshTokenResult fetchRefreshTokenSynchronous(final Context context,
        final Uri redirectUri) {

    final String error = redirectUri.getQueryParameter("error");

    if (error != null) {

        if (error.equals("access_denied")) {
            return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.USER_REFUSED_PERMISSION,
                    new RRError(context.getString(R.string.error_title_login_user_denied_permission),
                            context.getString(R.string.error_message_login_user_denied_permission)));

        } else {//  w  w w .j  ava  2s .co  m
            return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.INVALID_REQUEST,
                    new RRError(context.getString(R.string.error_title_login_unknown_reddit_error) + error,
                            context.getString(R.string.error_unknown_message)));
        }
    }

    final String code = redirectUri.getQueryParameter("code");

    if (code == null) {
        return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.INVALID_RESPONSE,
                new RRError(context.getString(R.string.error_unknown_title),
                        context.getString(R.string.error_unknown_message)));
    }

    final String uri = ACCESS_TOKEN_URL;
    StatusLine responseStatus = null;

    try {
        final HttpClient httpClient = CacheManager.createHttpClient(context);

        final HttpPost request = new HttpPost(uri);

        final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nameValuePairs.add(new BasicNameValuePair("code", code));
        nameValuePairs.add(new BasicNameValuePair("redirect_uri", REDIRECT_URI));
        request.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        request.addHeader("Authorization", "Basic "
                + Base64.encodeToString((CLIENT_ID + ":").getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));

        final HttpResponse response = httpClient.execute(request);
        responseStatus = response.getStatusLine();

        if (responseStatus.getStatusCode() != 200) {
            return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.UNKNOWN_ERROR,
                    new RRError(context.getString(R.string.error_unknown_title),
                            context.getString(R.string.message_cannotlogin), null, responseStatus,
                            request.getURI().toString()));
        }

        final JsonValue jsonValue = new JsonValue(response.getEntity().getContent());
        jsonValue.buildInThisThread();
        final JsonBufferedObject responseObject = jsonValue.asObject();

        final RefreshToken refreshToken = new RefreshToken(responseObject.getString("refresh_token"));
        final AccessToken accessToken = new AccessToken(responseObject.getString("access_token"));

        return new FetchRefreshTokenResult(refreshToken, accessToken);

    } catch (IOException e) {
        return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.CONNECTION_ERROR,
                new RRError(context.getString(R.string.error_connection_title),
                        context.getString(R.string.error_connection_message), e, responseStatus, uri));

    } catch (Throwable t) {
        return new FetchRefreshTokenResult(FetchRefreshTokenResultStatus.UNKNOWN_ERROR,
                new RRError(context.getString(R.string.error_unknown_title),
                        context.getString(R.string.error_unknown_message), t, responseStatus, uri));
    }
}

From source file:net.bither.util.TransactionsUtil.java

public static List<In> getInSignatureFromBither(String str) {
    List<In> result = new ArrayList<In>();
    if (str.length() > 0) {
        String[] txs = str.split(";");
        for (String tx : txs) {
            String[] ins = tx.split(":");
            byte[] txHash = Utils.reverseBytes(Base64.decode(ins[0], Base64.URL_SAFE));
            for (int i = 1; i < ins.length; i++) {
                String[] array = ins[i].split(",");
                int inSn = Integer.decode(array[0]);
                byte[] inSignature = Base64.decode(array[1], Base64.URL_SAFE);
                In in = new In();
                in.setTxHash(txHash);//from   www .  jav  a 2  s. co m
                in.setInSn(inSn);
                in.setInSignature(inSignature);
                result.add(in);
            }
        }
    }
    return result;
}

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  ww.java 2s  .co  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.gluu.com.ox_push2.u2f.v2.SoftwareDevice.java

public TokenResponse sign(String jsonRequest, String origin, Boolean isDeny)
        throws JSONException, IOException, U2FException {
    if (BuildConfig.DEBUG)
        Log.d(TAG, "Starting to process sign request: " + jsonRequest);
    JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue();

    JSONArray authenticateRequestArray = null;
    if (request.has("authenticateRequests")) {
        authenticateRequestArray = request.getJSONArray("authenticateRequests");
        if (authenticateRequestArray.length() == 0) {
            throw new U2FException("Failed to get authentication request!");
        }/*w  w  w .  ja v a  2  s .c  o  m*/
    } else {
        authenticateRequestArray = new JSONArray();
        authenticateRequestArray.put(request);
    }

    Log.i(TAG, "Found " + authenticateRequestArray.length() + " authentication requests");

    AuthenticateResponse authenticateResponse = null;
    String authenticatedChallenge = null;
    JSONObject authRequest = null;
    for (int i = 0; i < authenticateRequestArray.length(); i++) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Process authentication request: " + authRequest);
        authRequest = (JSONObject) authenticateRequestArray.get(i);

        if (!authRequest.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) {
            throw new U2FException("Unsupported U2F_V2 version!");
        }

        String version = authRequest.getString(JSON_PROPERTY_VERSION);
        String appParam = authRequest.getString(JSON_PROPERTY_APP_ID);
        String challenge = authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE);
        byte[] keyHandle = Base64.decode(authRequest.getString(JSON_PROPERTY_KEY_HANDLE),
                Base64.URL_SAFE | Base64.NO_WRAP);

        authenticateResponse = u2fKey.authenticate(new AuthenticateRequest(version,
                AuthenticateRequest.USER_PRESENCE_SIGN, challenge, appParam, keyHandle));
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Authentication response: " + authenticateResponse);
        if (authenticateResponse != null) {
            authenticatedChallenge = challenge;
            break;
        }
    }

    if (authenticateResponse == null) {
        return null;
    }

    JSONObject clientData = new JSONObject();
    if (isDeny) {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, AUTHENTICATE_CANCEL_TYPE);
    } else {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_AUTHENTICATE);
    }
    clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE));
    clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin);

    String keyHandle = authRequest.getString(JSON_PROPERTY_KEY_HANDLE);
    String clientDataString = clientData.toString();
    byte[] resp = rawMessageCodec.encodeAuthenticateResponse(authenticateResponse);

    JSONObject response = new JSONObject();
    response.put("signatureData", Utils.base64UrlEncode(resp));
    response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII"))));
    response.put("keyHandle", keyHandle);

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setResponse(response.toString());
    tokenResponse.setChallenge(authenticatedChallenge);
    tokenResponse.setKeyHandle(keyHandle);

    return tokenResponse;
}

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

protected String createHmac(SharedPreferences pref, String content, boolean stripEquals)
        throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
    String secret = getString(pref, Secret);
    SecretKeySpec key = new SecretKeySpec(secret.getBytes(UTF8), HMAC);
    Mac hmac = Mac.getInstance(HMAC);
    hmac.init(key);//from  w  w  w  . ja v a 2  s  . c o  m
    hmac.update(content.getBytes(UTF8));
    byte[] bytes = hmac.doFinal();
    String derived = new String(Base64.encode(bytes, Base64.URL_SAFE), UTF8).trim();
    if (stripEquals)
        derived = derived.replaceAll("=", "");

    return derived;
}

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.ledger.android.u2f.bridge.MainActivity.java

private U2FContext parseU2FContextSign(JSONObject json) {
    try {/*from  w  ww .j  av a  2 s  .  c o  m*/
        String appId = json.getString(TAG_JSON_APPID);
        byte[] challenge = Base64.decode(json.getString(TAG_JSON_CHALLENGE), Base64.URL_SAFE);
        int requestId = json.getInt(TAG_JSON_REQUESTID);
        JSONArray array = json.getJSONArray(TAG_JSON_REGISTERED_KEYS);
        Vector<byte[]> keyHandles = new Vector<byte[]>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject keyHandleItem = array.getJSONObject(i);
            if (!keyHandleItem.getString(TAG_JSON_VERSION).equals(VERSION_U2F_V2)) {
                Log.e(TAG, "Invalid handle version");
                return null;
            }
            byte[] keyHandle = Base64.decode(keyHandleItem.getString(TAG_JSON_KEYHANDLE), Base64.URL_SAFE);
            keyHandles.add(keyHandle);
        }
        return new U2FContext(appId, challenge, keyHandles, requestId, true);
    } catch (JSONException e) {
        Log.e(TAG, "Error decoding request");
        return null;
    }
}

From source file:au.com.wallaceit.reddinator.RedditData.java

private JSONObject getJSONFromPost(String url, ArrayList<NameValuePair> data, boolean addOauthHeaders)
        throws RedditApiException {
    JSONObject jObj = new JSONObject();
    String json;//from w w  w .  ja v a  2  s .  co m
    InputStream is = null;
    // create client if null
    if (httpclient == null) {
        createHttpClient();
    }
    try {
        HttpPost httppost = new HttpPost(url);
        if (addOauthHeaders) {
            // For oauth token retrieval and refresh
            httppost.addHeader("Authorization", "Basic " + Base64
                    .encodeToString((OAUTH_CLIENTID + ":").getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        } else if (isLoggedIn()) {
            if (isTokenExpired()) {
                refreshToken();
            }
            String tokenStr = getTokenValue("token_type") + " " + getTokenValue("access_token");
            //System.out.println("Logged In, setting token header: " + tokenStr);
            httppost.addHeader("Authorization", tokenStr);
        }
        if (data != null)
            httppost.setEntity(new UrlEncodedFormEntity(data));

        HttpResponse httpResponse = httpclient.execute(httppost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Pattern p = Pattern.compile("<h2>(\\S+)</h2>");
            Matcher m = p.matcher(getStringFromStream(is));
            String details = "";
            if (m.find()) {
                details = m.group(1);
            }
            throw new RedditApiException(
                    String.valueOf(httpResponse.getStatusLine().getStatusCode()) + ": " + details);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    json = getStringFromStream(is);
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        System.out.println("Error parsing data " + e.toString());
    }
    // return json response
    return jObj;
}

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 ww. j  a  v a  2s.c  o  m

    /**
     * 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);
    }
}

From source file:no.ntnu.idi.socialhitchhiking.myAccount.MyAccountCar.java

/**
 * Displaying the car information in the layout.
 * @param res//from w  w  w. ja v  a 2s .  c  o m
 */
public void showMain(CarResponse res, PreferenceResponse prefResInit) {
    // Initializing the views
    setContentView(R.layout.my_account_car);
    this.imageView = (ImageView) this.findViewById(R.id.cameraView);
    carName = (EditText) this.findViewById(R.id.carName);
    bar = (RatingBar) this.findViewById(R.id.ratingBar1);
    seatsText = (EditText) this.findViewById(R.id.myAccountCarSeats);

    // Setting the number of seats available
    prefRes = prefResInit;
    seatsAvailable = prefRes.getPreferences().getSeatsAvailable();
    if (seatsAvailable > 0) {
        seatsText.setText(seatsAvailable.toString());
    } else {
        seatsText.setText("");
    }

    // If the user does have a car registered
    if (user.getCarId() != 0) {
        // Setting the car name
        carNameString = res.getCar().getCarName();
        // Setting the car ID
        id = res.getCar().getCarId();
        // Setting the comfort
        comfort = (float) res.getCar().getComfort();
        // Getting the car image
        byteArray = res.getCar().getPhoto();

        /*Values of the car from database*/

        // Display these values to the user
        carName.setText(carNameString);
        bar.setRating(comfort);

        String empty = "No car type set";
        byteArrayx = empty.getBytes();
        // If a new image is set, display it
        if (byteArray.length > 15) {
            if (!(res.getCar().getPhotoAsBase64().equals(Base64.encode(byteArrayx, Base64.URL_SAFE)))) {
                btm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                imageView.setImageBitmap(btm);
            }
        }
        // Indicates that the car is initialized
        isCarInitialized = true;
    }
    //if user does not yet have a car registated
    else {
        carNameString = "";
        id = -1;
        comfort = 0.0f;
        String empty = "No car type set";
        byteArray = empty.getBytes();
    }

    // Setting the button for taking a car picture
    Button photoButton = (Button) this.findViewById(R.id.cameraButton);
    photoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            carChanged = true;
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, "tempName");
            cameraIntent.putExtra("return-data", true);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    });
    // Setting the button for getting a car picture from the phone
    Button getimageButton = (Button) this.findViewById(R.id.getimageButton);
    getimageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            carChanged = true;
            Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, ALBUM_REQUEST);
        }
    });
}