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.jrummyapps.android.safetynet.SafetyNetHelper.java

/**
 * Parse the JSON Web Signature (JWS) response from the {@link SafetyNet} response.
 *
 * @param jws/*from   w w w  .j a  v a 2s  . co m*/
 *     The output of {@link SafetyNetApi.AttestationResult#getJwsResult()}.
 * @return The {@link SafetyNetResponse}.
 * @throws SafetyNetError
 *     If an error occurs while parsing the JWS.
 */
public static SafetyNetResponse getSafetyNetResponseFromJws(@NonNull String jws) throws SafetyNetError {
    try {
        String[] parts = jws.split("\\.");

        HashMap<String, Object> header = new HashMap<>();

        try {
            JSONObject json = new JSONObject(new String(Base64.decode(parts[0], Base64.DEFAULT)));
            for (Iterator<String> iterator = json.keys(); iterator.hasNext();) {
                String key = iterator.next();
                header.put(key, json.get(key));
            }
        } catch (Exception ignored) {
        }

        JSONObject json = new JSONObject(new String(Base64.decode(parts[1], Base64.DEFAULT)));
        String nonce = json.optString("nonce");
        long timestampMs = json.optLong("timestampMs");
        String apkPackageName = json.optString("apkPackageName");

        JSONArray jsonArray = json.optJSONArray("apkCertificateDigestSha256");
        String[] apkCertificateDigestSha256 = null;
        if (jsonArray != null) {
            int length = jsonArray.length();
            apkCertificateDigestSha256 = new String[length];
            for (int i = 0; i < length; i++) {
                apkCertificateDigestSha256[i] = jsonArray.getString(i);
            }
        }

        String apkDigestSha256 = json.optString("apkDigestSha256");
        boolean ctsProfileMatch = json.optBoolean("ctsProfileMatch");
        String signature = parts[2];

        return new SafetyNetResponse(jws, header, nonce, timestampMs, apkPackageName,
                apkCertificateDigestSha256, apkDigestSha256, ctsProfileMatch, signature);

    } catch (Exception e) {
        throw new SafetyNetError(e);
    }
}

From source file:com.mi.xserv.Xserv.java

private void manageMessage(String event) {
    JSONObject json = null;//from w  ww . j a  v  a  2  s .  c  om
    try {
        json = new JSONObject(event);
    } catch (JSONException ignored) {
    }

    if (json != null) {
        int op = 0;
        try {
            op = json.getInt("op");
        } catch (JSONException ignored) {
        }

        if (op == 0) {
            // messages

            onReceiveMessages(json);
        } else if (op > 0) {
            // operations

            try {
                String data = json.getString("data");
                byte[] b = Base64.decode(data, Base64.DEFAULT);
                json.put("data", new String(b, "UTF-8")); // string
            } catch (JSONException | UnsupportedEncodingException ignored) {
            }

            JSONObject json_data = null;
            try {
                String data = json.getString("data");
                Object type = new JSONTokener(data).nextValue();
                if (type instanceof JSONObject) {
                    json_data = new JSONObject(data);

                    json.put("data", json_data);
                } else if (type instanceof JSONArray) {
                    json.put("data", new JSONArray(data));
                }
            } catch (JSONException ignored) {
            }

            try {
                json.put("name", stringifyOp(op));
            } catch (JSONException ignored) {
            }

            int rc = 0;
            String uuid = "";
            String topic = "";
            String descr = "";
            try {
                rc = json.getInt("rc");
                uuid = json.getString("uuid");
                topic = json.getString("topic");
                descr = json.getString("descr");
            } catch (JSONException ignored) {
            }

            if (op == OP_HANDSHAKE) {
                // handshake

                if (rc == RC_OK) {
                    if (json_data != null) {
                        setUserData(json_data);

                        isConnected = true;

                        onOpenConnection();
                    } else {
                        mCallbacks.clear();

                        onErrorConnection(new Exception(descr));
                    }
                } else {
                    mCallbacks.clear();

                    onErrorConnection(new Exception(descr));
                }
            } else {
                // classic operations

                if (op == OP_SUBSCRIBE && isPrivateTopic(topic) && rc == RC_OK) {
                    if (json_data != null) {
                        setUserData(json_data);
                    }
                }

                if (mCallbacks.get(uuid) != null) {
                    mCallbacks.get(uuid).onCompletion(json);
                    mCallbacks.remove(uuid);
                } else {
                    OnReceiveOperations(json);
                }
            }
        }
    }
}

From source file:com.lillicoder.newsblurry.net.PreferenceCookieStore.java

/**
 * Decodes the given base-64 cookie string and returns a
 * {@link Cookie} representing that data.
 * @param encodedCookie Base-64 encoded string of a stored {@link Cookie}.
 * @return {@link Cookie} decoded from the given base-64 encoded cookie string.
 *///from   w  ww.j  av  a2  s. com
private Cookie decodeCookie(String encodedCookie) {
    Assert.assertTrue(encodedCookie != null);

    byte[] rawData = Base64.decode(encodedCookie, Base64.DEFAULT);
    ByteArrayInputStream in = new ByteArrayInputStream(rawData);

    Cookie cookie = null;
    try {
        ObjectInputStream inStream = new ObjectInputStream(in);
        SerializableCookie serializableCookie = (SerializableCookie) inStream.readObject();
        if (serializableCookie != null)
            cookie = serializableCookie.getCookie();
    } catch (ClassNotFoundException e) {
        Log.w(TAG, WARNING_FAILED_TO_FIND_SERIALIZABLE_COOKIE_CLASS);
    } catch (IOException e) {
        Log.w(TAG, WARNING_FAILED_TO_READ_COOKIE_FROM_STREAM);
    }

    return cookie;
}

From source file:org.wso2.emm.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *///from w  w w.  ja  v  a2s .  com
public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener)
        throws AndroidAgentException {

    if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) {
        try {
            listener.onDeviceCertCreated(
                    new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    } else {

        try {
            ServerConfig utils = new ServerConfig();
            final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE)
                    .generateKeyPair();
            X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO);
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject,
                    deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate());

            EndPointInfo endPointInfo = new EndPointInfo();
            endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.POST);
            endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT);
            endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT));

            new APIController().invokeAPI(endPointInfo, new APIResultCallBack() {
                @Override
                public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
                    try {
                        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                        InputStream in = new ByteArrayInputStream(
                                Base64.decode(result.get("response"), Base64.DEFAULT));
                        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        KeyStore keyStore = KeyStore.getInstance("PKCS12");
                        keyStore.load(null);
                        keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS,
                                (Key) deviceKeyPair.getPrivate(),
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(),
                                new java.security.cert.Certificate[] { cert });
                        keyStore.store(byteArrayOutputStream,
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray());
                        FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME,
                                Context.MODE_PRIVATE);
                        outputStream.write(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.close();
                        outputStream.close();
                        try {
                            listener.onDeviceCertCreated(new BufferedInputStream(
                                    context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
                        } catch (FileNotFoundException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    } catch (CertificateException e) {
                        Log.e(TAG, e.getMessage());
                    } catch (KeyStoreException e) {
                        e.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, Constants.SCEP_REQUEST_CODE, context, true);

        } catch (NoSuchAlgorithmException e) {
            throw new AndroidAgentException("No algorithm for key generation", e);
        } catch (SignatureException e) {
            throw new AndroidAgentException("Invalid Signature", e);
        } catch (NoSuchProviderException e) {
            throw new AndroidAgentException("Invalid provider", e);
        } catch (InvalidKeyException e) {
            throw new AndroidAgentException("Invalid key", e);
        }

    }

}

From source file:com.youku.player.service.GetVideoUrlServiceYouku.java

/**
 * ??Url??VideoUrlInfo???//  w w  w.  ja  va  2 s  . c  o m
 * 
 * @param mResult
 *            ?VideoUrlInfo msg???
 * 
 * @return 
 * 
 * */
public void setVideoUrlInfo(VideoUrlInfo mResult) {
    try {

        JSONObject json = new JSONObject(VideoInfoReasult.getResponseString());
        String data = json.getString("data");
        byte[] bytes = Base64.decode(data.getBytes(), Base64.DEFAULT);
        String decrypt = new String(PlayerUtil.decrypt(bytes, "qwer3as2jin4fdsa"));
        JSONObject object = new JSONObject(decrypt);
        // ?Url???
        Logger.d(LogTag.TAG_PLAYER, "??? setVideoUrlInfo");
        setVideoUrlInfoFromJson(object);
    } catch (JSONException e) {
        Logger.e(LogTag.TAG_PLAYER, "??? setVideoUrlInfo ", e);
    }
}

From source file:com.charabia.SmsViewActivity.java

@Override
public void onResume() {
    super.onResume();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefPhoneNumber = prefs.getString(PreferencesActivity.PHONE_NUMBER, null);
    if (prefPhoneNumber == null || prefPhoneNumber.length() <= 0) {

        Intent intent;//from ww  w .  jav a2s  .c  o m

        intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.setClassName(this, PreferencesActivity.class.getName());
        startActivity(intent);

        intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.setClassName(this, WebViewActivity.class.getName());
        intent.setData(Uri.parse(WebViewActivity.getBaseUrl(this, "/help", "enter_phone_number.html")));
        startActivity(intent);

        //Attempt to retrieve old keys

        android.content.ContentResolver cr = getContentResolver();
        android.database.Cursor cursor = cr.query(Data.CONTENT_URI,
                new String[] { Data._ID, Tools.PHONE, Tools.KEY }, Data.MIMETYPE + "=?",
                new String[] { Tools.CONTENT_ITEM_TYPE }, null);
        while (cursor.moveToNext()) {
            try {
                tools.updateOrCreateContactKey(cursor.getString(cursor.getColumnIndex(Tools.PHONE)),
                        Base64.decode(cursor.getString(cursor.getColumnIndex(Tools.KEY)), Base64.DEFAULT),
                        false);

                cr.delete(ContentUris.withAppendedId(Data.CONTENT_URI,
                        cursor.getLong(cursor.getColumnIndex(Data._ID))), null, null);
            } catch (NoContactException e) {
                e.printStackTrace();
                Toast.makeText(this, "No contact for " + cursor.getColumnIndex(Tools.PHONE), Toast.LENGTH_SHORT)
                        .show();
            }

        }
    }
}

From source file:mobisocial.bento.todo.io.BentoManager.java

synchronized public Bitmap getTodoBitmap(Uri objUri, String todoUuid, int targetWidth, int targetHeight,
        float degrees) {
    Bitmap bitmap = null;//from  w  w w .j  ava2  s  . c o  m

    DbFeed dbFeed = mMusubi.objForUri(objUri).getSubfeed();

    Cursor c = dbFeed.query();
    c.moveToFirst();
    for (int i = 0; i < c.getCount(); i++) {
        Obj object = mMusubi.objForCursor(c);
        if (object != null && object.getJson() != null && object.getJson().has(TODO_IMAGE)) {
            JSONObject diff = object.getJson().optJSONObject(TODO_IMAGE);
            if (todoUuid.equals(diff.optString(TODO_IMAGE_UUID))) {
                byte[] byteArray = Base64.decode(object.getJson().optString(B64JPGTHUMB), Base64.DEFAULT);
                bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                break;
            }
        }
        c.moveToNext();
    }
    c.close();

    if (bitmap != null) {
        bitmap = BitmapHelper.getResizedBitmap(bitmap, targetWidth, targetHeight, degrees);
    }

    return bitmap;
}

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

private Bitmap getBitmap(String imageData, String imageDataType) throws IOException {
    Bitmap bmp;//  w  w  w.j  a v  a 2 s  .  c  om
    if (imageDataType.equals(IMAGE_DATA_TYPE_BASE64)) {
        byte[] blob = Base64.decode(imageData, Base64.DEFAULT);
        bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);
    } else {
        File imagefile = new File(imageData);
        FileInputStream fis = new FileInputStream(imagefile);
        bmp = BitmapFactory.decodeStream(fis);
    }
    return bmp;
}

From source file:com.grouptuity.venmo.VenmoSDK.java

private static String base64_url_decode(String payload) {
    String payload_modified = payload.replace('-', '+').replace('_', '/').trim();
    String jsonString = new String(Base64.decode(payload_modified, Base64.DEFAULT));

    return jsonString;
}

From source file:org.nick.ghettounlock.GhettoTrustAgent.java

public static RSAPublicKey getPublicKey(Context ctx) {
    String pubKeyStr = PreferenceManager.getDefaultSharedPreferences(ctx).getString(PREF_PUB_KEY, null);
    if (pubKeyStr == null) {
        return null;
    }//from   www .j  ava2  s  .  c o m

    try {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
                Base64.decode(pubKeyStr.getBytes("UTF-8"), Base64.DEFAULT));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(keySpec);

        return pubKey;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}