Example usage for android.util Base64 decode

List of usage examples for android.util Base64 decode

Introduction

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

Prototype

public static byte[] decode(byte[] input, int flags) 

Source Link

Document

Decode the Base64-encoded data in input and return the data in a new byte array.

Usage

From source file:com.remobile.cordova.CordovaArgs.java

public byte[] getArrayBuffer(int index) throws JSONException {
    String encoded = baseArgs.getString(index);
    return Base64.decode(encoded, Base64.DEFAULT);
}

From source file:org.kde.kdeconnect.Helpers.SecurityHelpers.RsaHelper.java

public static PrivateKey getPrivateKey(Context context) throws Exception {

    try {/* w  w w  .  j  a  v a2  s  . co  m*/
        SharedPreferences globalSettings = PreferenceManager.getDefaultSharedPreferences(context);
        byte[] privateKeyBytes = Base64.decode(globalSettings.getString("privateKey", ""), 0);
        PrivateKey privateKey = KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        return privateKey;
    } catch (Exception e) {
        throw e;
    }

}

From source file:com.ibm.pickmeup.utils.MessageConductor.java

/**
 * Steer the message according to the rules related to the message payload and topic
 *
 * @param payload as a String//  w  ww . j av a  2 s .co  m
 * @param topic   as a String
 * @throws JSONException
 */
public void steerMessage(String payload, String topic) throws JSONException {
    Log.d(TAG, ".steerMessage() entered");

    // create a JSONObject from the payload string
    JSONObject jsonPayload = new JSONObject(payload);

    if (jsonPayload.has(Constants.TYPE) && jsonPayload.has(Constants.DRIVER_ID)
            && jsonPayload.get(Constants.TYPE).equals(Constants.ACCEPT)) {

        // pairing message - get the driverId and send it to the router
        String driverId = jsonPayload.getString(Constants.DRIVER_ID);
        Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
        actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_DRIVER_ACCEPTED);
        actionIntent.putExtra(Constants.DRIVER_ID, driverId);
        context.sendBroadcast(actionIntent);
    } else if (topic.contains(Constants.PICTURE) && jsonPayload.has(Constants.URL)) {

        // driver picture message - get the driverPicture as bytes array and send it to the router
        String urlStr = jsonPayload.getString(Constants.URL);
        byte[] decodedPictureAsBytes = Base64.decode(urlStr.substring(urlStr.indexOf(",")), Base64.DEFAULT);
        Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
        actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_DRIVER_DETAILS_RECEIVED);
        actionIntent.putExtra(Constants.DRIVER_PICTURE, decodedPictureAsBytes);
        context.sendBroadcast(actionIntent);
    } else if (topic.contains(Constants.DRIVER_HEAD_PREFIX) && jsonPayload.has(Constants.NAME)
            && jsonPayload.has(Constants.CONNECTION_TIME)) {

        // driver name message - get the name and send it to the router
        String driverName = jsonPayload.getString(Constants.NAME);
        Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
        actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_DRIVER_DETAILS_RECEIVED);
        actionIntent.putExtra(Constants.NAME, driverName);
        context.sendBroadcast(actionIntent);
    } else if (topic.equals(TopicFactory.getInstance(context).getPassengerChatTopic())
            && jsonPayload.has(Constants.FORMAT) && jsonPayload.has(Constants.DATA)) {

        // chat message - get the format and data and send it to the router
        Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
        actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_CHAT_MESSAGE_RECEIVED);
        String format = jsonPayload.getString(Constants.FORMAT);
        String data = jsonPayload.getString(Constants.DATA);
        actionIntent.putExtra(Constants.DATA, data);
        actionIntent.putExtra(Constants.FORMAT, format);
        context.sendBroadcast(actionIntent);
    } else if (topic.equals(TopicFactory.getInstance(context).getDriverLocationTopic())
            && jsonPayload.has(Constants.LATITUDE) && jsonPayload.has(Constants.LONGITUDE)) {

        // driver location message - send it directly to the map
        // check for previousCoordinatesReceivedTime to throttle messages within 100 milliseconds
        if (System.currentTimeMillis() - previousCoordinatesReceivedTime > 100) {
            Intent actionIntent = new Intent(Constants.ACTION_INTENT_COORDINATES_CHANGED);
            float lon = Float.parseFloat(jsonPayload.getString(Constants.LONGITUDE));
            float lat = Float.parseFloat(jsonPayload.getString(Constants.LATITUDE));
            actionIntent.putExtra(Constants.LONGITUDE, lon);
            actionIntent.putExtra(Constants.LATITUDE, lat);
            context.sendBroadcast(actionIntent);
            previousCoordinatesReceivedTime = System.currentTimeMillis();
        }
    } else if (topic.equals(TopicFactory.getInstance(context).getPassengerInboxTopic())
            && jsonPayload.has(Constants.TYPE)) {
        if (jsonPayload.get(Constants.TYPE).equals(Constants.TRIP_START)) {

            // trip started message - send it to the router
            Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
            actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_START_TRIP);
            context.sendBroadcast(actionIntent);
        } else if (jsonPayload.get(Constants.TYPE).equals(Constants.TRIP_END) && jsonPayload.has(Constants.TIME)
                && jsonPayload.has(Constants.COST) && jsonPayload.has(Constants.DISTANCE)) {

            // trip ended message - collect time, distance, cost and send to the router
            Intent actionIntent = new Intent(Constants.ACTION_INTENT_ROUTE_MESSAGE);
            actionIntent.putExtra(Constants.ROUTE_MESSAGE_TYPE, Constants.ACTION_INTENT_END_TRIP);
            String time = jsonPayload.getString(Constants.TIME);
            String distance = jsonPayload.getString(Constants.DISTANCE);
            String cost = jsonPayload.getString(Constants.COST);
            actionIntent.putExtra(Constants.TIME, time);
            actionIntent.putExtra(Constants.DISTANCE, distance);
            actionIntent.putExtra(Constants.COST, cost);
            context.sendBroadcast(actionIntent);
        } else if (jsonPayload.get(Constants.TYPE).equals(Constants.TRIP_PROCESSED)) {

            // payment processed message - send it directly to the waiting activity
            Intent actionIntent = new Intent(Constants.ACTION_INTENT_PAYMENT_RECEIVED);
            context.sendBroadcast(actionIntent);
        }
    }
}

From source file:com.parse.ParseDecoder.java

public Object decode(Object object) {
    if (object instanceof JSONArray) {
        return convertJSONArrayToList((JSONArray) object);
    }//from w w w .j a  va2s .com

    if (!(object instanceof JSONObject)) {
        return object;
    }

    JSONObject jsonObject = (JSONObject) object;

    String opString = jsonObject.optString("__op", null);
    if (opString != null) {
        try {
            return ParseFieldOperations.decode(jsonObject, this);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    String typeString = jsonObject.optString("__type", null);
    if (typeString == null) {
        return convertJSONObjectToMap(jsonObject);
    }

    if (typeString.equals("Date")) {
        String iso = jsonObject.optString("iso");
        return ParseDateFormat.getInstance().parse(iso);
    }

    if (typeString.equals("Bytes")) {
        String base64 = jsonObject.optString("base64");
        return Base64.decode(base64, Base64.NO_WRAP);
    }

    if (typeString.equals("Pointer")) {
        return decodePointer(jsonObject.optString("className"), jsonObject.optString("objectId"));
    }

    if (typeString.equals("File")) {
        return new ParseFile(jsonObject, this);
    }

    if (typeString.equals("GeoPoint")) {
        double latitude, longitude;
        try {
            latitude = jsonObject.getDouble("latitude");
            longitude = jsonObject.getDouble("longitude");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return new ParseGeoPoint(latitude, longitude);
    }

    if (typeString.equals("Object")) {
        return ParseObject.fromJSON(jsonObject, null, true, this);
    }

    if (typeString.equals("Relation")) {
        return new ParseRelation<>(jsonObject, this);
    }

    if (typeString.equals("OfflineObject")) {
        throw new RuntimeException("An unexpected offline pointer was encountered.");
    }

    return null;
}

From source file:se.leap.bitmaskclient.ConfigHelper.java

protected static RSAPrivateKey parseRsaKeyFromString(String RsaKeyString) {
    RSAPrivateKey key = null;/*from   ww w .  java 2  s . c  o  m*/
    try {
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");

        RsaKeyString = RsaKeyString.replaceFirst("-----BEGIN RSA PRIVATE KEY-----", "")
                .replaceFirst("-----END RSA PRIVATE KEY-----", "");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(RsaKeyString, Base64.DEFAULT));
        key = (RSAPrivateKey) kf.generatePrivate(keySpec);
    } catch (InvalidKeySpecException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    return key;
}

From source file:com.example.kushagar.knockknock.FragmentMain.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    //TextView mTxtTitle = (TextView) rootView.findViewById(R.id.txtTitle);
    //mTxtTitle.setText(getArguments().getString(TEXT_FRAGMENT));
    mCardContainer = (CardContainer) rootView.findViewById(R.id.layoutview);

    SimpleCardStackAdapter adapter = new SimpleCardStackAdapter(getActivity());

    Resources r = getResources();

    //add the cards here by posting a get request.
    byte[] encodeByte = Base64.decode("Description goes here", Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
    Drawable d = new BitmapDrawable(bitmap);

    adapter.add(new CardModel("Title1", "Description goes here", d));

    CardModel cardModel = new CardModel("Title1", "Description goes here", r.getDrawable(R.drawable.picture1));
    cardModel.setOnClickListener(new CardModel.OnClickListener() {
        @Override//from   w w  w. j a va 2 s. c om
        public void OnClickListener() {
            Log.i("Swipeable Cards", "I am pressing the card");
        }
    });

    cardModel.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() {
        @Override
        public void onLike() {
            Log.i("Swipeable Cards", "I like the card");
        }

        @Override
        public void onDislike() {
            Log.i("Swipeable Cards", "I dislike the card");
        }
    });

    adapter.add(cardModel);

    mCardContainer.setAdapter(adapter);

    rootView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    return rootView;
}

From source file:org.apache.cordova.todataurl.ToDataURL.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action         The action to execute.
 * @param args           JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return              True if the action was valid, false otherwise.
 *///from   ww w.  j a  v a 2  s. c o  m
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
        throws JSONException {
    Log.v(LOG_TAG, "Executing action: " + action);

    if ("getImageData".equals(action)) {
        try {
            // String encodedData = args.getString (0).replaceFirst ("^data:image/(png|jpg|jpeg);base64,", "");
            // Log.i(LOG_TAG, "getImageData[" + encodedData.length () + "] = " + encodedData);

            byte[] data = Base64.decode(
                    args.getString(0).replaceFirst("^data:image/(png|jpg|jpeg);base64,", ""), Base64.DEFAULT);// args.getArrayBuffer (0);
            /*
            int width = args.getInt (1);
            int height = args.getInt (2);
            */
            String type = args.optString(1, "image/png");
            int quality = args.optInt(2, 100);
            int orientation = args.optInt(3, 0);

            // Log.i(LOG_TAG, "getImageData[" + type + "][" + quality + "] = " + width + "x" + height);
            // Log.i(LOG_TAG, "getImageData[" + data.length + "] = " + data);

            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
            /*
            bmp = Bitmap.createBitmap (width, height, Bitmap.Config.ARGB_8888);
            bmp.copyPixelsFromBuffer (ByteBuffer.wrap (data));
            */
            // Log.i(LOG_TAG, "getImageData::bmp = " + bmp);

            try {
                final Matrix bitmapMatrix = new Matrix();

                switch (orientation) {
                case 1:
                    break; // top left
                case 2:
                    bitmapMatrix.postScale(-1, 1);
                    break; // top right
                case 3:
                    bitmapMatrix.postRotate(180);
                    break; // bottom right
                case 4:
                    bitmapMatrix.postRotate(180);
                    bitmapMatrix.postScale(-1, 1);
                    break; // bottom left
                case 5:
                    bitmapMatrix.postRotate(90);
                    bitmapMatrix.postScale(-1, 1);
                    break; // left top
                case 6:
                    bitmapMatrix.postRotate(90);
                    break; // right top
                case 7:
                    bitmapMatrix.postRotate(270);
                    bitmapMatrix.postScale(-1, 1);
                    break; // right bottom
                case 8:
                    bitmapMatrix.postRotate(270);
                    break; // left bottom
                default:
                    break; // Unknown
                }

                // Create new bitmap.
                bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), bitmapMatrix, false);

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                bmp.compress((type.endsWith("jpeg") ? Bitmap.CompressFormat.JPEG : Bitmap.CompressFormat.PNG),
                        quality, out);

                String dataURL = "data:" + type + ";base64," + Base64.encodeToString(out.toByteArray(), 0);
                // Log.i(LOG_TAG, "getImageData::dataURL = " + dataURL);

                PluginResult r = new PluginResult(PluginResult.Status.OK, dataURL);
                callbackContext.sendPluginResult(r);

                return true;
            } catch (Exception e) {
                // TODO: handle exception
                callbackContext.error("Create Bitmap Matrix");

                PluginResult r = new PluginResult(PluginResult.Status.ERROR);
                callbackContext.sendPluginResult(r);

                return true;
            }
        } catch (IllegalArgumentException e) {
            callbackContext.error("Illegal Argument Exception");

            PluginResult r = new PluginResult(PluginResult.Status.ERROR);
            callbackContext.sendPluginResult(r);

            return true;
        }
        /*
        PluginResult r = new PluginResult (PluginResult.Status.NO_RESULT);
        r.setKeepCallback (true);
        callbackContext.sendPluginResult (r);
                
        return true;
        */
    }

    return false;
}

From source file:com.amazonaws.mobileconnectors.kinesis.kinesisrecorder.internal.JSONRecordAdapter.java

/**
 * @param source The JSONObject that was created and stored via translateFromRecord
 * @return The corresponding//ww w . jav a 2s .c o m
 */
public PutRecordRequest translateToRecord(JSONObject source) {

    PutRecordRequest putRequest = new PutRecordRequest();
    try {
        putRequest.withData(ByteBuffer.wrap(Base64.decode(source.getString(DATA_FIELD_KEY), Base64.DEFAULT)));
        putRequest.withPartitionKey(source.getString(PARTITION_KEY_FIELD));
        putRequest.withStreamName(source.getString(STREAM_NAME_FIELD));
        if (source.has(EXPLICIT_HASH_FIELD)) {
            putRequest.withExplicitHashKey(source.getString(EXPLICIT_HASH_FIELD));
        }
        if (source.has(SEQUENCE_NUMBER_FIELD)) {
            putRequest.withSequenceNumberForOrdering(source.getString(SEQUENCE_NUMBER_FIELD));
        }

        return putRequest;

    } catch (JSONException e) {
        logger.e("Error creating stored request from representation on disk, ignoring request", e);
        return null;
    }

}

From source file:com.google.samples.apps.abelana.AbelanaThings.java

public AbelanaThings(Context ctx, String phint) {
    final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    final HttpTransport httpTransport = new NetHttpTransport();
    Resources r = ctx.getResources();
    byte[] android, server;
    byte[] password = new byte[32];

    android = Base64.decode("vW7CmbQWdPjpdfpBU39URsjHQV50KEKoSfafHdQPSh8",
            Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP);
    server = Base64.decode(phint, Base64.URL_SAFE);

    int i = 0;//from  www.j ava 2  s  .  c o m
    for (byte b : android) {
        password[i] = (byte) (android[i] ^ server[i]);
        i++;
    }
    byte[] pw = Base64.encode(password, Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP);
    String pass = new String(pw);

    if (storage == null) {
        try {
            KeyStore keystore = KeyStore.getInstance("PKCS12");
            keystore.load(r.openRawResource(R.raw.abelananew), pass.toCharArray());

            credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
                    .setServiceAccountId(r.getString(R.string.service_account))
                    .setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL))
                    .setServiceAccountPrivateKey((PrivateKey) keystore.getKey("privatekey", pass.toCharArray()))
                    .build();

            storage = new Storage.Builder(httpTransport, jsonFactory, credential)
                    .setApplicationName(r.getString(R.string.app_name) + "/1.0").build();

        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("loaded");
    }
}

From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle arguments = getArguments();//from  ww  w .ja  v  a 2 s  .  co m

    if (arguments == null) {
        throw new IllegalArgumentException("arguments is not set");
    }

    mConsumerKey = arguments.getString("consumerKey");
    mConsumerSecret = arguments.getString("consumerSecret");
    if (TextUtils.isEmpty(mConsumerKey) || TextUtils.isEmpty(mConsumerSecret)) {
        throw new IllegalArgumentException("both consumerKey and consumerSecret is required");
    }

    SharedPreferences preferences = getActivity().getSharedPreferences("twitter", Activity.MODE_PRIVATE);
    if (preferences.contains("access_token_str")) {
        String ats = preferences.getString("access_token_str", "");
        if (!TextUtils.isEmpty(ats)) {
            byte[] decode = Base64.decode(ats, Base64.DEFAULT);
            mAccessToken = SerializationUtils.deserialize(decode);
        }
    }

}