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.danielme.muspyforandroid.services.MuspyClient.java

private void setAuthHeader(AbstractHttpMessage abstractHttpMessage, Context context)
        throws AuthorizationException {
    abstractHttpMessage.setHeader(AUTHORIZATION, "Basic " + Base64.encodeToString(
            (Utils.getEmail(context) + ":" + Utils.getPass(context)).getBytes(), Base64.NO_WRAP));
}

From source file:com.shopify.buy.dataprovider.BuyClient.java

/**
 * Post a credit card to Shopify's card server and associate it with a Checkout
 *
 * @param card     the {@link CreditCard} to associate
 * @param checkout the {@link Checkout} to associate the card with
 * @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
 *///from  w w  w .  j  a v  a  2s  .  c  o m
public void storeCreditCard(final CreditCard card, final Checkout checkout, final Callback<Checkout> callback) {
    if (card == null) {
        throw new NullPointerException("card cannot be null");
    }

    if (checkout == null) {
        throw new NullPointerException("checkout cannot be null");
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            PaymentSessionCheckoutWrapper dataWrapper = new PaymentSessionCheckoutWrapper();
            PaymentSessionCheckout data = new PaymentSessionCheckout();
            data.setToken(checkout.getToken());
            data.setCreditCard(card);
            data.setBillingAddress(checkout.getBillingAddress());
            dataWrapper.setCheckout(data);

            RequestBody body = RequestBody.create(jsonMediateType, new Gson().toJson(dataWrapper));

            Request request = new Request.Builder().url(checkout.getPaymentUrl()).post(body)
                    .addHeader("Authorization",
                            "Basic " + Base64.encodeToString(apiKey.getBytes(), Base64.NO_WRAP))
                    .addHeader("Content-Type", "application/json").addHeader("Accept", "application/json")
                    .build();
            try {
                com.squareup.okhttp.Response httpResponse = httpClient.newCall(request).execute();
                String paymentSessionId = parsePaymentSessionResponse(httpResponse);
                checkout.setPaymentSessionId(paymentSessionId);

                Response retrofitResponse = new Response(request.urlString(), httpResponse.code(),
                        httpResponse.message(), Collections.<Header>emptyList(), null);
                callback.success(checkout, retrofitResponse);
            } catch (IOException e) {
                e.printStackTrace();

                callback.failure(RetrofitError.unexpectedError(request.urlString(), e));
            }
        }
    }).start();
}

From source file:com.pdftron.pdf.utils.Utils.java

public static String encryptIt(Context context, String value) {
    String cryptoPass = context.getString(context.getApplicationInfo().labelRes);
    try {/*from   ww w .j a va2 s . c  om*/
        DESKeySpec keySpec = new DESKeySpec(cryptoPass.getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        byte[] clearText = value.getBytes("UTF8");
        // Cipher is not thread safe
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        String encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT);
        Log.d("MiscUtils", "Encrypted: " + value + " -> " + encrypedValue);
        return encrypedValue;

    } catch (Exception e) {
        Log.d(e.getClass().getName(), e.getMessage());
    }
    return value;
}

From source file:de.wikilab.android.friendica01.TwAjax.java

private void runFileUpload() throws IOException {

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "d1934afa-f2e4-449b-99be-8be6ebfec594";
    Log.i("Andfrnd/TwAjax", "URL=" + getURL());
    URL url = new URL(getURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);/*from w  w  w .  j  a  va 2 s .  com*/
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    //generate auth header if user/pass are provided to this class
    if (this.myHttpAuthUser != null) {
        connection.setRequestProperty("Authorization", "Basic " + Base64
                .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP));
    }
    //Log.i("Andfrnd","-->"+connection.getRequestProperty("Authorization")+"<--");

    connection.setRequestProperty("Host", url.getHost());
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    for (NameValuePair nvp : myPostData) {
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + nvp.getName() + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd + nvp.getValue() + lineEnd);
    }
    for (PostFile pf : myPostFiles) {
        pf.writeToStream(outputStream, boundary);
    }
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    myHttpStatus = connection.getResponseCode();

    outputStream.flush();
    outputStream.close();

    if (myHttpStatus < 400) {
        myResult = convertStreamToString(connection.getInputStream());
    } else {
        myResult = convertStreamToString(connection.getErrorStream());
    }

    success = true;
}

From source file:com.swisscom.safeconnect.backend.BackendConnector.java

public static String getBase64EncodedString(String string) {
    try {//from w  w w  .  j  a v a2  s .  com
        String b64EncodedPhoneNumber = Base64.encodeToString(string.getBytes("UTF-8"), Base64.URL_SAFE);
        return URLEncoder.encode(b64EncodedPhoneNumber, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        if (BuildConfig.DEBUG)
            Log.e(Config.TAG, "Exception when encoding url string", e);
        return null;
    }
}

From source file:com.phonegap.plugins.blinkid.BlinkIdScanner.java

/**
 * Called when the scanner intent completes.
 * /*from ww  w .ja va 2 s .c o  m*/
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param data
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == REQUEST_CODE) {

        if (resultCode == ScanCard.RESULT_OK) {

            // First, obtain recognition result
            RecognitionResults results = data.getParcelableExtra(ScanCard.EXTRAS_RECOGNITION_RESULTS);
            // Get scan results array. If scan was successful, array will contain at least one element.
            // Multiple element may be in array if multiple scan results from single image were allowed in settings.
            BaseRecognitionResult[] resultArray = results.getRecognitionResults();

            // Each recognition result corresponds to active recognizer. There are 7 types of
            // recognizers available (PDF417, USDL, Bardecoder, ZXing, MRTD, UKDL and MyKad),
            // so there are 7 types of results available.

            JSONArray resultsList = new JSONArray();

            for (BaseRecognitionResult res : resultArray) {
                try {
                    if (res instanceof Pdf417ScanResult) { // check if scan result is result of Pdf417 recognizer
                        resultsList.put(buildPdf417Result((Pdf417ScanResult) res));
                    } else if (res instanceof BarDecoderScanResult) { // check if scan result is result of BarDecoder recognizer
                        resultsList.put(buildBarDecoderResult((BarDecoderScanResult) res));
                    } else if (res instanceof ZXingScanResult) { // check if scan result is result of ZXing recognizer
                        resultsList.put(buildZxingResult((ZXingScanResult) res));
                    } else if (res instanceof MRTDRecognitionResult) { // check if scan result is result of MRTD recognizer
                        resultsList.put(buildMRTDResult((MRTDRecognitionResult) res));
                    } else if (res instanceof USDLScanResult) { // check if scan result is result of US Driver's Licence recognizer
                        resultsList.put(buildUSDLResult((USDLScanResult) res));
                    } else if (res instanceof EUDLRecognitionResult) { // check if scan result is result of EUDL recognizer
                        resultsList.put(buildUKDLResult((EUDLRecognitionResult) res));
                    } else if (res instanceof MyKadRecognitionResult) { // check if scan result is result of MyKad recognizer
                        resultsList.put(buildMyKadResult((MyKadRecognitionResult) res));
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG, "Error parsing " + res.getClass().getName());
                }
            }

            try {
                JSONObject root = new JSONObject();
                root.put(RESULT_LIST, resultsList);
                if (mImageType != IMAGE_NONE) {
                    Image resultImage = ImageHolder.getInstance().getLastImage();
                    if (resultImage != null) {
                        Bitmap resultImgBmp = resultImage.convertToBitmap();
                        if (resultImgBmp != null) {
                            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            boolean success = resultImgBmp.compress(Bitmap.CompressFormat.JPEG,
                                    COMPRESSED_IMAGE_QUALITY, byteArrayOutputStream);
                            if (success) {
                                String resultImgBase64 = Base64
                                        .encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
                                root.put(RESULT_IMAGE, resultImgBase64);
                            }
                            try {
                                byteArrayOutputStream.close();
                            } catch (IOException ignorable) {
                            }
                        }
                        ImageHolder.getInstance().clear();
                    }
                }
                root.put(CANCELLED, false);
                this.callbackContext.success(root);
            } catch (JSONException e) {
                Log.e(LOG_TAG, "This should never happen");
            }

        } else if (resultCode == ScanCard.RESULT_CANCELED) {
            JSONObject obj = new JSONObject();
            try {
                obj.put(CANCELLED, true);

            } catch (JSONException e) {
                Log.e(LOG_TAG, "This should never happen");
            }
            this.callbackContext.success(obj);

        } else {
            this.callbackContext.error("Unexpected error");
        }
    }
}

From source file:com.orange.oidc.tim.service.SDCardStorage.java

public String getClientSecretBasic() {

    String bearer = (TIM_client_id + ":" + TIM_secret);
    return Base64.encodeToString(bearer.getBytes(), Base64.DEFAULT);
}

From source file:com.facebook.Settings.java

public static String getApplicationSignature(Context context) {
    if (context == null) {
        return null;
    }//from   w w w. j  a va 2  s.  c  om
    PackageManager packageManager = context.getPackageManager();
    if (packageManager == null) {
        return null;
    }

    String packageName = context.getPackageName();
    PackageInfo pInfo;
    try {
        pInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
    } catch (PackageManager.NameNotFoundException e) {
        return null;
    }

    Signature[] signatures = pInfo.signatures;
    if (signatures == null || signatures.length == 0) {
        return null;
    }

    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        return null;
    }

    md.update(pInfo.signatures[0].toByteArray());
    return Base64.encodeToString(md.digest(), Base64.URL_SAFE | Base64.NO_PADDING);
}

From source file:com.microsoft.aad.adal.Oauth2.java

public String encodeProtocolState() {
    String state = String.format("a=%s&r=%s", mRequest.getAuthority(), mRequest.getResource());
    return Base64.encodeToString(state.getBytes(), Base64.NO_PADDING | Base64.URL_SAFE);
}

From source file:reportsas.com.formulapp.Formulario.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if (data != null) {
            if (data.hasExtra("data")) {

                Bitmap photobmp = (Bitmap) data.getParcelableExtra("data");

                // iv.setImageBitmap(photobmp);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                photobmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] imageBytes = baos.toByteArray();
                String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

                if (parametroCam == null) {
                    parametroCam = new ParametrosRespuesta(2);
                }/*from  www  .  j  a v  a  2  s.c o  m*/

                parametroCam.setValor(encodedImage);

                // prueba.setText(encodedImage);
                //    new MyAsyncTask(Formulario.this)
                //          .execute("POST",encodedImage, HTTP_EVENT);
            }

        }
    }

    if (requestCode == MY_REQUEST_CODE && resultCode == Pdf417ScanActivity.RESULT_OK) {
        // First, obtain scan results array. If scan was successful, array will contain at least one element.
        // Multiple element may be in array if multiple scan results from single image were allowed in settings.

        Parcelable[] resultArray = data
                .getParcelableArrayExtra(Pdf417ScanActivity.EXTRAS_RECOGNITION_RESULT_LIST);

        StringBuilder sb = new StringBuilder();

        for (Parcelable p : resultArray) {
            if (p instanceof Pdf417ScanResult) { // check if scan result is result of Pdf417 recognizer
                Pdf417ScanResult result = (Pdf417ScanResult) p;
                // getStringData getter will return the string version of barcode contents
                String barcodeData = result.getStringData();

                // isUncertain getter will tell you if scanned barcode contains some uncertainties
                boolean uncertainData = result.isUncertain();
                // getRawData getter will return the raw data information object of barcode contents
                BarcodeDetailedData rawData = result.getRawData();
                // BarcodeDetailedData contains information about barcode's binary layout, if you
                // are only interested in raw bytes, you can obtain them with getAllData getter
                byte[] rawDataBuffer = rawData.getAllData();
                DataR = rawData.toString();

                String[] arrayElements = DataR.split("Element #");
                String Nombre = "", Apellido = "", cedula = "", fecha = "", dia, mes, ano;
                if (arrayElements.length >= 7) {
                    String[] auxliarArray = arrayElements[7].split("decoded\\):");

                    String strDatos = auxliarArray[1];
                    char[] ca = strDatos.toCharArray();
                    for (int i = 0; i < strDatos.length(); i++) {
                        if (Character.isLetter(ca[i])) //Si es letra
                            Apellido += ca[i]; //Salto de lnea e imprimimos el carcter
                        else //Si no es letra
                            cedula += ca[i]; //Imprimimos el carcter
                    }
                    Apellido = Apellido.trim();
                    cedula = (cedula.replaceAll("\n", "")).trim();
                    if (cedula.length() == 0) {
                        auxliarArray = arrayElements[5].split("decoded\\):");
                        strDatos = auxliarArray[1];
                        ca = strDatos.toCharArray();
                        Apellido = "";
                        for (int i = 0; i < strDatos.length(); i++) {
                            if (Character.isLetter(ca[i])) //Si es letra
                                Apellido += ca[i]; //Salto de lnea e imprimimos el carcter
                            else //Si no es letra
                                cedula += ca[i]; //Imprimimos el carcter
                        }
                        Apellido = Apellido.trim();
                        cedula = (cedula.replaceAll("\n", "")).trim();
                        cedula = cedula.substring(cedula.length() - 10, cedula.length());
                        cedula = eliminarceros(cedula);
                        auxliarArray = arrayElements[9].split("decoded\\):");
                        Nombre = (auxliarArray[1].replaceAll("\n", "")).trim();

                    } else {

                        cedula = eliminarceros(cedula);
                        auxliarArray = arrayElements[11].split("decoded\\):");
                        Nombre = (auxliarArray[1].replaceAll("\n", "")).trim();
                    }

                    auxliarArray = result.getStringData().toString().split(Nombre);
                    strDatos = auxliarArray[1];
                    ca = strDatos.toCharArray();
                    Boolean result_ciclo = true;
                    int i = 0;
                    while (result_ciclo) {
                        if (Character.isDigit(ca[i])) {
                            fecha += ca[i];
                        }
                        if (fecha.length() >= 9) {
                            result_ciclo = false;
                        }
                        i++;
                    }
                    fecha = fecha.substring(1, fecha.length());
                } else {
                    int puntoI = 0;
                    if (barcodeData.indexOf("1F") > 0) {
                        puntoI = barcodeData.indexOf("1F");
                    } else if (barcodeData.indexOf("0M") > 0) {
                        puntoI = barcodeData.indexOf("0M");
                    } else if (barcodeData.indexOf("0F") > 0) {
                        puntoI = barcodeData.indexOf("0F");
                    } else if (barcodeData.indexOf("1M") > 0) {
                        puntoI = barcodeData.indexOf("1M");
                    } else {

                    }
                    if (puntoI > 0) {
                        String seb = barcodeData.substring(1, puntoI);
                        fecha = barcodeData.substring(puntoI + 2, puntoI + 10);

                        int posL = 0, posE;
                        char[] ca = seb.toCharArray();
                        for (int w = seb.length() - 1; w > 0; w--) {
                            if (Character.isLetter(ca[w])) {
                                posL = w;
                                break;
                            }
                        }
                        seb = seb.substring(1, posL + 1);
                        ca = seb.toCharArray();
                        for (int w = seb.length() - 1; w > 0; w--) {
                            if (Character.isLetter(ca[w])) {
                                Nombre = ca[w] + Nombre;
                                posL = w;
                            } else {
                                break;
                            }
                        }
                        seb = seb.substring(1, posL);
                        ca = seb.toCharArray();
                        for (int w = seb.length() - 1; w > 0; w--) {
                            if (Character.isDigit(ca[w])) {
                                posL = w;
                                break;
                            }
                        }

                        for (int w = posL + 1; w <= seb.length(); w++) {
                            if (Character.isLetter(ca[w])) {
                                Apellido += ca[w];
                            } else {
                                break;
                            }
                        }

                        cedula = seb.substring(posL - 9, posL + 1);
                        cedula = eliminarceros(cedula);
                    } else {
                        fecha = "";
                    }
                }
                if (fecha.length() == 0) {
                    parametroScan = null;

                    Toast toast1 = Toast.makeText(this, "Los datos de codigo no pudieron ser interpretados!",
                            Toast.LENGTH_SHORT);

                    toast1.show();

                } else {
                    dia = fecha.substring(6, 8);
                    mes = fecha.substring(4, 6);
                    ano = fecha.substring(0, 4);
                    fecha = dia + "/" + mes + "/" + ano;

                    Infocadena = "Nombre: \n" + Nombre + ".\nApellido: \n" + Apellido + ". \nCedula: \n"
                            + cedula + ". \nFecha de Nacimiento: \n" + fecha + ".";
                    if (parametroScan == null) {
                        parametroScan = new ParametrosRespuesta(3);

                    }
                    parametroScan.setValor(Infocadena);

                }

                //  new MyAsyncTask(Formulario.this)
                //        .execute("POST",Infocadena, HTTP_EVENT);

            } else if (p instanceof BarDecoderScanResult) { // check if scan result is result of BarDecoder recognizer
                /* BarDecoderScanResult result = (BarDecoderScanResult) p;
                 // with getBarcodeType you can obtain barcode type enum that tells you the type of decoded barcode
                 BarcodeType type = result.getBarcodeType();
                 // as with PDF417, getStringData will return the string contents of barcode
                 String barcodeData = result.getStringData();
                 if(checkIfDataIsUrlAndCreateIntent(barcodeData)) {
                return;
                 } else {
                sb.append(type.name());
                sb.append(" string data:\n");
                sb.append(barcodeData);
                sb.append("\n\n\n");=
                 }*/
            } else if (p instanceof ZXingScanResult) { // check if scan result is result of ZXing recognizer
                /* ZXingScanResult result= (ZXingScanResult) p;
                 // with getBarcodeType you can obtain barcode type enum that tells you the type of decoded barcode
                 BarcodeType type = result.getBarcodeType();
                 // as with PDF417, getStringData will return the string contents of barcode
                 String barcodeData = result.getStringData();
                 if(checkIfDataIsUrlAndCreateIntent(barcodeData)) {
                return;
                 } else {
                sb.append(type.name());
                sb.append(" string data:\n");
                sb.append(barcodeData);
                sb.append("\n\n\n");
                 }*/
            } else if (p instanceof USDLScanResult) { // check if scan result is result of US Driver's Licence recognizer
                USDLScanResult result = (USDLScanResult) p;

                // USDLScanResult can contain lots of information extracted from driver's licence
                // you can obtain information using the getField method with keys defined in
                // USDLScanResult class

                String name = result.getField(USDLScanResult.kCustomerFullName);

                sb.append(result.getTitle());
                sb.append("\n\n");
                sb.append(result.toString());
            }
        }

    }
}