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:org.wso2.iot.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *///from   w ww.j a  va 2  s.  co  m
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.iot.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 | KeyStoreException | NoSuchAlgorithmException
                            | IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }, 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???//from www. j av a  2 s. co 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;// w  ww  .ja v a2 s .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:com.webXells.ImageResizer.ImageResizePlugin.java

private Bitmap getBitmap(String imageData, String imageDataType) throws IOException {
    Bitmap bmp;/*from   ww  w  .  java2 s.co m*/
    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:mobisocial.bento.todo.io.BentoManager.java

synchronized public Bitmap getTodoBitmap(Uri objUri, String todoUuid, int targetWidth, int targetHeight,
        float degrees) {
    Bitmap bitmap = null;//  www  .ja  va  2s  . 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.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:de.treichels.hott.ui.android.html.AndroidCurveImageGenerator.java

@Override
public String getImageSource(final Curve curve, final float scale, final boolean description) {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    getBitmap(curve, scale, description).compress(CompressFormat.PNG, 100, baos);
    return PREFIX + Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
}

From source file:com.oakesville.mythling.util.MediaStreamProxy.java

private HttpResponse download() throws IOException {

    httpClient = AndroidHttpClient.newInstance("Android");
    // httpClient.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost("127.0.0.1"));

    URL netUrl = proxyInfo.netUrl;
    HttpHost host = new HttpHost(netUrl.getHost(), netUrl.getPort(), netUrl.getProtocol());

    HttpRequestBase request = new HttpGet(netUrl.toString());
    HttpResponse response = null;//from  w ww. j a  va 2  s.c o m
    Log.d(TAG, "Proxy starting download");
    if (authType == AuthType.Digest) {
        HttpContext context = HttpHelper.getDigestAuthContext(netUrl.getHost(), netUrl.getPort(),
                proxyInfo.user, proxyInfo.password);
        response = httpClient.execute(host, request, context);
    } else if (authType == AuthType.Basic) {
        String credentials = Base64.encodeToString((proxyInfo.user + ":" + proxyInfo.password).getBytes(),
                Base64.DEFAULT);
        request.setHeader("Authorization", "Basic " + credentials);
        response = httpClient.execute(host, request);
    } else {
        response = httpClient.execute(host, request);
    }
    Log.d(TAG, "Proxy response downloaded");
    return response;
}

From source file:at.diamonddogs.util.Utils.java

/**
 * Byte array to base64//  ww  w .j  av a2s  . com
 *
 * @param inMsg the message to be converted to base64
 * @return the base64 string
 */
public static String encrypt(byte[] inMsg) {
    return Base64.encodeToString(inMsg, Base64.DEFAULT);
}

From source file:com.example.android.apis.graphics.FingerPaint.java

private Bitmap loadBitmap() {
    SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
    String previouslyEncodedImage = shre.getString("paint_image_data", "");

    if (!previouslyEncodedImage.equalsIgnoreCase("")) {
        byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
        Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        return mutableBitmap;
    }/* w  w w.  j  a  v a 2  s  . c o  m*/

    Display display = getWindowManager().getDefaultDisplay();
    @SuppressWarnings("deprecation")
    int width = display.getWidth();

    @SuppressWarnings("deprecation")
    int height = display.getHeight();

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    return bitmap;
}