Example usage for android.util Base64 NO_WRAP

List of usage examples for android.util Base64 NO_WRAP

Introduction

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

Prototype

int NO_WRAP

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

Click Source Link

Document

Encoder flag bit to omit all line terminators (i.e., the output will be on one long line).

Usage

From source file:com.aegiswallet.utils.WalletUtils.java

/**
 * This file will check the password provided when importing a backup file. If the password is correct,
 * it will return true, if not, false./* w w  w.  j  a  va 2s . com*/
 *
 * @param fileName
 * @param password
 * @return
 */
public static boolean checkPasswordForBackupFile(String fileName, String password) {
    boolean result = false;

    try {
        if (Constants.WALLET_BACKUP_DIRECTORY.exists() && Constants.WALLET_BACKUP_DIRECTORY.isDirectory()) {

            File file = new File(Constants.WALLET_BACKUP_DIRECTORY, fileName);

            FileInputStream fileInputStream = new FileInputStream(file);
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(fileInputStream, Constants.UTF_8));

            while (true) {
                final String line = in.readLine();
                if (line == null)
                    break; // eof

                if (line.startsWith("#X2:")) {

                    String[] splitStr = line.split(":");
                    String x2Base64 = splitStr[1];

                    String x2Encrypted = new String(Base64.decode(x2Base64.getBytes(), Base64.NO_WRAP));
                    String x2Decrypted = WalletUtils.decryptString(x2Encrypted, password);
                    x2Decrypted = x2Decrypted.split(":")[1];

                    if (x2Decrypted != null) {
                        return true;
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IO Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "some other exception: " + e.getMessage());
    }

    return result;
}

From source file:ie.ucd.www.bee.MainActivity.java

public void signin(View view) {
    final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
    pDialog.setTitleText("Sign in...");
    pDialog.show();//from  w w  w.ja  va  2 s . co  m

    final String SERVER_URL = getString(R.string.server_url);
    EditText username = (EditText) findViewById(R.id.user_name);
    EditText password = (EditText) findViewById(R.id.user_password);
    final CheckBox rememberMe = (CheckBox) findViewById(R.id.remember_me);

    final String userName = username.getText().toString();
    final String userPassword = password.getText().toString();

    final Context thisContext = this;
    final Intent homeIntent = new Intent(this, HomeActivity.class);

    Retrofit retrofit = new Retrofit.Builder().baseUrl(SERVER_URL)
            .addConverterFactory(GsonConverterFactory.create()).build();

    UserSignInService userSignInService = retrofit.create(UserSignInService.class);

    String encodingAuth = "Basic "
            + Base64.encodeToString(String.format("%s:%s", userName, userPassword).getBytes(), Base64.NO_WRAP);

    Call<ResponseBody> call = userSignInService.userSignIn(encodingAuth);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                try {
                    pDialog.dismiss();
                    SharedPreferences userInfoKeep = getSharedPreferences("user_info_keep", MODE_PRIVATE);
                    SharedPreferences.Editor userInfoEditor = userInfoKeep.edit();
                    String token = response.body().string();
                    homeIntent.putExtra("token", extractMessage(token));
                    homeIntent.putExtra("username", userName);
                    if (rememberMe.isChecked()) {
                        userInfoEditor.putBoolean("remember_me", true);
                        userInfoEditor.putString("username", userName);
                        userInfoEditor.putString("password", userPassword);
                        userInfoEditor.commit();
                    } else {
                        userInfoEditor.putBoolean("remember_me", false);
                        userInfoEditor.remove("username");
                        userInfoEditor.remove("password");
                        userInfoEditor.commit();
                    }
                    new SweetAlertDialog(thisContext, SweetAlertDialog.SUCCESS_TYPE).setTitleText("Success")
                            .setContentText("Welcome to BeeBia").setConfirmText("Continue")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    startActivity(homeIntent);
                                }
                            }).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                pDialog.dismiss();
                try {
                    String errorMessage = response.errorBody().string();
                    new SweetAlertDialog(thisContext, SweetAlertDialog.ERROR_TYPE).setTitleText("Error")
                            .setContentText(extractMessage(errorMessage)).setConfirmText("Try again").show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable throwable) {
            pDialog.dismiss();
            new SweetAlertDialog(thisContext, SweetAlertDialog.ERROR_TYPE).setTitleText("Sorry")
                    .setContentText("There are some errors of the web service, please try again later.")
                    .setConfirmText("return").show();
            String result = throwable.toString();
            Log.e("SignInResult", result);
        }
    });
}

From source file:com.securekey.sdk.sample.VerifyQuickCodeActivity.java

/**
 * Implements VerifyQuickCodeListener.verifyQuickCodeComplete
 * <p>/*from w  ww  . j ava2s . c  om*/
 * If successful, will forward received txnId for final verification by the RP Server
 * 
 */
@Override
public void verifyQuickCodeComplete(int status, String transactionId) {
    if (status == Briidge.STATUS_OK) {
        if (this.jwsExpected) {
            // The JWT should be provide to a third party to be verify
            // It could be parse to see what's inside 

            dismissProgressDialog();
            String[] jwtSegment = getJWSSegments(transactionId);
            try {
                final StringBuilder message = new StringBuilder();
                message.append(new String(Base64.decode(jwtSegment[0], Base64.NO_WRAP), "UTF-8") + "\n");
                message.append(new String(Base64.decode(jwtSegment[1], Base64.NO_WRAP), "UTF-8") + "\n\n\n");
                showDialog(message.toString());

                verifyJWT(transactionId);
            } catch (UnsupportedEncodingException e) {
                Log.e(VerifyQuickCodeActivity.class.toString(), e.getMessage());
            }

        } else {

            rpQuickCodeVerify(transactionId);
        }
    } else if (status == Briidge.STATUS_TRY_LATER_TOO_MANY_INVALID_ATTEMPTS) {
        showDialog("User suspended!");
    } else if (status == Briidge.STATUS_WRONG_CODE) {
        showDialog("Invalid code!");
    } else {
        dismissProgressDialog();
        showDialog("Failed during verification process.");
    }

}

From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java

/**
 * Add a saved password for a file//from  w  w  w .  j  av  a2  s .c o m
 */
public void addSavedPassword(Uri fileUri, String password, Cipher cipher)
        throws UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
    byte[] enc = cipher.doFinal(password.getBytes("UTF-8"));
    String encStr = Base64.encodeToString(enc, Base64.NO_WRAP);
    String ivStr = Base64.encodeToString(cipher.getIV(), Base64.NO_WRAP);

    String keyName = getPrefsKey(fileUri);
    SharedPreferences prefs = getPrefs();
    prefs.edit().putString(keyName, encStr).putString(getIvPrefsKey(keyName), ivStr).apply();
}

From source file:com.glabs.homegenie.client.Control.java

public static HttpGet getHttpGetRequest(String url) {
    HttpGet getRequest = new HttpGet(url);
    //getRequest.setHeader("Accept", "text/json");
    if (!_hg_user.equals("") && !_hg_pass.equals("")) {
        getRequest.addHeader("Authorization",
                "Basic " + Base64.encodeToString((_hg_user + ":" + _hg_pass).getBytes(), Base64.NO_WRAP));
    }/*from ww w.jav  a  2s  .com*/
    return getRequest;
}

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 {//from   www.  j a v  a2 s  . 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:org.openbmap.soapclient.AsyncUploader.java

/**
 * Sends an authenticated http post request to upload file
 * @param file File to upload (full path)
 * @return true on response code 200, false otherwise
 */// w w  w. ja  v  a2s  .c o m
private UploadResult httpPostRequest(final String file) {
    // TODO check network state
    // @see http://developer.android.com/training/basics/network-ops/connecting.html

    // Adjust HttpClient parameters
    final HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    // HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);
    final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    final HttpPost httppost = new HttpPost(mServer);
    try {
        final MultipartEntity entity = new MultipartEntity();
        entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml"));

        if ((mUser != null) && (mPassword != null)) {
            final String authorizationString = "Basic "
                    + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP);
            httppost.setHeader("Authorization", authorizationString);
        }

        if (mToken != null) {
            entity.addPart(API_FIELD, new StringBody(mToken));
        }

        httppost.setEntity(entity);
        final HttpResponse response = httpclient.execute(httppost);

        final int reply = response.getStatusLine().getStatusCode();
        if (reply == 200) {
            // everything is ok if we receive HTTP 200
            mSize = entity.getContentLength();
            Log.i(TAG, "Uploaded " + file + ": Server reply " + reply);
            return UploadResult.OK;
        } else if (reply == 401) {
            Log.e(TAG, "Wrong username or password");
            return UploadResult.WRONG_PASSWORD;
        } else {
            Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply);
            return UploadResult.ERROR;
        }
        // TODO: redirects (301, 302) are NOT handled here
        // thus if something changes on the server side we're dead here
    } catch (final ClientProtocolException e) {
        Log.e(TAG, e.getMessage());
    } catch (final IOException e) {
        Log.e(TAG, "I/O exception on file " + file);
    }
    return UploadResult.UNDEFINED;
}

From source file:net.olejon.spotcommander.PlaylistsActivity.java

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

    // Allow landscape?
    if (!mTools.allowLandscape())
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // Intent//from w w  w. ja va  2s.c  o  m
    final Intent intent = getIntent();

    // Computer
    final long computerId = mTools.getSharedPreferencesLong(
            "WIDGET_" + intent.getStringExtra(WidgetLarge.WIDGET_LARGE_INTENT_EXTRA) + "_COMPUTER_ID");

    final String[] computer = mTools.getComputer(computerId);

    // Layout
    setContentView(R.layout.activity_playlists);

    // Toolbar
    final Toolbar toolbar = (Toolbar) findViewById(R.id.playlists_toolbar);
    toolbar.setNavigationIcon(R.drawable.ic_close_white_24dp);
    toolbar.setTitle(getString(R.string.playlists_title));

    setSupportActionBar(toolbar);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.playlists_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Listview
    mListView = (ListView) findViewById(R.id.playlists_list);

    // Get playlists
    final Cache cache = new DiskBasedCache(getCacheDir(), 0);

    final Network network = new BasicNetwork(new HurlStack());

    final RequestQueue requestQueue = new RequestQueue(cache, network);

    requestQueue.start();

    final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            computer[0] + "/playlists.php?get_playlists_as_json", null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    requestQueue.stop();

                    try {
                        final ArrayList<String> playlistNames = new ArrayList<>();

                        final Iterator<?> iterator = response.keys();

                        while (iterator.hasNext()) {
                            String key = (String) iterator.next();

                            playlistNames.add(key);
                        }

                        Collections.sort(playlistNames, new Comparator<String>() {
                            @Override
                            public int compare(String string1, String string2) {
                                return string1.compareToIgnoreCase(string2);
                            }
                        });

                        for (String playlistName : playlistNames) {
                            mPlaylistUris.add(response.getString(playlistName));
                        }

                        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(mContext,
                                R.layout.activity_playlists_list_item, playlistNames);

                        mProgressBar.setVisibility(View.GONE);

                        mListView.setAdapter(arrayAdapter);
                        mListView.setVisibility(View.VISIBLE);

                        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                mTools.remoteControl(computerId, "shuffle_play_uri",
                                        mPlaylistUris.get(position));

                                finish();
                            }
                        });
                    } catch (Exception e) {
                        mProgressBar.setVisibility(View.GONE);

                        final TextView textView = (TextView) findViewById(R.id.playlists_error);
                        textView.setVisibility(View.VISIBLE);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    requestQueue.stop();

                    mProgressBar.setVisibility(View.GONE);

                    final TextView textView = (TextView) findViewById(R.id.playlists_error);
                    textView.setVisibility(View.VISIBLE);
                }
            }) {
        @Override
        public HashMap<String, String> getHeaders() {
            final HashMap<String, String> hashMap = new HashMap<>();

            if (!computer[1].equals("") && !computer[2].equals(""))
                hashMap.put("Authorization", "Basic "
                        + Base64.encodeToString((computer[1] + ":" + computer[2]).getBytes(), Base64.NO_WRAP));

            return hashMap;
        }
    };

    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(2500, 0, 0));

    requestQueue.add(jsonObjectRequest);
}

From source file:com.wodify.cordova.plugin.filepicker.FilePicker.java

/**
 * Converts byte array to base 64 representation of string.
 * //from w  w w . ja v  a2s.  c  om
 * @param  bytes
 *         Byte representation of file
 */
private String getBase64EncodedStringFromBytes(byte[] bytes) {
    if (bytes != null && bytes.length > 0) {
        byte[] base64EncodedFile = Base64.encode(bytes, Base64.NO_WRAP);
        return new String(base64EncodedFile);
    }
    return null;
}

From source file:nl.hnogames.domoticz.Utils.RequestUtil.java

/**
 * Method to create a basic HTTP base64 encrypted authentication header
 *
 * @param username Username// w  ww  . j  av  a2s.  c om
 * @param password Password
 * @return Base64 encrypted header map
 */
static Map<String, String> createBasicAuthHeader(String username, String password) {

    Map<String, String> headerMap = new HashMap<>();

    String credentials = username + ":" + password;
    String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
    headerMap.put("Authorization", "Basic " + base64EncodedCredentials);

    return headerMap;
}