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.hybris.mobile.lib.commerce.helper.SecurityHelper.java

/**
 * Encrypt String associated with a key/*from   ww  w.  j  a  va  2 s .c  om*/
 *
 * @param value The value to encrypt
 * @return encrypted string
 */
public static String encrypt(String value) {
    if (StringUtils.isBlank(value)) {
        throw new IllegalArgumentException();
    }

    String encryptedText = "";

    try {
        Cipher cipher = Cipher.getInstance(CIPHER);
        cipher.init(Cipher.ENCRYPT_MODE, mSecretKeySpec, mIvParameterSpec);
        encryptedText = Base64.encodeToString(cipher.doFinal(value.getBytes()), Base64.NO_CLOSE);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Algorithm not found.");
    } catch (NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) {
        Log.e(TAG, "Exception during encrypt");
    } catch (InvalidKeyException e) {
        Log.e(TAG, "No valid key provided.");
    } catch (InvalidAlgorithmParameterException e) {
        Log.e(TAG, "Algorithm parameter specification is invalid");
    }

    return encryptedText;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

public static JSONObject json(byte[] data) {
    String encoded = Base64.encodeToString(data, Base64.DEFAULT);
    JSONObject obj = new JSONObject();
    try {//from   w w  w.  j a  v a 2 s .  c  o  m
        obj.put("data", encoded);
    } catch (JSONException e) {
    }
    return obj;
}

From source file:com.paymaya.sdk.android.payment.PayMayaPayment.java

/**
 * Request and returns a payment token/*from ww w  . j  av a  2 s .c o m*/
 *
 * @return PaymentToken
 * @throws PayMayaPaymentException
 */
public PaymentToken getPaymentToken() throws PayMayaPaymentException {
    try {
        Request request = new Request(Request.Method.POST,
                PayMayaConfig.getEnvironment() == PayMayaConfig.ENVIRONMENT_PRODUCTION
                        ? BuildConfig.API_PAYMENTS_ENDPOINT_PRODUCTION
                        : BuildConfig.API_PAYMENTS_ENDPOINT_SANDBOX + "/payment-tokens");

        byte[] body = JSONUtils.toJSON(mCard).toString().getBytes();
        request.setBody(body);

        String key = mClientKey + ":";
        String authorization = Base64.encodeToString(key.getBytes(), Base64.DEFAULT);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Basic " + authorization);
        headers.put("Content-Length", Integer.toString(body.length));
        headers.put("Idempotent-Token", mUuidIdempotentKey);
        request.setHeaders(headers);

        AndroidClient androidClient = new AndroidClient();
        Response response = androidClient.call(request);

        //check errors

        return JSONUtils.fromJSONPaymentToken(response.getResponse());
    } catch (JSONException je) {
        throw new PayMayaPaymentException("Unknown Error", je);
    } catch (PayMayaPaymentException ppe) {
        throw new PayMayaPaymentException(ppe.getMessage());
    }

}

From source file:net.networksaremadeofstring.cyllell.Authentication.java

private String SignHeaders(String dataToSign)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchProviderException {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decode(this.PrivateKey.getBytes(), 0));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pk = kf.generatePrivate(spec);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, pk);

    byte[] EncryptedStream = new byte[cipher.getOutputSize(dataToSign.length())];
    try {//  w ww . ja  va2 s .com
        cipher.doFinal(dataToSign.getBytes(), 0, dataToSign.length(), EncryptedStream, 0);
    } catch (ShortBufferException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Base64.encodeToString(EncryptedStream, Base64.NO_WRAP);
}

From source file:com.tapcentive.sdk.service.CouponStatusService.java

/**
 * Execute.//from  w  w w .  j a v a2 s.  c  o m
 *
 * @param coupon the coupon
 */
public void execute(byte[] coupon) {
    Map<String, String> headers = new HashMap<String, String>();
    JSONObject jsonCoupon = new JSONObject();

    if (isConnectedToNetwork()) {
        try {

            headers.put("User-Agent", "consumer");

            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this.context);
            String msiURLString = sharedPref.getString("pref_key_msi_url", "");
            if ((msiURLString != null) && (!msiURLString.equals(""))) {
                String url = msiURLString + "/reward/status";
                jsonCoupon.put("timestamp", (long) System.currentTimeMillis() / 1000);
                jsonCoupon.put("apdu", Base64.encodeToString(coupon, Base64.NO_WRAP));

                Log.d(TAG, "Coupon Data: " + Base64.encodeToString(coupon, Base64.NO_WRAP));

                CustomJsonObjectRequest jsonRequest = new CustomJsonObjectRequest(Method.POST, url, jsonCoupon,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                Log.d(TAG, "Redeemable" + response.toString());
                                callback.isValid(true);
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Log.d(TAG, "Error " + error.toString());
                                if (error == null || error.networkResponse == null) {
                                    callback.isValid(true);
                                    return;
                                }
                                if (error.networkResponse.statusCode == 400
                                        || error.networkResponse.statusCode == 204
                                        || error.networkResponse.statusCode == 403) {
                                    Response<JSONObject> response = CustomJsonObjectRequest.parseError(error);

                                    try {
                                        int detailcode = response.result.getInt("detailcode");
                                        String extraDetails = response.result.getString("details");
                                        Log.d(TAG,
                                                "Got an error: " + error.networkResponse.statusCode
                                                        + " Detail Code from MSI: " + detailcode
                                                        + " Extra Details: " + extraDetails);

                                    } catch (JSONException e) {

                                        e.printStackTrace();
                                    }

                                    callback.isValid(false);
                                    /*TapcentiveConfig config = TapcentiveLibrary.getInstance().getConfig();
                                    if(config.getCallback() != null) {
                                       config.getCallback().onTapcentiveError(new TapcentiveError(TapcentiveErrorType.TapcentiveUnexpectedError));
                                    }*/
                                    return;
                                }
                            }
                        }, headers);

                // Add the request to the queue and execute
                getRequestQueue().add(jsonRequest);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d(TAG, "Exception" + e.toString());
            callback.isValid(true);
            TapcentiveConfig config = TapcentiveLibrary.getInstance().getConfig();
            if (config.getCallback() != null) {
                config.getCallback().onTapcentiveError(
                        new TapcentiveError(this.context, TapcentiveErrorType.TapcentiveUnexpectedError));
            }
        }
    } else {
        TapcentiveConfig config = TapcentiveLibrary.getInstance().getConfig();
        if (config.getCallback() != null) {
            config.getCallback().onTapcentiveError(
                    new TapcentiveError(this.context, TapcentiveErrorType.TapcentiveNetworkUnavailable));
        }
    }
}

From source file:com.ibm.mobileclientaccess.fbauth.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    infoTextView = (TextView) findViewById(R.id.info);

    MCAAuthorizationManager.createInstance(this);

    Logger.setSDKDebugLoggingEnabled(true);

    /*//from   ww w .j a  v  a2s  .c  o m
    There may be issues with the hash key for the app, because it may not be correct when using from command line
    https://developers.facebook.com/docs/android/getting-started#release-key-hash (troubleshoot section)
    Add this code (and remove after getting the correct key (debug? release)) for this will print to log the correct hash code.
     */
    try {
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (PackageManager.NameNotFoundException e) {
    } catch (NoSuchAlgorithmException e) {
    }

    try {
        //Register to the server with backendroute and GUID
        BMSClient.getInstance().initialize(this, backendRoute, backendGUID, BMSClient.REGION_UK);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    // Register the default delegate for Facebook
    FacebookAuthenticationManager.getInstance().register(this);
    Logger.setSDKDebugLoggingEnabled(true);
}

From source file:com.facebook.samples.sessionlogin.LoginUsingActivityActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);/*from   w w  w  .j a  v  a2 s  .co m*/
    Log.v("msg", "hello");
    try {
        PackageInfo info = getPackageManager().getPackageInfo("com.facebook.samples.sessionlogin",
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }

    buttonLoginLogout = (Button) findViewById(R.id.buttonLoginLogout);
    textInstructionsOrLink = (TextView) findViewById(R.id.instructionsOrLink);

    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    Session session = Session.getActiveSession();
    if (session == null) {
        if (savedInstanceState != null) {
            session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
        }
        if (session == null) {
            session = new Session(this);
        }
        Session.setActiveSession(session);
        if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
        }
    }
    Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this,
            Arrays.asList("friends_birthday"));
    session.requestNewReadPermissions(newPermissionsRequest);
    updateView();
}

From source file:com.connectsdk.service.config.WebOSTVServiceConfig.java

private String exportCertificateToPEM(X509Certificate cert) {
    try {/*from  ww w  . j  ava  2  s  .  c  o m*/
        if (cert == null)
            return null;
        return Base64.encodeToString(cert.getEncoded(), Base64.DEFAULT);
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.mimo.service.api.MimoHttpConnection.java

/**
 * Function for Making HTTP "post" request and getting server response.
 * /*from  www .  j a va  2  s  . co m*/
 * @param p_url
 *            - Http Url
 * @throws ClientProtocolException
 * @throws IOException
 * @return HttpResponse- Returns the HttpResponse.
 */
public static synchronized HttpResponse getHttpTransferUrlConnection(String p_url)
        throws ClientProtocolException, IOException // throws
// CustomException
{

    DefaultHttpClient m_httpClient = new DefaultHttpClient();
    HttpPost m_post = new HttpPost(p_url);

    String m_authString = MimoAPIConstants.USERNAME + ":" + MimoAPIConstants.PASSWORD;
    String m_authStringEnc = Base64.encodeToString(m_authString.getBytes(), Base64.NO_WRAP);
    m_post.addHeader(MimoAPIConstants.HEADER_TEXT_AUTHORIZATION,
            MimoAPIConstants.HEADER_TEXT_BASIC + m_authStringEnc);
    HttpResponse m_response = null;

    try {
        m_response = m_httpClient.execute(m_post);
    } catch (IllegalStateException e) {
        if (MimoAPIConstants.DEBUG) {
            Log.e(TAG, e.getMessage());
        }
    }

    return m_response;
}

From source file:edu.umich.eecs.lab11.summon.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.init();
    wv = ((WebView) appView.getEngine().getView());
    wv.addJavascriptInterface(new JavaScriptInterface(getPackageManager()), "gateway");
    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setSupportMultipleWindows(false);
    wv.getSettings().setNeedInitialFocus(false);
    wv.getSettings().setSupportZoom(false);
    wv.getSettings().setAllowFileAccess(true);
    wv.getSettings().setAppCacheEnabled(true);
    wv.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    wv.getSettings().setAppCachePath(wv.getContext().getCacheDir().getAbsolutePath());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        setTaskDescription(new TaskDescription(null, null, Color.parseColor("#FFC107")));
    loadUrl(launchUrl);//from  www. j a v a  2 s  . c o  m
    try {
        InputStream is = getAssets().open("www/summon.android.js");
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        is.close();
        js = "javascript:(function(){ " + "s=document.createElement('script');" + "s.innerHTML = atob('"
                + Base64.encodeToString(buffer, Base64.NO_WRAP) + "'); "
                + "document.querySelector('head').appendChild(s); " + "})()";
    } catch (Exception e) {
        e.printStackTrace();
    }
}