Example usage for android.util Base64 DEFAULT

List of usage examples for android.util Base64 DEFAULT

Introduction

In this page you can find the example usage for android.util Base64 DEFAULT.

Prototype

int DEFAULT

To view the source code for android.util Base64 DEFAULT.

Click Source Link

Document

Default values for encoder/decoder flags.

Usage

From source file:com.webXells.ImageResizer.ImageResizePlugin.java

@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
    JSONObject params;/*from   ww w . j ava 2s  .c o  m*/
    String imageData;
    String imageDataType;
    String format;
    Bitmap bmp;
    Log.d("PLUGIN", action);
    try {
        // parameters (forst object of the json array)
        params = data.getJSONObject(0);
        // image data, either base64 or url
        imageData = params.getString("data");
        // which data type is that, defaults to base64
        imageDataType = params.has("imageDataType") ? params.getString("imageDataType")
                : DEFAULT_IMAGE_DATA_TYPE;
        // which format should be used, defaults to jpg
        format = params.has("format") ? params.getString("format") : DEFAULT_FORMAT;
        // create the Bitmap object, needed for all functions
        bmp = getBitmap(imageData, imageDataType);
    } catch (JSONException e) {
        callbackContext.error(e.getMessage());
        return false;
    } catch (IOException e) {
        callbackContext.error(e.getMessage());
        return false;
    }
    // resize the image
    Log.d("PLUGIN", "passed init");
    if (action.equals("resizeImage")) {
        try {
            double widthFactor;
            double heightFactor;

            // compression quality
            int quality = params.getInt("quality");

            // Pixels or Factor resize
            String resizeType = params.getString("resizeType");

            // Get width and height parameters
            double width = params.getDouble("width");
            double height = params.getDouble("height");

            if (resizeType.equals(RESIZE_TYPE_PIXEL)) {
                widthFactor = width / ((double) bmp.getWidth());
                heightFactor = height / ((double) bmp.getHeight());
            } else {
                widthFactor = width;
                heightFactor = height;
            }

            Bitmap resized = getResizedBitmap(bmp, (float) widthFactor, (float) heightFactor);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (format.equals(FORMAT_PNG)) {
                resized.compress(Bitmap.CompressFormat.PNG, quality, baos);
            } else {
                resized.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            }
            byte[] b = baos.toByteArray();
            String returnString = Base64.encodeToString(b, Base64.DEFAULT);
            // return object
            JSONObject res = new JSONObject();
            res.put("imageData", returnString);
            res.put("width", resized.getWidth());
            res.put("height", resized.getHeight());
            callbackContext.success(res);
            return true;
        } catch (JSONException e) {
            callbackContext.error(e.getMessage());
            return false;
        }
    } else if (action.equals("imageSize")) {
        try {

            JSONObject res = new JSONObject();
            res.put("width", bmp.getWidth());
            res.put("height", bmp.getHeight());
            Log.d("PLUGIN", "finished get image size");
            callbackContext.success(res);
            return true;
        } catch (JSONException e) {
            callbackContext.error(e.getMessage());
            return false;
        }
    } else if (action.equals("storeImage")) {
        try {
            // Obligatory Parameters, throw JSONException if not found
            String filename = params.getString("filename");
            filename = (filename.contains(".")) ? filename : filename + "." + format;
            String directory = params.getString("directory");
            directory = directory.startsWith("/") ? directory : "/" + directory;
            int quality = params.getInt("quality");

            OutputStream outStream;
            // store the file locally using the external storage directory
            File file = new File(Environment.getExternalStorageDirectory().toString() + directory, filename);
            try {
                outStream = new FileOutputStream(file);
                if (format.equals(FORMAT_PNG)) {
                    bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream);
                } else {
                    bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
                }
                outStream.flush();
                outStream.close();
                JSONObject res = new JSONObject();
                res.put("url", "file://" + file.getAbsolutePath());
                callbackContext.success(res);
                return true;
            } catch (IOException e) {
                callbackContext.error(e.getMessage());
                return false;
            }
        } catch (JSONException e) {
            callbackContext.error(e.getMessage());
            return false;
        }
    }
    Log.d("PLUGIN", "unknown action");
    return false;
}

From source file:com.amanmehara.programming.android.adapters.LanguageAdapter.java

private Consumer<String> getLogoResponseCallback(String url, boolean cacheHit, String languageName,
        ViewHolder viewHolder) {/*from   w  w  w. ja va  2  s  .  c  om*/
    return response -> {
        try {
            if (!cacheHit) {
                sharedPreferences.edit().putString(url, response).apply();
            }
            JSONObject icon = new JSONObject(response);
            byte[] imageBlob = Base64.decode(icon.getString("content"), Base64.DEFAULT);
            int imageBlobLength = imageBlob.length;
            Bitmap logo = BitmapFactory.decodeByteArray(imageBlob, 0, imageBlobLength);
            logos.put(languageName, imageBlob);
            viewHolder.languageImageView.setImageBitmap(logo);
        } catch (JSONException e) {
            Log.e(TAG, e.getMessage());
            if (cacheHit) {
                sharedPreferences.edit().remove(url).apply();
            }
            viewHolder.languageImageView.setImageResource(R.drawable.ic_circle_logo);
        }
    };
}

From source file:jp.alessandro.android.iab.Security.java

/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key./*www  .  ja  v  a 2s . c o  m*/
 *
 * @param encodedPublicKey rsa public key generated by Google Play Developer Console
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
protected PublicKey generatePublicKey(String encodedPublicKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException {

    byte[] decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
    return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
}

From source file:com.hg.development.apps.messagenotifier_v1.Utils.Utility.java

/**
 * Permet de convertir une photo d'un contact  un objet String.
 * @param bitmap photo du contact  convertir.
 * @return//from ww  w  .ja v a2  s  .c o  m
 */
public static String BitMapToString(Bitmap bitmap) {
    try {
        ByteArrayOutputStream ByteStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, ByteStream);
        byte[] b = ByteStream.toByteArray();
        String temp = Base64.encodeToString(b, Base64.DEFAULT);

        return temp;
    } catch (Exception ex) {
        return null;
    }
}

From source file:ca.uwaterloo.magic.goodhikes.ProfileActivity.java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_CANCELED)
        return;//  ww  w  . j a  v  a  2  s  .  c om
    if (requestCode == FROM_GALLERY)
        if (resultCode == RESULT_OK) {
            Uri selectedImage = data.getData();
            profile_image.setImageURI(selectedImage);
            try {
                /* uri -> bitmap -> encoded string
                 * store string in sharedpreference */
                image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
                ByteArrayOutputStream byte_out = new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG, 90, byte_out); //image is the bitmap object
                image = Bitmap.createScaledBitmap(image, 640, 480, false);
                byte[] byte_arr = byte_out.toByteArray();
                String encoded = Base64.encodeToString(byte_arr, Base64.DEFAULT);
                Log.d(LOG_TAG, "encoded string length: " + encoded.length());
                String input = "uid=";
                input += URLEncoder.encode(user.getId(), "UTF-8");
                input += "&image_str=";
                input += URLEncoder.encode(encoded, "UTF-8");
                new SyncImage().execute(input);
                userManager.setImage(encoded);
                //Log.d(LOG_TAG, "set image str: " + userManager.getImage());
            } catch (Exception e) {
                Log.d(LOG_TAG, e.getMessage());
            }
        }
}

From source file:com.microsoft.graph.connect.AuthenticationManager.java

public JSONObject getClaims(String idToken) {
    JSONObject retValue = null;/*  w  w  w.  j  ava  2  s.  c o m*/
    String payload = idToken.split("[.]")[1];

    try {
        // The token payload is in the 2nd element of the JWT
        String jsonClaims = new String(Base64.decode(payload, Base64.DEFAULT), "UTF-8");
        retValue = new JSONObject(jsonClaims);
    } catch (JSONException | IOException e) {
        Log.e(TAG, "Couldn't decode id token: " + e.getMessage());
    }
    return retValue;
}

From source file:mobisocial.musubi.nearby.scanner.GpsScannerTask.java

@Override
protected List<NearbyItem> doInBackground(Void... params) {
    if (DBG)/*from   ww w . j av a  2  s . c o  m*/
        Log.d(TAG, "Scanning for nearby gps...");
    while (!mmLocationScanComplete) {
        synchronized (mmLocationResult) {
            if (!mmLocationScanComplete) {
                try {
                    if (DBG)
                        Log.d(TAG, "Waiting for location results...");
                    mmLocationResult.wait();
                } catch (InterruptedException e) {
                }
            }
        }
    }
    if (DBG)
        Log.d(TAG, "Got location " + mmLocation);
    if (isCancelled()) {
        return null;
    }

    try {
        if (DBG)
            Log.d(TAG, "Querying gps server...");
        Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/findgroup");

        StringBuffer sb = new StringBuffer();
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(uri.toString());
        httpPost.addHeader("Content-Type", "application/json");
        JSONArray buckets = new JSONArray();

        double lat = mmLocation.getLatitude();
        double lng = mmLocation.getLongitude();

        long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2);
        Log.i(TAG, "coords: " + Arrays.toString(coords));

        //TODO: encrypt coords with mmPassword

        for (long c : coords) {
            MessageDigest md;
            try {
                byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes();
                md = MessageDigest.getInstance("SHA-256");
                ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length);
                b.putLong(c);
                b.put(obfuscate);
                String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT);
                buckets.put(buckets.length(), secret_bucket);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("your platform does not support sha256", e);
            }
        }
        Log.i(TAG, "buckets: " + buckets);
        httpPost.setEntity(new StringEntity(buckets.toString()));
        try {
            HttpResponse execute = client.execute(httpPost);
            InputStream content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                if (isCancelled()) {
                    return null;
                }
                sb.append(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashSet<Pair<TByteArrayList, TByteArrayList>> dupes = new HashSet<Pair<TByteArrayList, TByteArrayList>>();

        String response = sb.toString();
        JSONArray groupsJSON = new JSONArray(response);
        Log.d(TAG, "Got " + groupsJSON.length() + " groups");
        for (int i = 0; i < groupsJSON.length(); i++) {
            try {
                String s_enc_data = groupsJSON.get(i).toString();
                byte[] enc_data = Base64.decode(s_enc_data, Base64.DEFAULT);
                byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes());
                byte[] data;

                Cipher cipher;
                AlgorithmParameterSpec iv_spec;
                SecretKeySpec sks;
                try {
                    cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
                } catch (Exception e) {
                    throw new RuntimeException("AES not supported on this platform", e);
                }
                try {
                    iv_spec = new IvParameterSpec(enc_data, 0, 16);
                    sks = new SecretKeySpec(key, "AES");
                    cipher.init(Cipher.DECRYPT_MODE, sks, iv_spec);
                } catch (Exception e) {
                    throw new RuntimeException("bad iv or key", e);
                }
                try {
                    data = cipher.doFinal(enc_data, 16, enc_data.length - 16);
                } catch (Exception e) {
                    throw new RuntimeException("body decryption failed", e);
                }

                JSONObject group = new JSONObject(new String(data));

                String group_name = group.getString("group_name");
                byte[] group_capability = Base64.decode(group.getString("group_capability"), Base64.DEFAULT);
                String sharer_name = group.getString("sharer_name");
                byte[] sharer_hash = Base64.decode(group.getString("sharer_hash"), Base64.DEFAULT);
                byte[] thumbnail = null;
                if (group.has("thumbnail"))
                    thumbnail = Base64.decode(group.getString("thumbnail"), Base64.DEFAULT);
                int member_count = group.getInt("member_count");
                int sharer_type = group.getInt("sharer_type");
                Pair<TByteArrayList, TByteArrayList> p = Pair.with(new TByteArrayList(sharer_hash),
                        new TByteArrayList(group_capability));
                if (dupes.contains(p))
                    continue;
                dupes.add(p);
                addNearbyItem(new NearbyFeed(mContext, group_name, group_capability, sharer_name,
                        Authority.values()[sharer_type], sharer_hash, thumbnail, member_count));
            } catch (Throwable e) {
                Log.e(TAG, "Failed to parse group " + i, e);
            }
        }
    } catch (Exception e) {
        if (DBG)
            Log.d(TAG, "Error searching nearby feeds", e);
    }
    return null;
}

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

/**
 * {@code connect} is for forming the secure connection between server and
 * android, sending and receiving of the data.
 * //ww  w .  j a  va 2  s  .  c o  m
 * @param arg0
 *            data which is to be sent to server.
 * 
 * @return data in string format, received from the server.
 */
public String connect(String... arg0) {

    int nrOfDataToSendToServer = arg0.length;
    nrOfDataToSendToServer = nrOfDataToSendToServer - 1;
    boolean valid = false;
    String dataFromServer = "unverified", serverPublicKeySigStr, serverDataSig;

    try {
        //Creating the server certificate
        Certificate serverCertificate = getServerCertificate();

        KeyStore keyStore = getKeyStore(serverCertificate);

        TrustManagerFactory tmf = getTrustManager(keyStore);

        SSLContext sslContext = getSSLContext(tmf);

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection urlConnection = getURLConnection(sslContext, hostnameVerifier);

        // Converting the data into JSONObject
        JSONObject obj = new JSONObject();
        for (int i = 0; i <= nrOfDataToSendToServer; i++) {
            obj.put("param" + i, arg0[i]);
        }

        // Converting the JSONObject into string
        String dataToSend = obj.toString();

        KeyPairGenerator keyGen = getKeyPairGenerator();

        KeyPair keyPair = keyGen.generateKeyPair();
        //Public key for verifying the digital signature
        PublicKey clientPublicKeySig = keyPair.getPublic();
        //Private key for signing the data
        PrivateKey clientPrivateKeySig = keyPair.getPrivate();

        // Get signed data
        String sigData = getDataSig(clientPrivateKeySig, dataToSend);

        // Creating URL Format
        String urlData = URLEncoder.encode("clientPublicKeySig", "UTF-8") + "=" + URLEncoder
                .encode(Base64.encodeToString(clientPublicKeySig.getEncoded(), Base64.DEFAULT), "UTF-8");
        urlData += "&" + URLEncoder.encode("clientData", "UTF-8") + "="
                + URLEncoder.encode(dataToSend, "UTF-8");
        urlData += "&" + URLEncoder.encode("clientDataSig", "UTF-8") + "="
                + URLEncoder.encode(sigData, "UTF-8");

        // Sending the data to the server
        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(urlData);
        wr.flush();
        wr.close();

        // Receiving the data from server
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
            // sb.append(line);
        }
        String text = sb.toString();
        reader.close();

        // Extracting the data, public key and signature received from
        // server
        Vector<String> storeExtractedValues = new Vector<String>();

        storeExtractedValues = extractDataFromJson(text, "data");
        dataFromServer = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverPublicKeySig");
        serverPublicKeySigStr = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverDataSig");
        serverDataSig = storeExtractedValues.get(0);

        // Converting the Server Public key format to Java compatible from
        PublicKey serverPublicKeySig = getServerPublicKey(serverPublicKeySigStr);

        // Verify the received data
        valid = getDataValidity(serverPublicKeySig, dataFromServer, serverDataSig);

        // Disconnect the url connection
        urlConnection.disconnect();

        if (dataFromServer.equalsIgnoreCase("unverified")) {
            CExceptionHandling.ExceptionState = ExceptionSet.SENT_DATA_UNVERIFIED;
            return "-1";
        } else if (valid == false) {
            CExceptionHandling.ExceptionState = ExceptionSet.RECEIVED_DATA_UNVERIFIED;
            return "-1";
        } else {
            return dataFromServer;
        }

    } catch (Exception e) {
        CExceptionHandling.ExceptionMsg = e.getMessage();

        if (e.toString().equals("java.net.SocketException: Network unreachable")) {
            CExceptionHandling.ExceptionState = ExceptionSet.NO_DATA_CONNECTION;
        } else if (e.toString().equals(
                "java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 443) after 10000ms")) {
            CExceptionHandling.ExceptionState = ExceptionSet.CONNECTION_TIMEOUT;
        } else {
            CExceptionHandling.ExceptionState = ExceptionSet.OTHER_EXCEPTIONS;
        }
        return "-1";
    }

}

From source file:com.andernity.launcher2.InstallShortcutReceiver.java

private static ArrayList<PendingInstallShortcutInfo> getAndClearInstallQueue(SharedPreferences sharedPrefs) {
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (strings == null) {
            return new ArrayList<PendingInstallShortcutInfo>();
        }/*from   w  ww . ja v a 2  s  .c o  m*/
        ArrayList<PendingInstallShortcutInfo> infos = new ArrayList<PendingInstallShortcutInfo>();
        for (String json : strings) {
            try {
                JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                Intent data = Intent.parseUri(object.getString(DATA_INTENT_KEY), 0);
                Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                String name = object.getString(NAME_KEY);
                String iconBase64 = object.optString(ICON_KEY);
                String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
                String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
                if (iconBase64 != null && !iconBase64.isEmpty()) {
                    byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
                    Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
                } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
                    Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
                    iconResource.resourceName = iconResourceName;
                    iconResource.packageName = iconResourcePackageName;
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
                }
                data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
                PendingInstallShortcutInfo info = new PendingInstallShortcutInfo(data, name, launchIntent);
                infos.add(info);
            } catch (org.json.JSONException e) {
                Log.d("InstallShortcutReceiver", "Exception reading shortcut to add: " + e);
            } catch (java.net.URISyntaxException e) {
                Log.d("InstallShortcutReceiver", "Exception reading shortcut to add: " + e);
            }
        }
        sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>()).commit();
        return infos;
    }
}

From source file:mobisocial.musubi.identity.AphidIdentityProvider.java

public AphidIdentityProvider(Context context) {
    mContext = context;//from   w  w w.ja v  a2 s  .com
    mEncryptionScheme = new IBEncryptionScheme(Base64.decode(ENCRYPTION_PUBLIC_PARAMETERS, Base64.DEFAULT));
    mSignatureScheme = new IBSignatureScheme(Base64.decode(SIGNATURE_PUBLIC_PARAMETERS, Base64.DEFAULT));
    mIdentitiesManager = new IdentitiesManager(App.getDatabaseSource(mContext));
    mPendingIdentityManager = new PendingIdentityManager(App.getDatabaseSource(mContext));
    mKnownTokens = new HashMap<Pair<Authority, String>, String>();
}