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.google.ipc.invalidation.ticl.android.AndroidChannel.java

/** Returns the web encoded version of the channel network endpoint ID for HTTP requests. */
@Override/*from ww w.  jav  a2  s .  co m*/
protected String getWebEncodedEndpointId() {
    NetworkEndpointId networkEndpointId = getNetworkId();
    return Base64.encodeToString(networkEndpointId.toByteArray(),
            Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
}

From source file:com.badlogic.gdx.pay.android.ouya.PurchaseManagerAndroidOUYA.java

public void requestPurchase(final Product product)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", product.getIdentifier());
    // purchaseRequest.put("testing", "true"); // !!!! This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);/* ww w  .  j av  a 2 s  .c  o  m*/
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, ouyaPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    purchasable = new Purchasable(product.getIdentifier(), Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
            Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (ouyaOutstandingPurchaseRequests) {
        ouyaOutstandingPurchaseRequests.put(uniqueId, product);
    }
}

From source file:br.com.GUI.perfil.PerfilPersonal.java

public void atualizarDadosPersonal() {

    if (nome.getText().toString() == null) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
        alertDialog.setTitle("Ateno");
        alertDialog.setMessage("Por favor, digite o seu nome");
        alertDialog.setIcon(R.drawable.critical);
        alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();/*  w w w. ja  va 2s.  c  o m*/
            }
        });

        alertDialog.show();
    } else {

        byte[] byteFoto = ImageUtils.bitmapToByteArray(bmp);
        String fotoPersonal = Base64.encodeToString(byteFoto, 0);

        String dataDeNascimento = dataNascimentoDia.getValue() + "/" + dataNascimentoMes.getValue() + "/"
                + dataNascimentoAno.getValue();

        final Personal p = new Personal(telefone.getText().toString(), nome.getText().toString(),
                dataDeNascimento, email.getText().toString(), pref.getString("sexo", null),
                pref.getString("usuario", null), pref.getString("senha", null), fotoPersonal);

        boolean r = p.atualizarPersonalWeb();

        if (r && p.atualizar(b, byteFoto)) {
            Toast.makeText(getActivity(), "Atualizado com Sucesso", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getActivity(), "Erro ao salvar no servidor", Toast.LENGTH_SHORT).show();

        }
    }
}

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

private void runDefault() throws IOException {
    Log.v("TwAjax", "runDefault URL=" + myUrl);

    // Create a new HttpClient and Get/Post Header
    DefaultHttpClient httpclient = getNewHttpClient();
    setHttpClientProxy(httpclient);/*from ww w. j ava2 s . c  om*/
    httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    //final HttpParams params = new BasicHttpParams();
    HttpClientParams.setRedirecting(httpclient.getParams(), false);

    HttpRequestBase m;
    if (myMethod == "POST") {
        m = new HttpPost(myUrl);
        ((HttpPost) m).setEntity(new UrlEncodedFormEntity(myPostData, "utf-8"));
    } else {
        m = new HttpGet(myUrl);
    }
    m.addHeader("Host", m.getURI().getHost());
    if (twSession != null)
        m.addHeader("Cookie", "twnetSID=" + twSession);
    httpclient.setCookieStore(cookieStoreManager);

    //generate auth header if user/pass are provided to this class
    if (this.myHttpAuthUser != null) {
        m.addHeader("Authorization", "Basic " + Base64
                .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP));
    }
    // Execute HTTP Get/Post Request
    HttpResponse response = httpclient.execute(m);
    //InputStream is = response.getEntity().getContent();
    myHttpStatus = response.getStatusLine().getStatusCode();
    if (this.fetchHeader != null) {
        this.fetchHeaderResult = response.getHeaders(this.fetchHeader);
        Header[] h = response.getAllHeaders();
        for (Header hh : h)
            Log.d(TAG, "Header " + hh.getName() + "=" + hh.getValue());

    } else if (this.downloadToFile != null) {
        Log.v("TwAjax", "runDefault downloadToFile=" + downloadToFile);
        // download the file
        InputStream input = new BufferedInputStream(response.getEntity().getContent());
        OutputStream output = new FileOutputStream(downloadToFile);

        byte data[] = new byte[1024];

        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            //publishProgress((int)(total*100/lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } else if (this.convertToBitmap) {
        myBmpResult = BitmapFactory.decodeStream(response.getEntity().getContent());
    } else if (this.convertToXml) {
        try {
            myXmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(response.getEntity().getContent());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }

    } else {
        myResult = EntityUtils.toString(response.getEntity(), "UTF-8");
    }
    //BufferedInputStream bis = new BufferedInputStream(is);
    //ByteArrayBuffer baf = new ByteArrayBuffer(50);

    //int current = 0;
    //while((current = bis.read()) != -1){
    //    baf.append((byte)current);
    //}

    //myResult = new String(baf.toByteArray(), "utf-8");
    success = true;
}

From source file:com.dh.perfectoffer.event.framework.net.network.NetworkConnectionImpl.java

private static String createAuthenticationHeader(UsernamePasswordCredentials credentials) {
    StringBuilder sb = new StringBuilder();
    sb.append(credentials.getUserName()).append(":").append(credentials.getPassword());
    return "Basic " + Base64.encodeToString(sb.toString().getBytes(), Base64.NO_WRAP);
}

From source file:com.charabia.SmsViewActivity.java

@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
    case SMS_KEY_CONTACT:
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();/*ww  w .  ja va  2s.c  om*/

            ContentResolver cr = getContentResolver();

            Cursor cursor = cr.query(uri, new String[] { Contacts.LOOKUP_KEY }, null, null, null);

            String lookup = null;

            if (cursor.moveToFirst()) {
                lookup = cursor.getString(0);
            }

            cursor.close();

            if (lookup == null) {
                Toast.makeText(this, R.string.unexpected_error, Toast.LENGTH_LONG).show();
                return;
            }

            cursor = cr.query(Data.CONTENT_URI, new String[] { Phone.NUMBER },
                    Data.MIMETYPE + "=? AND " + Data.LOOKUP_KEY + "=?",
                    new String[] { Phone.CONTENT_ITEM_TYPE, lookup }, null);

            ArrayList<String> options = new ArrayList<String>();

            while (cursor.moveToNext()) {
                options.add(cursor.getString(0));
            }

            cursor.close();

            final String[] phoneList = options.toArray(new String[0]);

            Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.send_invit_on_phone);
            builder.setItems(phoneList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {

                    keypair = tools.loadKeyPair();
                    RSAPublicKey pubKey = (RSAPublicKey) keypair.getPublic();

                    byte[] encoded = pubKey.getModulus().toByteArray();

                    byte[] data = new byte[3 + encoded.length];

                    data[0] = Tools.MAGIC[0];
                    data[1] = Tools.MAGIC[1];
                    data[2] = Tools.PUBLIC_KEY_TYPE;

                    System.arraycopy(encoded, 0, data, 3, encoded.length);

                    tools.sendData(phoneList[i], Tools.INVITATION, "", data);

                }
            });

            builder.create().show();
        } else {
            Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
        }
        break;
    case IntentIntegrator.REQUEST_CODE:
        if (resultCode == RESULT_OK) {
            try {
                String contents = data.getStringExtra("SCAN_RESULT");
                @SuppressWarnings("unused")
                String format = data.getStringExtra("SCAN_RESULT_FORMAT");
                // Handle successful scan

                // TODO: add more tests control

                String[] infos = contents.split("\n");

                Cipher rsaCipher = Cipher.getInstance(Tools.RSA_CIPHER_ALGO);

                if (mode == MODE_ESCLAVE) {
                    // Save key and show crypted key on QRCode
                    key = tools.generateKeyAES().getEncoded();

                    KeyFactory keyFact = KeyFactory.getInstance("RSA");

                    PublicKey pubkey = keyFact.generatePublic(
                            new RSAPublicKeySpec(new BigInteger(infos[1]), new BigInteger(infos[2])));

                    rsaCipher.init(Cipher.ENCRYPT_MODE, pubkey);

                    int blockSize = rsaCipher.getBlockSize();

                    int nbBlock = key.length / blockSize;
                    int reste = key.length % blockSize;

                    byte[] cryptedKey = new byte[(nbBlock + 1) * rsaCipher.getOutputSize(blockSize)];

                    int offset = 0;

                    for (int i = 0; i < nbBlock; i++) {
                        offset += rsaCipher.doFinal(key, i * blockSize, blockSize, cryptedKey, offset);
                    }

                    rsaCipher.doFinal(key, nbBlock * blockSize, reste, cryptedKey, offset);

                    IntentIntegrator.shareText(SmsViewActivity.this,
                            prefPhoneNumber + "\n" + Base64.encodeToString(cryptedKey, Base64.NO_WRAP));

                } else {

                    // We have read crypted key, so decode it
                    rsaCipher.init(Cipher.DECRYPT_MODE, keypair.getPrivate());

                    byte[] cryptedData = Base64.decode(infos[1], Base64.NO_WRAP);

                    int blockSize = rsaCipher.getBlockSize();
                    int nbBlock = cryptedData.length / blockSize;

                    int offset = 0;

                    byte[] tempKey = new byte[(nbBlock + 1) * blockSize];

                    for (int i = 0; i < nbBlock; i++) {
                        offset += rsaCipher.doFinal(cryptedData, i * blockSize, blockSize, tempKey, offset);
                    }

                    key = new byte[offset];
                    System.arraycopy(tempKey, 0, key, 0, offset);
                }

                phoneNumber = infos[0];

                // store the key
                // TODO dialog to confirm add contact in mode SLAVE
                try {
                    new Tools(this).updateOrCreateContactKey(phoneNumber, key);
                } catch (NoContactException e) {
                    e.printStackTrace();
                    // propose to add contact
                    Intent newIntent = new Intent(Intents.SHOW_OR_CREATE_CONTACT);
                    newIntent.setData(Uri.fromParts("tel", phoneNumber, null));
                    startActivityForResult(newIntent, ADD_CONTACT);
                    return;
                }

                Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG)
                        .show();

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
            }

        } else {
            // TODO: string
            Toast.makeText(this, R.string.fail_reading_tag, Toast.LENGTH_LONG).show();
        }
        break;
    case ADD_CONTACT:
        try {
            tools.updateOrCreateContactKey(phoneNumber, key);
            Toast.makeText(this, getString(R.string.contact_added) + "\n" + phoneNumber, Toast.LENGTH_LONG)
                    .show();
        } catch (NoContactException e) {
            e.printStackTrace();
            Toast.makeText(this, R.string.error_create_key, Toast.LENGTH_LONG).show();
        }
        break;
    }

}

From source file:org.quantumbadger.redreader.reddit.api.RedditOAuth.java

public static FetchAccessTokenResult fetchAnonymousAccessTokenSynchronous(final Context context) {

    final String uri = ACCESS_TOKEN_URL;
    StatusLine responseStatus = null;//from w w  w  . j av  a 2 s.  co m

    try {
        final HttpClient httpClient = CacheManager.createHttpClient(context);

        final HttpPost request = new HttpPost(uri);

        final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs
                .add(new BasicNameValuePair("grant_type", "https://oauth.reddit.com/grants/installed_client"));
        nameValuePairs.add(new BasicNameValuePair("device_id", "DO_NOT_TRACK_THIS_DEVICE"));
        request.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        request.addHeader("Authorization", "Basic "
                + Base64.encodeToString((CLIENT_ID + ":").getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));

        final HttpResponse response = httpClient.execute(request);
        responseStatus = response.getStatusLine();

        if (responseStatus.getStatusCode() != 200) {
            return new FetchAccessTokenResult(FetchAccessTokenResultStatus.UNKNOWN_ERROR,
                    new RRError(context.getString(R.string.error_unknown_title),
                            context.getString(R.string.message_cannotlogin), null, responseStatus,
                            request.getURI().toString()));
        }

        final JsonValue jsonValue = new JsonValue(response.getEntity().getContent());
        jsonValue.buildInThisThread();
        final JsonBufferedObject responseObject = jsonValue.asObject();

        final String accessTokenString = responseObject.getString("access_token");

        if (accessTokenString == null) {
            throw new RuntimeException("Null access token: " + responseObject.getString("error"));
        }

        final AccessToken accessToken = new AccessToken(accessTokenString);

        return new FetchAccessTokenResult(accessToken);

    } catch (IOException e) {
        return new FetchAccessTokenResult(FetchAccessTokenResultStatus.CONNECTION_ERROR,
                new RRError(context.getString(R.string.error_connection_title),
                        context.getString(R.string.error_connection_message), e, responseStatus, uri));

    } catch (Throwable t) {
        return new FetchAccessTokenResult(FetchAccessTokenResultStatus.UNKNOWN_ERROR,
                new RRError(context.getString(R.string.error_unknown_title),
                        context.getString(R.string.message_cannotlogin), t, responseStatus, uri));
    }
}

From source file:com.example.kjpark.smartclass.NoticeTab.java

private void setSignatureLayout() {
    LayoutInflater dialogInflater = (LayoutInflater) getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    dialogView = dialogInflater.inflate(R.layout.dialog_signature, null);
    mSignaturePad = (SignaturePad) dialogView.findViewById(R.id.signature_pad);

    clearButton = (Button) dialogView.findViewById(R.id.clearButton);
    sendButton = (Button) dialogView.findViewById(R.id.sendButton);

    mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
        @Override/*from w  w w .j ava2  s . c  o  m*/
        public void onSigned() {
            clearButton.setEnabled(true);
            sendButton.setEnabled(true);
        }

        @Override
        public void onClear() {
            clearButton.setEnabled(false);
            sendButton.setEnabled(false);
        }
    });
    clearButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mSignaturePad.clear();
        }
    });
    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //send sign image to server
            ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() {
                Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
                private String num = Integer.toString(currentViewItem);

                @Override
                protected Boolean doInBackground(String... params) {
                    URL obj = null;
                    try {
                        obj = new URL("http://165.194.104.22:5000/enroll_sign");
                        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

                        //implement below code if token is send to server
                        con = ConnectServer.getInstance().setHeader(con);

                        con.setDoOutput(true);

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        signatureBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        byte[] b = baos.toByteArray();
                        String sign_image = Base64.encodeToString(b, Base64.DEFAULT);
                        Log.d(TAG, "sign_image: " + sign_image.length());

                        String parameter = URLEncoder.encode("num", "UTF-8") + "="
                                + URLEncoder.encode(num, "UTF-8");
                        parameter += "&" + URLEncoder.encode("sign_image", "UTF-8") + "="
                                + URLEncoder.encode(sign_image, "UTF-8");

                        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
                        wr.write(parameter);
                        wr.flush();

                        BufferedReader rd = null;

                        if (con.getResponseCode() == 200) {
                            // ? 
                            rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

                            Log.d("---- success ----", rd.toString());

                        } else {
                            // ? 
                            rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                            Log.d("---- failed ----", String.valueOf(rd.readLine()));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Boolean aBoolean) {

                }
            });
            ConnectServer.getInstance().execute();
            signature_dialog.dismiss();
            loadBoards();
        }
    });
}

From source file:ca.ualberta.app.activity.CreateAnswerActivity.java

/**
 * compress the image to 64kb//w w  w. j  a va  2  s. c  om
 * 
 * @return return the imageString after compressed
 */
private String compressImage() {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    int quality = 100;
    while (stream.toByteArray().length > 65536 && quality != 0) {
        stream.reset();
        image.compress(Bitmap.CompressFormat.JPEG, quality, stream);
        quality -= 10;
    }
    if (quality == 0)
        return null;
    return Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
}

From source file:org.uoyabause.android.YabauseHandler.java

void doReportCurrentGame(int rating, String message, boolean screenshot) {
    current_report = new ReportContents();
    current_report._rating = rating;//  ww  w  . j  av a  2 s  .c  o m
    current_report._message = message;
    current_report._screenshot = screenshot;
    _report_status = REPORT_STATE_INIT;

    String gameinfo = YabauseRunnable.getGameinfo();
    if (gameinfo != null) {

        try {

            showDialog();
            AsyncReport asyncTask = new AsyncReport(this);
            current_game_info = new JSONObject(gameinfo);

            DateFormat dateFormat = new SimpleDateFormat("_yyyy_MM_dd_HH_mm_ss");
            Date date = new Date();

            String screen_shot_save_path = YabauseStorage.getStorage().getScreenshotPath()
                    + YabauseRunnable.getCurrentGameCode() + dateFormat.format(date) + ".png";

            if (YabauseRunnable.screenshot(screen_shot_save_path) != 0) {
                dismissDialog();
                return;
            }

            InputStream inputStream = new FileInputStream(screen_shot_save_path);//You can get an inputStream using any IO API
            byte[] bytes;
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
                dismissDialog();
                return;
            }
            bytes = output.toByteArray();
            String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);

            JSONObject jsonObjimg = new JSONObject();
            jsonObjimg.put("data", encodedString);
            jsonObjimg.put("filename", screen_shot_save_path);
            jsonObjimg.put("content_type", "image/png");
            JSONObject jsonObjgame = current_game_info.getJSONObject("game");
            jsonObjgame.put("title_image", jsonObjimg);

            if (screenshot) {
                current_report._screenshot_base64 = encodedString;
                current_report._screenshot_save_path = screen_shot_save_path;
            }
            //asyncTask.execute("http://192.168.0.7:3000/api/", YabauseRunnable.getCurrentGameCode());
            asyncTask.execute("http://www.uoyabause.org/api/", YabauseRunnable.getCurrentGameCode());

            return;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}