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:jp.alessandro.android.iab.Security.java

/**
 * Verifies that the signature from the server matches the computed
 * signature on the data.  Returns true if the data is correctly signed.
 *
 * @param logger     the logger to use for printing events
 * @param publicKey  rsa public key generated by Google Play Developer Console
 * @param signedData signed data from server
 * @param signature  server signature/*from  w ww .j  av a  2 s .c om*/
 * @return true if the data and signature match
 */
protected boolean verify(Logger logger, PublicKey publicKey, String signedData, String signature)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException,
        InvalidKeyException, SignatureException, IllegalArgumentException {

    byte[] signatureBytes = Base64.decode(signature, Base64.DEFAULT);
    Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);

    sig.initVerify(publicKey);
    sig.update(signedData.getBytes("UTF-8"));
    if (!sig.verify(signatureBytes)) {
        logger.e(Logger.TAG, "Signature verification failed.");
        return false;
    }
    return true;
}

From source file:at.tugraz.ist.akm.webservice.requestprocessor.interceptor.AuthorizationInterceptor.java

private void extractCredentialsFromRequestHeader(Header header, StringBuffer requestUserName,
        StringBuffer requestPassword) {
    String headerValue = header.getValue();
    int idx = headerValue.indexOf(" ");
    if (idx >= 0) {
        String userCredentials;//from www . java 2  s.c o m
        try {
            userCredentials = new String(Base64.decode(headerValue.substring(idx + 1), 0), mDefaultEncoding);
            requestUserName.append(getUsernameSubstring(userCredentials));
            requestPassword.append(getPasswordSubstring(userCredentials));
        } catch (UnsupportedEncodingException e) {
            mLog.error("failed to extract string from header: " + e.getMessage());
        }
    }
}

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

@Override
public void onStart() {
    super.onStart();
    Intent intent = getIntent();//from   w w  w.j ava 2 s . c  om
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            questionID = extras.getLong(QUESTION_ID);
            String questionTitle = extras.getString(QUESTION_TITLE);
            String questionContent = extras.getString(QUESTION_CONTENT);
            try {
                byte[] imageByteArray = Base64.decode(extras.getByteArray(IMAGE), Base64.NO_WRAP);
                image = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
                scaleImage(THUMBIMAGESIZE, THUMBIMAGESIZE, true);
                imageView.setVisibility(View.VISIBLE);
                imageView.setImageBitmap(imageThumb);
            } catch (Exception e) {
            }
            titleText.setText(questionTitle);
            contentText.setText(questionContent);
            edit = true;
        }
    }
}

From source file:com.securekey.sdk.sample.AuthenticateDeviceActivity.java

/**
 * Implementation of Briidge.AuthenticateDeviceListener.authenticateDeviceComplete
 * or Briidge.AuthenticateDeviceReturnJWSListener.authenticateDeviceComplete
 *//*from ww  w. j  a v a  2 s  . com*/
@Override
public void authenticateDeviceComplete(int status, String txnId) {
    dismissProgressDialog();
    if (status == Briidge.STATUS_OK) {
        if (txnId != null) {

            if (this.jwsExpected) {

                // The JWT should be provide to a third party to be verify
                // It could be parse to see what's inside 

                dismissProgressDialog();
                String[] jwtSegment = getJWSSegments(txnId);
                try {
                    final StringBuilder message = new StringBuilder();
                    message.append(new String(Base64.decode(jwtSegment[0], Base64.NO_WRAP), "UTF-8") + "\n");
                    message.append(
                            new String(Base64.decode(jwtSegment[1], Base64.NO_WRAP), "UTF-8") + "\n\n\n");
                    showDialog(message.toString());

                    // JWT could be check on server side
                    verifyJWT(txnId);
                } catch (UnsupportedEncodingException e) {
                    Log.e(VerifyQuickCodeActivity.class.toString(), e.getMessage());
                }

            } else {

                getDeviceId(txnId);
            }
        } else {
            showDialog("Error: null data!");
        }
    } else if (status == Briidge.STATUS_CONNECTIVITY_ERROR) {
        showDialog("Error connecting to server!");
    } else {
        showDialog("Error processing request!");
    }
}

From source file:com.airbop.client.GCMIntentService.java

/**
 * Decode a base64 string into a Bitmap//from w w w.j a  v  a2 s .  c o m
 */
private static Bitmap decodeImage(String image_data) {
    // Decode the encoded string into largeIcon
    Bitmap largeIcon = null;
    if ((image_data != null) && (!image_data.equals(""))) {
        byte[] decodedImage = Base64.decode(image_data, Base64.DEFAULT);
        if (decodedImage != null) {
            largeIcon = BitmapFactory.decodeByteArray(decodedImage, 0, decodedImage.length);
        }
    }
    return largeIcon;
}

From source file:com.villasoftgps.movil.Act_Main.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // se instancia las preferencias de la aplicacion
    if (villaprefs == null) {
        villaprefs = getApplicationContext().getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    }/*w  w w. j  av a 2s  .c om*/

    // se instancia el editor de preferencias
    prefsedit = villaprefs.edit();

    /*
     * se valida que exista un usuario en las preferencia
     * de lo contrario se cierra la sesin y se redirecciona al login
     */
    String strClient = villaprefs.getString(PROPERTY_USER, "");
    if (strClient.equals("")) {
        Intent frm = new Intent(Act_Main.this, Act_Login.class);
        startActivity(frm);
        finish();
    }

    gson = new Gson();

    /*
    se instancia la clase cliente con los datos del usuario almacenado en las preferencias
     */
    client = new Client();
    client = gson.fromJson(strClient, Client.class);

    /*
    se instancia la clase que contiene los atributos u opciones de las preferencias
     */
    preferences = new Preferences();

    String strPreferences = villaprefs.getString(PROPERTY_PREFS, "");
    if (!strPreferences.equals("")) {
        preferences = gson.fromJson(villaprefs.getString(PROPERTY_PREFS, ""), Preferences.class);
    }

    /*
    se valida si la aplicacion se encuentra en status de bloqueo,
    de ser asi, se redirecciona a la actividad de bloqueado.
     */
    if (preferences.isLocked()) {
        Intent frm_Locked = new Intent(Act_Main.this, Act_Locked.class);
        startActivity(frm_Locked);
    }

    setContentView(R.layout.activity_main);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    /*
    se instancia el objeto del mapa
     */
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    /*
    se instancia el listview que contendr la lista de dispositivos
    y vehiculos del cliente logueado.
     */
    lvDevices = (ListView) findViewById(R.id.lvDevices);

    View lvDevicesHeader = getLayoutInflater().inflate(R.layout.lv_menu_header, null);
    VillaTextView lblEmail = (VillaTextView) lvDevicesHeader.findViewById(R.id.lblEmail);
    VillaTextView lblUser = (VillaTextView) lvDevicesHeader.findViewById(R.id.lblUser);
    VillaImageView imgProfile = (VillaImageView) lvDevicesHeader.findViewById(R.id.imgProfile);

    String userName = client.getFirstName() + " " + client.getLastName();
    lblUser.setText(userName);
    String userEmail = "(" + client.getEmail() + ")";
    lblEmail.setText(userEmail);

    if (client.getImage().equals("")) {
        Glide.with(Act_Main.this).load(R.drawable.icon_profile).centerCrop().crossFade().into(imgProfile);
    } else {
        byte[] image = Base64.decode(client.getImage(), 0);

        Glide.with(Act_Main.this).load(image).centerCrop().crossFade().into(imgProfile);
    }

    /*
    se cargan los items del lvDevices y el adapter
     */
    lvDevices.addHeaderView(lvDevicesHeader);
    devicesAdapter = new DevicesAdapter(Act_Main.this, client.getDevices());
    lvDevices.setAdapter(devicesAdapter);

    /*
    se ejecuta el procedimiento asincrono para cargar la lista de dispositivos
    correspondientes al cliente logueado
     */
    new AsyncGetDevices().execute(client.getClientId());

    /*
    se instancian el resto de controles que contiene la actividad
     */
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_menu);
    btnMenu = (Button) findViewById(R.id.btnMenu);
    btnMapaRoad = (Button) findViewById(R.id.btnMapaRoad);
    btnMapaSatelite = (Button) findViewById(R.id.btnMapaSatelite);
    btnLock = (Button) findViewById(R.id.btnLock);
    btnLogout = (Button) findViewById(R.id.btnLogout);

    btnMenu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mostrarOcultarMenu();
        }
    });

    btnMapaRoad.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mapa.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        }
    });

    btnMapaSatelite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mapa.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        }
    });

    btnLock.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent frmLocked = new Intent(Act_Main.this, Act_Locked.class);
            startActivity(frmLocked);
        }
    });

    btnLogout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mostrarMensaje(false, DialogType.PROMPT, R.drawable.icon_prompt,
                    getString(R.string.prompt_cerrar_sesion), Ejecutar.LOGOUT);
        }
    });
}

From source file:org.kde.kdeconnect.Device.java

Device(Context context, String deviceId) {
    settings = context.getSharedPreferences(deviceId, Context.MODE_PRIVATE);

    //Log.e("Device","Constructor A");

    this.context = context;
    this.deviceId = deviceId;
    this.name = settings.getString("deviceName", context.getString(R.string.unknown_device));
    this.pairStatus = PairStatus.Paired;
    this.protocolVersion = NetworkPackage.ProtocolVersion; //We don't know it yet
    this.deviceType = DeviceType.FromString(settings.getString("deviceType", "desktop"));

    try {//ww w  .jav a  2 s .co  m
        String publicKeyStr = settings.getString("publicKey", null);
        if (publicKeyStr != null) {
            byte[] publicKeyBytes = Base64.decode(publicKeyStr, 0);
            publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("KDE/Device", "Exception deserializing stored public key for device");
    }

    //Assume every plugin is supported until addLink is called and we can get the actual list
    m_supportedPlugins = new Vector<>(PluginFactory.getAvailablePlugins());

    //Do not load plugins yet, the device is not present
    //reloadPluginsFromSettings();
}

From source file:com.codebutler.farebot.card.felica.FelicaCard.java

public static FelicaCard fromXml(byte[] tagId, Date scannedAt, Element element) {
    Element systemsElement = (Element) element.getElementsByTagName("systems").item(0);

    NodeList systemElements = systemsElement.getElementsByTagName("system");

    FeliCaLib.IDm idm = new FeliCaLib.IDm(
            Base64.decode(element.getElementsByTagName("idm").item(0).getTextContent(), Base64.DEFAULT));
    FeliCaLib.PMm pmm = new FeliCaLib.PMm(
            Base64.decode(element.getElementsByTagName("pmm").item(0).getTextContent(), Base64.DEFAULT));

    FelicaSystem[] systems = new FelicaSystem[systemElements.getLength()];

    for (int x = 0; x < systemElements.getLength(); x++) {
        Element systemElement = (Element) systemElements.item(x);

        int systemCode = Integer.parseInt(systemElement.getAttribute("code"));

        Element servicesElement = (Element) systemElement.getElementsByTagName("services").item(0);

        NodeList serviceElements = servicesElement.getElementsByTagName("service");

        FelicaService[] services = new FelicaService[serviceElements.getLength()];

        for (int y = 0; y < serviceElements.getLength(); y++) {
            Element serviceElement = (Element) serviceElements.item(y);
            int serviceCode = Integer.parseInt(serviceElement.getAttribute("code"));

            Element blocksElement = (Element) serviceElement.getElementsByTagName("blocks").item(0);

            NodeList blockElements = blocksElement.getElementsByTagName("block");

            FelicaBlock[] blocks = new FelicaBlock[blockElements.getLength()];

            for (int z = 0; z < blockElements.getLength(); z++) {
                Element blockElement = (Element) blockElements.item(z);
                byte address = Byte.parseByte(blockElement.getAttribute("address"));
                byte[] data = Base64.decode(blockElement.getTextContent(), Base64.DEFAULT);

                blocks[z] = new FelicaBlock(address, data);
            }/*from   w w  w .java 2s  . c  o m*/

            services[y] = new FelicaService(serviceCode, blocks);
        }

        systems[x] = new FelicaSystem(systemCode, services);
    }

    return new FelicaCard(tagId, scannedAt, idm, pmm, systems);
}

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

@Override
protected List<NearbyItem> doInBackground(Void... params) {
    if (DBG)/*from   w w  w. ja v 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.afwsamples.testdpc.safetynet.SafetyNetFragment.java

private static JSONObject retrievePayloadFromJws(String jws) throws JSONException {
    String[] parts = jws.split("\\.");
    if (parts.length != 3) {
        throw new JSONException("Invalid JWS");
    }/*from  www .  j  a  v a  2 s  .c  o  m*/
    return new JSONObject(new String(Base64.decode(parts[1], Base64.URL_SAFE)));
}