Example usage for android.util Base64 encodeToString

List of usage examples for android.util Base64 encodeToString

Introduction

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

Prototype

public static String encodeToString(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated String with the result.

Usage

From source file:android.locationprivacy.algorithm.Webservice.java

@Override
public Location obfuscate(Location location) {
    // We do it this way to run network connection in main thread. This
    // way is not the normal one and does not comply to best practices,
    // but the main thread must wait for the obfuscation service reply anyway.
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);//  w w  w . j a  v a 2  s  . com

    final String HOST_ADDRESS = configuration.getString("host");
    String username = configuration.getString("username");
    String password = configuration.getString("secret_password");

    Location newLoc = new Location(location);
    double lat = location.getLatitude();
    double lon = location.getLongitude();

    String urlString = HOST_ADDRESS;
    urlString += "?lat=" + lat;
    urlString += "&lon=" + lon;
    URL url;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Error: could not build URL");
        Log.e(TAG, e.getMessage());
        return null;
    }
    HttpsURLConnection connection = null;
    JSONObject json = null;
    InputStream is = null;
    try {
        connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        connection.setRequestProperty("Authorization",
                "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
        is = connection.getInputStream();

    } catch (IOException e) {
        Log.e(TAG, "Error while connectiong to " + url.toString());
        Log.e(TAG, e.getMessage());
        return null;
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    try {
        String line = reader.readLine();
        System.out.println("Line " + line);
        json = new JSONObject(line);
        newLoc.setLatitude(json.getDouble("lat"));
        newLoc.setLongitude(json.getDouble("lon"));
    } catch (IOException e) {
        Log.e(TAG, "Error: could not read from BufferedReader");
        Log.e(TAG, e.getMessage());
        return null;
    } catch (JSONException e) {
        Log.e(TAG, "Error: could not read from JSON");
        Log.e(TAG, e.getMessage());
        return null;
    }
    connection.disconnect();
    return newLoc;
}

From source file:ca.rmen.android.networkmonitor.app.email.Emailer.java

/**
 * Append the given attachments to the message which is being written by the given writer.
 *
 * @param boundary separates each file attachment
 *///from  w w w  .  ja  va 2s  .c o  m
private static void appendAttachments(Writer writer, String boundary, Collection<File> attachments)
        throws IOException {
    for (File attachment : attachments) {
        ByteArrayOutputStream fileOs = new ByteArrayOutputStream((int) attachment.length());
        FileInputStream fileIs = new FileInputStream(attachment);
        try {
            IoUtil.copy(fileIs, fileOs);
        } finally {
            IoUtil.closeSilently(fileIs, fileOs);
        }
        final String mimeType = attachment.getName().substring(attachment.getName().indexOf(".") + 1);
        writer.write("--" + boundary + "\n");
        writer.write("Content-Type: application/" + mimeType + "; name=\"" + attachment.getName() + "\"\n");
        writer.write("Content-Disposition: attachment; filename=\"" + attachment.getName() + "\"\n");
        writer.write("Content-Transfer-Encoding: base64\n\n");
        String encodedFile = Base64.encodeToString(fileOs.toByteArray(), Base64.DEFAULT);
        writer.write(encodedFile);
        writer.write("\n");
    }
}

From source file:com.samknows.measurement.util.LoginHelper.java

public static String getCredentialsEncoded() {
    return Base64.encodeToString((getCredentials()).getBytes(), Base64.NO_WRAP);
}

From source file:org.xwiki.android.authenticator.rest.XWikiConnector.java

public static String userSignIn(String server, String user, String pass, String authType) throws Exception {

    Log.d("xwiki", "userSignIn");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    String url = server + "/rest/";

    HttpGet httpGet = new HttpGet(url);

    httpGet.addHeader("Authorization",
            "Basic " + Base64.encodeToString((user + ':' + pass).getBytes(), Base64.NO_WRAP));

    HttpParams params = new BasicHttpParams();
    params.setParameter("username", user);
    params.setParameter("password", pass);
    httpGet.setParams(params);/* w  w w.  ja  v  a 2s. c  o  m*/

    HttpResponse response = httpClient.execute(httpGet);
    int error = response.getStatusLine().getStatusCode();
    if (error != 200) {
        throw new Exception("Error signing-in [" + url + "] with error code [" + error + "]");
    }

    return null;
}

From source file:com.ericrgon.postmark.BaseFragmentActivity.java

private byte[] getSalt() {
    SharedPreferences preferences = getSharedPreferences(CREDENTIALS_PREF_FILE, MODE_PRIVATE);
    byte[] salt;//from  ww  w . j av a2s .c  om
    if (preferences.contains(SALT_PREF)) {
        salt = Base64.decode(preferences.getString(SALT_PREF, ""), Base64.DEFAULT);
    } else {
        //Generate a new salt if one doesn't exist.
        salt = SecurityUtil.generateSalt().getEncoded();
        SharedPreferences.Editor editor = preferences.edit().putString(SALT_PREF,
                Base64.encodeToString(salt, Base64.DEFAULT));
        editor.apply();
    }

    return salt;
}

From source file:org.openihs.seendroid.lib.Connection.java

private void addHeaders(HttpMessage message) {
    String credentials = Base64.encodeToString((this.username + ":" + this.password).getBytes(),
            Base64.DEFAULT);//from  w w w.j  a va 2 s .c  o  m
    message.addHeader("User-agent", "SeenDroid");
    message.addHeader("Authorization", "Basic " + credentials.substring(0, credentials.length() - 1));
}

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

public boolean checkRawMessageBytes(InputStream in) {
    try {/*  w  w  w  .  ja  v  a  2  s  .c o  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:com.polatic.pantaudki.home.HomeFragment.java

@Deprecated
public static String encodeTobase64(Bitmap image) {
    Bitmap img = image;/* w  w w .j a  va2s  .co m*/
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    img.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    byte[] b = byteArrayOutputStream.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

    return imageEncoded;
}

From source file:br.com.vpsa.oauth2android.token.RefreshToken.java

/**
 * This method is special for the RefreshToken. It makes an authorized request to
 * the TokenEndpoint (AccessTokenServer) to request a new AccessToken. Therefore
 * it presents the RefreshToken in a basic http Authorization Header. <br>
 * You may use GET for the http Method, but it is recommended to use POST. If
 * the <code>method</code> parameter is empty POST will be used.<br>
 * The result is an Response-Instance containing the new Access-Token or throwing
 * an Exception if the server responds with an error.
 * @param client <code>Client</code> of this application
 * @param server <code>Server</code> Instance with the service-providers endpoints
 * @param method <code>String</code> value of the http-method used.
 * @return the <code>Response</code> of the request containing the AccessToken
 * @throws InvalidRequestException the request is missing a parameter or is otherwise invalid
 * @throws InvalidClientException the client could not be identified
 * @throws InvalidGrantException the authorization grant is not valid
 * @throws UnauthorizedClientException the token is not valid or is of the wrong type
 * @throws UnsupportedGrantTypeException the client used an unsupported method for the authorization grant
 * @throws InvalidScopeException the scope is incomplete or invalid
 * @throws OAuthException if this is catched, no other {@link org.gerstner.oauth2android.exception.OAuthException} extending Exception will be thrown.
 * @throws IOException a connection error occurred during the request
 *//*ww w.jav  a2  s  . co  m*/
public Response executeRefreshRequest(Client client, Server server, String method)
        throws IOException, InvalidRequestException, InvalidClientException, InvalidGrantException,
        UnauthorizedClientException, UnsupportedGrantTypeException, InvalidScopeException, OAuthException {
    HttpClient httpClient = new DefaultHttpClient();
    Response response;
    if (method == null) {
        method = "";
    }
    if (method.equalsIgnoreCase(Connection.HTTP_METHOD_GET)) {
        String parameterString = "grant_type=refresh_token&client_id=" + client.getClientID()
                + "&refresh_token=" + this.getToken();
        HttpGet httpGet = new HttpGet(server.getAccessTokenServer() + "?" + parameterString);

        String authorization = Base64.encodeToString(
                (client.getClientID() + ":" + client.getClientSecret()).getBytes(), Base64.DEFAULT);
        Header header = new BasicHeader("Authorization", "Basic " + authorization);
        httpGet.addHeader(header);

        response = new Response(httpClient.execute(httpGet));

    } else {
        HttpPost httpPost = new HttpPost(server.getAccessTokenServer());
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

        List<NameValuePair> parameterList = new ArrayList<NameValuePair>();
        parameterList.add(new BasicNameValuePair("grant_type", "refresh_token"));
        parameterList.add(new BasicNameValuePair("client_id", client.getClientID()));
        parameterList.add(new BasicNameValuePair("refresh_token", this.getToken()));
        httpPost.setEntity(new UrlEncodedFormEntity(parameterList));

        response = new Response(httpClient.execute(httpPost));
    }

    return response;
}

From source file:com.grarak.kerneladiutor.utils.Utils.java

public static String encodeString(String text) {
    try {/*from w w  w.  j  a  v  a  2 s.c o m*/
        return Base64.encodeToString(text.getBytes("UTF-8"), Base64.DEFAULT);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}