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.joanzapata.PDFViewActivity.java

public void convertQrCode(String _message) {
    // TODO Auto-generated method stub
    // Find screen size
    WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
    Display display = manager.getDefaultDisplay();
    Point point = new Point();
    display.getSize(point);/*from  www . j a  v  a 2 s.  c o m*/
    int width = point.x;
    int height = point.y;
    int smallerDimension = width < height ? width : height;
    smallerDimension = smallerDimension * 3 / 4;

    // Encode with a QR Code image
    QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(_message, null, Contents.Type.TEXT,
            BarcodeFormat.QR_CODE.toString(), smallerDimension);
    try {
        Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        bitmapQrcode = Base64.encodeToString(byteArray, Base64.DEFAULT);

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

}

From source file:net.hiroq.rxwsc.RxWebSocketClient.java

/**
 * create Secret specified RFC6455./*  w  ww.j a va  2 s.  co m*/
 *
 * @return
 */
private String createSecret() {
    byte[] nonce = new byte[16];
    for (int i = 0; i < 16; i++) {
        nonce[i] = (byte) (Math.random() * 256);
    }
    return Base64.encodeToString(nonce, Base64.DEFAULT).trim();
}

From source file:com.game.simple.Game3.java

private void printKeyHash() {
    // Add code to print out the key hash
    try {//from  w  w  w.  j av a2  s  .  com
        PackageInfo info = getPackageManager().getPackageInfo("com.game.simple", 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) {
        Log.d("KeyHash:", e.toString());
    } catch (NoSuchAlgorithmException e) {
        Log.d("KeyHash:", e.toString());
    }
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

private static byte[] sendAuthStep2(Context context, BigInteger clientM, String accountName, BigInteger srpA)
        throws UnsupportedEncodingException, ServerException, NetworkErrorException {
    final HttpPost post = new HttpPost(AUTH2_URI);
    List<BasicNameValuePair> values = new ArrayList<BasicNameValuePair>();
    values.add(new BasicNameValuePair("m",
            Base64.encodeToString(BigIntegers.asUnsignedByteArray(clientM), Base64.DEFAULT)));
    values.add(new BasicNameValuePair("srpA",
            Base64.encodeToString(BigIntegers.asUnsignedByteArray(srpA), Base64.DEFAULT)));

    HttpEntity postEntity = new UrlEncodedFormEntity(values, SyncDataHelper.DEFAULT_CHARSET_NAME);
    post.setHeader(postEntity.getContentEncoding());
    post.setEntity(postEntity);// w w  w .j  a  v  a2s .c  o m

    try {
        final HttpResponse resp = getHttpClient(context).execute(post, createHttpContext(accountName, null));
        return getResponse(resp);
    } catch (IOException ex) {
        throw new NetworkErrorException(ex);
    }
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Returns the string formatted digital signature for the data.
 * /*  ww  w  .ja  v  a 2s.c o  m*/
 * @param key
 *            Private key for signing the data.
 * @param data
 *            Data for which the signature is to be generated.
 * @return signed data with the provide private key.
 * @throws NoSuchAlgorithmException
 *             if the specified algorithm is not available.
 * @throws InvalidKeyException
 *             if privateKey is not valid.
 * @throws SignatureException
 *             if this Signature instance is not initialized properly.
 */
private String getDataSig(PrivateKey key, String data)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {

    // Generate Signature For the data
    Signature signature = Signature.getInstance("SHA256withRSA");
    signature.initSign(key);
    signature.update(data.getBytes());
    byte[] sigBytes = signature.sign();
    return Base64.encodeToString(sigBytes, Base64.DEFAULT);
}

From source file:ch.bfh.evoting.alljoyn.BusHandler.java

/**
 * Initialize AllJoyn/*from  w ww. jav a  2  s .  co m*/
 */
private void doInit() {
    PeerGroupListener pgListener = new PeerGroupListener() {

        @Override
        public void foundAdvertisedName(String groupName, short transport) {
            Intent i = new Intent("advertisedGroupChange");
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);
        }

        @Override
        public void lostAdvertisedName(String groupName, short transport) {
            Intent i = new Intent("advertisedGroupChange");
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);
        }

        @Override
        public void groupLost(String groupName) {
            if (mGroupManager.listHostedGroups().contains(groupName)
                    && mGroupManager.getNumPeers(groupName) == 1) {
                //signal was send because admin stays alone in the group
                //not necessary to manage this case for us
                Log.d(TAG, "Group destroyed event ignored");
                return;
            }
            Log.d(TAG, "Group " + groupName + " was destroyed.");
            Intent i = new Intent("groupDestroyed");
            i.putExtra("groupName", groupName);
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);
        }

        @Override
        public void peerAdded(String busId, String groupName, int numParticipants) {
            Log.d(TAG, "peer added");

            if (amIAdmin) {
                Log.d(TAG, "Sending salt " + Base64.encodeToString(messageEncrypter.getSalt(), Base64.DEFAULT));
                Message msg = obtainMessage(BusHandler.PING);
                Bundle data = new Bundle();
                data.putString("groupName", lastJoinedNetwork);
                data.putString("pingString", Base64.encodeToString(messageEncrypter.getSalt(), Base64.DEFAULT));
                data.putBoolean("encrypted", false);
                data.putSerializable("type", Type.SALT);
                msg.setData(data);
                sendMessage(msg);
            }

            //update UI
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("participantStateUpdate"));

        }

        @Override
        public void peerRemoved(String peerId, String groupName, int numPeers) {
            //update UI
            Log.d(TAG, "peer left");
            Intent intent = new Intent("participantStateUpdate");
            intent.putExtra("action", "left");
            intent.putExtra("id", peerId);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

            super.peerRemoved(peerId, groupName, numPeers);
        }

    };

    ArrayList<BusObjectData> busObjects = new ArrayList<BusObjectData>();
    Handler mainHandler = new Handler(context.getMainLooper());

    Runnable myRunnable = new Runnable() {

        @Override
        public void run() {
            org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(context);
        }

    };
    mainHandler.post(myRunnable);

    busObjects.add(new BusObjectData(mSimpleService, "/SimpleService"));
    mGroupManager = new PeerGroupManager(SERVICE_NAME, pgListener, busObjects);
    mGroupManager.registerSignalHandlers(this);
}

From source file:com.syncedsynapse.kore2.jsonrpc.HostConnection.java

/**
* Auxiliary method to open a HTTP connection.
* This method calls connect() so that any errors are cathced
* @param hostInfo Host info//from   w ww.  j a  va2s .  c o  m
* @return Connection set up
* @throws ApiException
*/
private HttpURLConnection openHttpConnection(HostInfo hostInfo) throws ApiException {
    try {
        //         LogUtils.LOGD(TAG, "Opening HTTP connection.");
        HttpURLConnection connection = (HttpURLConnection) new URL(hostInfo.getJsonRpcHttpEndpoint())
                .openConnection();
        connection.setRequestMethod("POST");
        connection.setConnectTimeout(connectTimeout);
        //connection.setReadTimeout(connectTimeout);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        // http basic authorization
        if ((hostInfo.getUsername() != null) && !hostInfo.getUsername().isEmpty()
                && (hostInfo.getPassword() != null) && !hostInfo.getPassword().isEmpty()) {
            final String token = Base64.encodeToString(
                    (hostInfo.getUsername() + ":" + hostInfo.getPassword()).getBytes(), Base64.DEFAULT);
            connection.setRequestProperty("Authorization", "Basic " + token);
        }

        // Check the connection
        connection.connect();
        return connection;
    } catch (ProtocolException e) {
        // Won't try to catch this
        LogUtils.LOGE(TAG, "Got protocol exception while opening HTTP connection.", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        LogUtils.LOGW(TAG, "Failed to open HTTP connection.", e);
        throw new ApiException(ApiException.IO_EXCEPTION_WHILE_CONNECTING, e);
    }
}

From source file:net.hiroq.rxwsc.RxWebSocketClient.java

/**
 * create SecretValidation specified RFC6455
 *
 * @param secret/*from   ww  w.j  ava 2s . c  o  m*/
 * @return
 */
private String createSecretValidation(String secret) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update((secret + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes());
        return Base64.encodeToString(md.digest(), Base64.DEFAULT).trim();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.electricdynamite.pasty.PastyClient.java

private String getHTTPBasicAuth() {
    if (basicAuthInfo == null) {
        String auth = username + ":" + password;
        this.basicAuthInfo = "Basic " + Base64.encodeToString(auth.getBytes(), Base64.NO_WRAP);
        auth = null;/*from  www.  ja v  a 2 s . com*/
    }
    return this.basicAuthInfo;
}

From source file:com.farmerbb.notepad.fragment.NoteViewFragment.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override//  w  w w  . j ava2  s  . c  o  m
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Set values
    setRetainInstance(true);
    setHasOptionsMenu(true);

    // Get filename of saved note
    filename = getArguments().getString("filename");

    // Change window title
    String title;

    try {
        title = listener.loadNoteTitle(filename);
    } catch (IOException e) {
        title = getResources().getString(R.string.view_note);
    }

    getActivity().setTitle(title);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Bitmap bitmap = ((BitmapDrawable) ContextCompat.getDrawable(getActivity(), R.drawable.ic_recents_logo))
                .getBitmap();

        ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title, bitmap,
                ContextCompat.getColor(getActivity(), R.color.primary));
        getActivity().setTaskDescription(taskDescription);
    }

    // Show the Up button in the action bar.
    ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Animate elevation change
    if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large")
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        LinearLayout noteViewEdit = getActivity().findViewById(R.id.noteViewEdit);
        LinearLayout noteList = getActivity().findViewById(R.id.noteList);

        noteList.animate().z(0f);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
            noteViewEdit.animate()
                    .z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation_land));
        else
            noteViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation));
    }

    // Set up content view
    TextView noteContents = getActivity().findViewById(R.id.textView);
    markdownView = getActivity().findViewById(R.id.markdownView);

    // Apply theme
    SharedPreferences pref = getActivity().getSharedPreferences(getActivity().getPackageName() + "_preferences",
            Context.MODE_PRIVATE);
    ScrollView scrollView = getActivity().findViewById(R.id.scrollView);
    String theme = pref.getString("theme", "light-sans");
    int textSize = -1;
    int textColor = -1;

    String fontFamily = null;

    if (theme.contains("light")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary));
            noteContents.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
        }

        if (markdownView != null) {
            markdownView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary);
        }

        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
    }

    if (theme.contains("dark")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark));
            noteContents
                    .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
        }

        if (markdownView != null) {
            markdownView
                    .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark);
        }

        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
    }

    if (theme.contains("sans")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SANS_SERIF);

        if (markdownView != null)
            fontFamily = "sans-serif";
    }

    if (theme.contains("serif")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SERIF);

        if (markdownView != null)
            fontFamily = "serif";
    }

    if (theme.contains("monospace")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.MONOSPACE);

        if (markdownView != null)
            fontFamily = "monospace";
    }

    switch (pref.getString("font_size", "normal")) {
    case "smallest":
        textSize = 12;
        break;
    case "small":
        textSize = 14;
        break;
    case "normal":
        textSize = 16;
        break;
    case "large":
        textSize = 18;
        break;
    case "largest":
        textSize = 20;
        break;
    }

    if (noteContents != null)
        noteContents.setTextSize(textSize);

    String css = "";
    if (markdownView != null) {
        String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom)
                / getResources().getDisplayMetrics().density) + "px";
        String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right)
                / getResources().getDisplayMetrics().density) + "px";
        String fontSize = " " + Integer.toString(textSize) + "px";
        String fontColor = " #" + StringUtils.remove(Integer.toHexString(textColor), "ff");
        String linkColor = " #" + StringUtils.remove(
                Integer.toHexString(new TextView(getActivity()).getLinkTextColors().getDefaultColor()), "ff");

        css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:"
                + fontFamily + "; " + "font-size:" + fontSize + "; " + "color:" + fontColor + "; " + "}"
                + "a { " + "color:" + linkColor + "; " + "}";

        markdownView.getSettings().setJavaScriptEnabled(false);
        markdownView.getSettings().setLoadsImagesAutomatically(false);
        markdownView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException | FileUriExposedException e) {
                        /* Gracefully fail */ }
                else
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        /* Gracefully fail */ }

                return true;
            }
        });
    }

    // Load note contents
    try {
        contentsOnLoad = listener.loadNote(filename);
    } catch (IOException e) {
        showToast(R.string.error_loading_note);

        // Add NoteListFragment or WelcomeFragment
        Fragment fragment;
        if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-normal"))
            fragment = new NoteListFragment();
        else
            fragment = new WelcomeFragment();

        getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteListFragment")
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
    }

    // Set TextView contents
    if (noteContents != null)
        noteContents.setText(contentsOnLoad);

    if (markdownView != null)
        markdownView.loadMarkdown(contentsOnLoad,
                "data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT));

    // Show a toast message if this is the user's first time viewing a note
    final SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    firstLoad = sharedPref.getInt("first-load", 0);
    if (firstLoad == 0) {
        // Show dialog with info
        DialogFragment firstLoad = new FirstViewDialogFragment();
        firstLoad.show(getFragmentManager(), "firstloadfragment");

        // Set first-load preference to 1; we don't need to show the dialog anymore
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("first-load", 1);
        editor.apply();
    }

    // Detect single and double-taps using GestureDetector
    final GestureDetector detector = new GestureDetector(getActivity(),
            new GestureDetector.OnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return false;
                }

                @Override
                public void onShowPress(MotionEvent e) {
                }

                @Override
                public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                    return false;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                }

                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                    return false;
                }

                @Override
                public boolean onDown(MotionEvent e) {
                    return false;
                }
            });

    detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true)) {
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putBoolean("show_double_tap_message", false);
                editor.apply();
            }

            Bundle bundle = new Bundle();
            bundle.putString("filename", filename);

            Fragment fragment = new NoteEditFragment();
            fragment.setArguments(bundle);

            getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteEditFragment")
                    .commit();

            return false;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true) && showMessage) {
                showToastLong(R.string.double_tap);
                showMessage = false;
            }

            return false;
        }

    });

    if (noteContents != null)
        noteContents.setOnTouchListener((v, event) -> {
            detector.onTouchEvent(event);
            return false;
        });

    if (markdownView != null)
        markdownView.setOnTouchListener((v, event) -> {
            detector.onTouchEvent(event);
            return false;
        });
}