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:com.mpower.mintel.android.utilities.WebUtils.java

public static String getSHA512(String input) {
    String retval = "";
    try {//from w  w  w .  jav  a 2 s .  com
        MessageDigest m = MessageDigest.getInstance("SHA-512");
        byte[] out = m.digest(input.getBytes());
        retval = Base64.encodeToString(out, Base64.NO_WRAP);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return retval;
}

From source file:de.niklasmerz.cordova.fingerprint.Fingerprint.java

public static void onAuthenticated(boolean withFingerprint) {
    JSONObject resultJson = new JSONObject();
    String errorMessage = "";
    boolean createdResultJson = false;
    try {// w ww .  java2  s.com

        if (withFingerprint) {
            // If the user has authenticated with fingerprint, verify that using cryptography and
            // then return the encrypted token
            byte[] encrypted = tryEncrypt();
            resultJson.put("withFingerprint", Base64.encodeToString(encrypted, 0 /* flags */));
        } else {
            // Authentication happened with backup password.
            resultJson.put("withPassword", true);

            // if failed to init cipher because of InvalidKeyException, create new key
            if (!initCipher()) {
                createKey();
            }
        }
        createdResultJson = true;
    } catch (BadPaddingException e) {
        errorMessage = "Failed to encrypt the data with the generated key:" + " BadPaddingException:  "
                + e.getMessage();
        Log.e(TAG, errorMessage);
    } catch (IllegalBlockSizeException e) {
        errorMessage = "Failed to encrypt the data with the generated key: " + "IllegalBlockSizeException: "
                + e.getMessage();
        Log.e(TAG, errorMessage);
    } catch (JSONException e) {
        errorMessage = "Failed to set resultJson key value pair: " + e.getMessage();
        Log.e(TAG, errorMessage);
    }

    if (createdResultJson) {
        mCallbackContext.success(resultJson);
        mPluginResult = new PluginResult(PluginResult.Status.OK);
    } else {
        mCallbackContext.error(errorMessage);
        mPluginResult = new PluginResult(PluginResult.Status.ERROR);
    }
    mCallbackContext.sendPluginResult(mPluginResult);
}

From source file:com.collecdoo.fragment.main.RegisterDriverPhotoFragment.java

private String encodeBitmapBase64(Bitmap bitmap) {
    if (bitmap == null)
        return "";

    return Base64.encodeToString(UIHelper.convertBitmapToByteArray(bitmap), Base64.NO_WRAP);
}

From source file:com.hybris.mobile.lib.commerce.service.OCCServiceHelper.java

@Override
public boolean authenticate(final ResponseReceiverEmpty responseReceiver, final String requestId,
        final QueryLogin queryLogin, final boolean shouldUseCache, final List<View> viewsToDisable,
        final OnRequestListener onRequestListener) {

    if (queryLogin == null || StringUtils.isBlank(queryLogin.getUsername())) {
        throw new IllegalArgumentException("The username parameter is missing from the query");
    }//  w  ww  .  j  a v a2 s. com

    Map<String, Object> parameters = buildLoginParameters(queryLogin, Constants.Login.CLIENT_ID,
            Constants.Login.GRANT_TYPE_LOGIN);

    // Constructing the headers map
    Map<String, String> headers = new HashMap<>();
    String authValue = "Basic "
            + Base64.encodeToString(Constants.Login.AUTHORIZATION.getBytes(), Base64.NO_WRAP);
    headers.put(Constants.Login.PARAM_HEADER_AUTHORIZATION, authValue);

    // We want to save the user information before sending back the result
    ResponseReceiver<UserInformation> responseReceiverBeforeCallback = new ResponseReceiver<UserInformation>() {

        @Override
        public void onResponse(Response<UserInformation> response) {
            // Saving the user information for future authorized requests
            saveUserInformation(response.getData(), queryLogin.getUsername());

            responseReceiver.onResponse(Response.createResponse(new EmptyResponse(), requestId, true));
        }

        @Override
        public void onError(Response<ErrorList> response) {
            responseReceiver.onError(response);
        }
    };

    return execute(responseReceiverBeforeCallback,
            DataConverter.Helper.build(UserInformation.class, ErrorList.class, null), shouldUseCache, requestId,
            UrlHelper.getWebserviceTokenUrl(mContext, mConfiguration), parameters, headers, false,
            HttpUtils.HTTP_METHOD_POST, viewsToDisable, onRequestListener);
}

From source file:com.facebook.unity.FB.java

/**
 * Provides the key hash to solve the openSSL issue with Amazon
 * @return key hash//w w  w. j  a  v  a  2  s.c o  m
 */
@TargetApi(Build.VERSION_CODES.FROYO)
public static String getKeyHash() {
    try {
        // In some cases the unity activity may not exist. This can happen when we are
        // completing a login and unity activity was killed in the background. In this
        // situation it's not necessary to send back the keyhash since the app will overwrite
        // the value with the value they get during the init call and the unity activity
        // wil be created by the time init is called.
        Activity activity = getUnityActivity();
        if (activity == null) {
            return "";
        }

        PackageInfo info = activity.getPackageManager().getPackageInfo(activity.getPackageName(),
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            String keyHash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
            Log.d(TAG, "KeyHash: " + keyHash);
            return keyHash;
        }
    } catch (NameNotFoundException e) {
    } catch (NoSuchAlgorithmException e) {
    }
    return "";
}

From source file:com.mobile.natal.natalchart.NetworkUtilities.java

private static String getB64Auth(String login, String pass) {
    String source = login + ":" + pass;
    String ret = "Basic " + Base64.encodeToString(source.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP);
    return ret;//from   w  ww .j  av a2s  . co m
}

From source file:im.delight.android.webrequest.WebRequest.java

protected String getAuthDigest() {
    if (mUsername != null && mPassword != null) {
        return "Basic " + Base64.encodeToString((mUsername + ":" + mPassword).getBytes(), Base64.NO_WRAP);
    } else {/*w  ww  .  j  a  v  a 2  s .co m*/
        return "";
    }
}

From source file:com.fa.mastodon.activity.EditProfileActivity.java

private static String bitmapToBase64(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    IOUtils.closeQuietly(stream);/*ww w .  ja  v a2s.  co m*/
    return "data:image/png;base64," + Base64.encodeToString(byteArray, Base64.DEFAULT);
}

From source file:com.ledger.android.u2f.bridge.MainActivity.java

private String createU2FResponseSign(U2FContext context, byte[] signature) {
    try {/*from  w  w w  .  jav a 2s  .  c  o m*/
        JSONObject response = new JSONObject();
        response.put(TAG_JSON_TYPE, SIGN_RESPONSE_TYPE);
        response.put(TAG_JSON_REQUESTID, context.getRequestId());
        JSONObject responseData = new JSONObject();
        responseData.put(TAG_JSON_KEYHANDLE, Base64.encodeToString(context.getChosenKeyHandle(),
                Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING));
        responseData.put(TAG_JSON_SIGNATUREDATA, Base64.encodeToString(signature, 0, signature.length - 2,
                Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING));
        String clientData = createClientData(context);
        responseData.put(TAG_JSON_CLIENTDATA, Base64.encodeToString(clientData.getBytes("UTF-8"),
                Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING));
        response.put(TAG_JSON_RESPONSEDATA, responseData);
        return response.toString();
    } catch (Exception e) {
        Log.e(TAG, "Error encoding request");
        return null;
    }
}

From source file:com.android.mms.service.http.NetworkAwareHttpClient.java

/**
 * Generates a cURL command equivalent to the given request.
 *///from   w  w  w .j  ava  2s.c  o m
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    // add in the method
    builder.append("-X ");
    builder.append(request.getMethod());
    builder.append(" ");

    for (Header header : request.getAllHeaders()) {
        if (!logAuthToken && (header.getName().equals("Authorization") || header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);

                if (isBinaryContent(request)) {
                    String base64 = Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
                    builder.insert(0, "echo '" + base64 + "' | base64 -d > /tmp/$$.bin; ");
                    builder.append(" --data-binary @/tmp/$$.bin");
                } else {
                    String entityString = stream.toString();
                    builder.append(" --data-ascii \"").append(entityString).append("\"");
                }
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}