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:Main.java

public static String largeFileSha1(File file) {
    InputStream inputStream = null;
    try {//from   w  ww.  j av  a2  s  .co m
        MessageDigest gsha1 = MessageDigest.getInstance("SHA1");
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        inputStream = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[1024];
        int nRead = 0;
        int block = 0;
        int count = 0;
        final int BLOCK_SIZE = 4 * 1024 * 1024;
        while ((nRead = inputStream.read(buffer)) != -1) {
            count += nRead;
            sha1.update(buffer, 0, nRead);
            if (BLOCK_SIZE == count) {
                gsha1.update(sha1.digest());
                sha1 = MessageDigest.getInstance("SHA1");
                block++;
                count = 0;
            }
        }
        if (count != 0) {
            gsha1.update(sha1.digest());
            block++;
        }
        byte[] digest = gsha1.digest();

        byte[] blockBytes = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(block).array();

        byte[] result = ByteBuffer.allocate(4 + digest.length).put(blockBytes, 0, blockBytes.length)
                .put(digest, 0, digest.length).array();

        return Base64.encodeToString(result, Base64.URL_SAFE | Base64.NO_WRAP);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:fr.bde_eseo.eseomega.events.tickets.AsyncEventEmail.java

public AsyncEventEmail(Context context, String email, AppCompatActivity backActivity, UserProfile userProfile,
        int idcmd) {
    this.context = context;
    this.email = email;
    this.backActivity = backActivity;
    this.userProfile = userProfile;
    this.idcmd = idcmd;
    this.b64email = ""; // pre init, prevents from null.getBytes
    try {/* w  w w .j a v a2 s  .  c o  m*/
        this.b64email = Base64.encodeToString(email.getBytes("UTF-8"), Base64.NO_WRAP);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

From source file:com.skubit.android.billing.BillingServiceBinder.java

public static String hash(byte[] message) {
    int flag = Base64.NO_PADDING | Base64.NO_WRAP | Base64.URL_SAFE;
    try {/* w  w w  .ja va2  s.  c o  m*/
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(message);
        return Base64.encodeToString(md.digest(), flag);
    } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {
    }
    return null;
}

From source file:org.sigimera.app.android.backend.network.LoginHttpHelper.java

@Override
protected Boolean doInBackground(String... params) {
    HttpClient httpclient = new MyHttpClient(ApplicationController.getInstance().getApplicationContext());
    HttpPost request = new HttpPost(HOST);
    request.addHeader("Host", "api.sigimera.org:443");

    /**//  ww w.j a  v  a  2 s  . com
     * Basic Authentication for the auth_token fetching:
     * 
     * Authorization: Basic QWxhZGluOnNlc2FtIG9wZW4=
     */
    StringBuffer authString = new StringBuffer();
    authString.append(params[0]);
    authString.append(":");
    authString.append(params[1]);
    String basicAuthentication = "Basic "
            + Base64.encodeToString(authString.toString().getBytes(), Base64.DEFAULT);
    request.addHeader("Authorization", basicAuthentication);

    try {
        HttpResponse result = httpclient.execute(request);

        JSONObject json_response = new JSONObject(
                new BufferedReader(new InputStreamReader(result.getEntity().getContent())).readLine());
        if (json_response.has("auth_token")) {
            SharedPreferences.Editor editor = ApplicationController.getInstance().getSharedPreferences().edit();
            editor.putString("auth_token", json_response.getString("auth_token"));
            return editor.commit();
        } else if (json_response.has("error")) {
            return false;
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return false;
}

From source file:com.parse.ParseEncoder.java

public Object encode(Object object) {
    try {//from   w  ww  .  java 2s  . co m
        if (object instanceof ParseObject) {
            return encodeRelatedObject((ParseObject) object);
        }

        // TODO(grantland): Remove once we disallow mutable nested queries t6941155
        if (object instanceof ParseQuery.State.Builder<?>) {
            ParseQuery.State.Builder<?> builder = (ParseQuery.State.Builder<?>) object;
            return encode(builder.build());
        }

        if (object instanceof ParseQuery.State<?>) {
            ParseQuery.State<?> state = (ParseQuery.State<?>) object;
            return state.toJSON(this);
        }

        if (object instanceof Date) {
            return encodeDate((Date) object);
        }

        if (object instanceof byte[]) {
            JSONObject json = new JSONObject();
            json.put("__type", "Bytes");
            json.put("base64", Base64.encodeToString((byte[]) object, Base64.NO_WRAP));
            return json;
        }

        if (object instanceof ParseFile) {
            return ((ParseFile) object).encode();
        }

        if (object instanceof ParseGeoPoint) {
            ParseGeoPoint point = (ParseGeoPoint) object;
            JSONObject json = new JSONObject();
            json.put("__type", "GeoPoint");
            json.put("latitude", point.getLatitude());
            json.put("longitude", point.getLongitude());
            return json;
        }

        if (object instanceof ParseACL) {
            ParseACL acl = (ParseACL) object;
            return acl.toJSONObject(this);
        }

        if (object instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) object;
            JSONObject json = new JSONObject();
            for (Map.Entry<String, Object> pair : map.entrySet()) {
                json.put(pair.getKey(), encode(pair.getValue()));
            }
            return json;
        }

        if (object instanceof Collection) {
            JSONArray array = new JSONArray();
            for (Object item : (Collection<?>) object) {
                array.put(encode(item));
            }
            return array;
        }

        if (object instanceof ParseRelation) {
            ParseRelation<?> relation = (ParseRelation<?>) object;
            return relation.encodeToJSON(this);
        }

        if (object instanceof ParseFieldOperation) {
            return ((ParseFieldOperation) object).encode(this);
        }

        if (object instanceof ParseQuery.RelationConstraint) {
            return ((ParseQuery.RelationConstraint) object).encode(this);
        }

        if (object == null) {
            return JSONObject.NULL;
        }

    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    // String, Number, Boolean,
    if (isValidType(object)) {
        return object;
    }

    throw new IllegalArgumentException("invalid type for ParseObject: " + object.getClass().toString());
}

From source file:com.amazonaws.mobileconnectors.kinesis.kinesisrecorder.internal.JSONRecordAdapter.java

/**
 * @param source the PutRecordRequest to that will be stored
 * @return JSONObject the json representation of the request
 *//*from  w  w w.ja  v  a  2s  .c om*/
public JSONObject translateFromRecord(PutRecordRequest source) {
    if (null == source) {
        logger.i("The Record provided was null");
        return null;
    }
    if (source.getData() == null || source.getPartitionKey() == null || source.getPartitionKey().isEmpty()
            || source.getStreamName() == null || source.getStreamName().isEmpty()) {
        throw new AmazonClientException("RecordRequests must specify a partition key, stream name, and data");
    }
    if (!source.getData().hasArray()) {
        throw new AmazonClientException("ByteBuffer must be based on array for proper storage");
    }
    JSONObject recordJson = new JSONObject();
    try {
        recordJson.put(DATA_FIELD_KEY, Base64.encodeToString(source.getData().array(), Base64.DEFAULT));
        recordJson.put(STREAM_NAME_FIELD, source.getStreamName());
        recordJson.put(PARTITION_KEY_FIELD, source.getPartitionKey());
        recordJson.putOpt(EXPLICIT_HASH_FIELD, source.getExplicitHashKey());
        recordJson.putOpt(SEQUENCE_NUMBER_FIELD, source.getSequenceNumberForOrdering());
    } catch (JSONException e) {
        throw new AmazonClientException("Unable to convert KinesisRecord to JSON " + e.getMessage());
    }

    return recordJson;
}

From source file:eu.codeplumbers.cosi.api.tasks.DeleteDocumentTask.java

public DeleteDocumentTask(String remoteId, Activity activity) {
    this.activity = activity;
    this.remoteId = remoteId;
    result = "";/*from   w  ww .j av a 2s .  c o m*/

    Device device = Device.registeredDevice();

    // cozy register device url
    this.url = device.getUrl() + "/ds-api/data/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    dialog = new ProgressDialog(activity);
    dialog.setCancelable(false);
    dialog.setMessage("Please wait");
    dialog.setIndeterminate(true);
    dialog.show();

}

From source file:eu.codeplumbers.cosi.api.tasks.RegisterDeviceTask.java

public RegisterDeviceTask(String url, String password, String deviceString, ConnectFragment connectFragment) {
    this.connectFragment = connectFragment;
    this.deviceString = deviceString;
    resultDevice = null;/*from   ww  w .j av  a 2s  .co m*/

    // cozy register device url
    this.url = url + "/device/";

    this.password = password;

    // concatenate username and password with colon for authentication
    final String credentials = "owner" + ":" + password;
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    dialog = new ProgressDialog(connectFragment.getActivity());
    dialog.setCancelable(false);
    dialog.setMessage("Please wait");
    dialog.setIndeterminate(true);
    dialog.show();

}

From source file:de.stadtrallye.rallyesoft.net.AuthProvider.java

private String getBasicAuth(byte[] username, byte[] password) {
    if (username == null) {
        username = new byte[0];
    }/*  ww  w .j  a  v  a  2  s. c  o  m*/

    if (password == null) {
        password = new byte[0];
    }

    final byte[] usernamePassword = new byte[username.length + password.length + 1];

    System.arraycopy(username, 0, usernamePassword, 0, username.length);
    usernamePassword[username.length] = ':';
    System.arraycopy(password, 0, usernamePassword, username.length + 1, password.length);

    return "Basic " + Base64.encodeToString(usernamePassword, Base64.DEFAULT);
}

From source file:eu.codeplumbers.cosi.api.tasks.CheckDesignDocumentsTask.java

public CheckDesignDocumentsTask(Fragment connectFragment) {
    this.connectFragment = connectFragment;

    Device device = Device.registeredDevice();

    // cozy register device url
    this.url = device.getUrl() + "/ds-api/request/???/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    dialog = new ProgressDialog(connectFragment.getActivity());
    dialog.setCancelable(false);/*  w  w w  .  j  a v a2 s .c  om*/
    dialog.setMessage("Please wait");
    dialog.setIndeterminate(true);
    dialog.show();

}