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.bamobile.fdtks.util.Tools.java

public static String convertBitmapToBase64(Bitmap bitmap) {
    // Convert bitmap to Base64 encoded image for web
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream.toByteArray();
    return android.util.Base64.encodeToString(byteArray, Base64.DEFAULT);
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

public String doRedirect(String urlRedirect, boolean useTim) {
    // android.os.Debug.waitForDebugger();
    try {//  www.j av a  2  s.c om
        // with server phpOIDC, check for '#'
        if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?"))
                || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) {
            String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&");
            String code = "";
            String state = "";
            String state_key = "state";
            for (int i = 0; i < params.length; i++) {
                String param = params[i];
                int idxEqual = param.indexOf('=');
                if (idxEqual >= 0) {
                    String key = param.substring(0, idxEqual);
                    String value = param.substring(idxEqual + 1);
                    if (key.startsWith("code"))
                        code = value;
                    if (key.startsWith("state"))
                        state = value;
                    if (key.startsWith("session_state")) {
                        state = value;
                        state_key = "session_state";
                    }
                }
            }

            // display code and state
            Logd(TAG, "doRedirect => code: " + code + " / state: " + state);

            // doRepost(code,state);
            if (code.length() > 0) {

                // get token_endpoint endpoint
                String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url);
                if (isEmpty(token_endpoint)) {
                    Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url);
                    return null;
                }

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                HttpURLConnection huc = getHUC(token_endpoint);
                huc.setInstanceFollowRedirects(false);

                if (useTim) {
                    if (mUsePrivateKeyJWT) {
                        nameValuePairs.add(new BasicNameValuePair("client_assertion_type",
                                "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));
                        String client_assertion = secureStorage.getPrivateKeyJwt(token_endpoint);
                        Logd(TAG, "client_assertion: " + client_assertion);
                        nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion));
                    } else {
                        huc.setRequestProperty("Authorization",
                                "Basic " + secureStorage.getClientSecretBasic());
                    }
                } else {
                    String authorization = (mOcp.m_client_id + ":" + mOcp.m_client_secret);
                    authorization = Base64.encodeToString(authorization.getBytes(), Base64.DEFAULT);
                    huc.setRequestProperty("Authorization", "Basic " + authorization);
                }

                huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                huc.setDoOutput(true);
                huc.setChunkedStreamingMode(0);

                OutputStream os = huc.getOutputStream();
                OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8");
                BufferedWriter writer = new BufferedWriter(out);

                nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
                nameValuePairs.add(new BasicNameValuePair("code", code));
                nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri));
                if (state != null && state.length() > 0)
                    nameValuePairs.add(new BasicNameValuePair(state_key, state));

                // write URL encoded string from list of key value pairs
                writer.write(getQuery(nameValuePairs));
                writer.flush();
                writer.close();
                out.close();
                os.close();

                Logd(TAG, "doRedirect => before connect");
                huc.connect();
                int responseCode = huc.getResponseCode();
                System.out.println("2 - code " + responseCode);
                Log.d(TAG, "doRedirect => responseCode " + responseCode);
                InputStream in = null;
                try {
                    in = new BufferedInputStream(huc.getInputStream());
                } catch (IOException ioe) {
                    sysout("io exception: " + huc.getErrorStream());
                }
                if (in != null) {
                    String result = convertStreamToString(in);
                    // now you have the string representation of the HTML request
                    in.close();

                    Logd(TAG, "doRedirect: " + result);

                    // save as static for now
                    return result;

                } else {
                    Logd(TAG, "doRedirect null");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.example.cake.mqtttest.registerActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch (requestCode) {
    case SELECT_PHOTO:
        if (resultCode == RESULT_OK) {
            Uri selectedImage = imageReturnedIntent.getData();
            InputStream imageStream = null;
            try {
                imageStream = getContentResolver().openInputStream(selectedImage);
                Bitmap yourSelectedImage = decodeUri(selectedImage);

                ImageView x = (ImageView) findViewById(R.id.avatarImageView);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

                x.setImageBitmap(yourSelectedImage);
            } catch (FileNotFoundException e) {
                e.printStackTrace();/*from  w  w  w  . ja  va  2s .  c om*/
            }

        }
    }
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

public static Pair<UserRegistrationState, String> registrateUser(Context context, String email,
        byte[] srpPassword, byte[] pwdSalt, String name) throws ServerException, NetworkErrorException {

    String username;/*from  w w w  .  j  ava 2s  .  c o m*/
    UserRegistrationState state;
    int retryCount = 5;
    boolean retry;
    do {
        retry = false;
        state = null;
        try {
            // create new Username
            username = createUsername(context, email);
            if (username == null) {
                return new Pair<UserRegistrationState, String>(UserRegistrationState.EMAIL_INVALID, null);
            }
            Pair<byte[], BigInteger> verif = SRP6Helper.createUserVerification(username, srpPassword);

            final HttpPost post = new HttpPost(REGISTRATION_URI);
            List<BasicNameValuePair> values = new ArrayList<BasicNameValuePair>();
            values.add(new BasicNameValuePair("username", username));
            values.add(new BasicNameValuePair("email", email));
            values.add(new BasicNameValuePair("verif",
                    Base64.encodeToString(BigIntegers.asUnsignedByteArray(verif.right), Base64.DEFAULT)));
            values.add(new BasicNameValuePair("srpSalt", Base64.encodeToString(verif.left, Base64.DEFAULT)));
            values.add(new BasicNameValuePair("pwdSalt", Base64.encodeToString(pwdSalt, Base64.DEFAULT)));
            values.add(new BasicNameValuePair("personname", name));
            values.add(new BasicNameValuePair("locale", Locale.getDefault().toString()));

            HttpEntity postEntity = new UrlEncodedFormEntity(values, SyncDataHelper.DEFAULT_CHARSET_NAME);
            post.setHeader(postEntity.getContentEncoding());
            post.setEntity(postEntity);

            byte[] content;
            final HttpResponse resp = getHttpClient(context).execute(post, createHttpContext(username, null));
            content = getResponse(resp);

            if (content != null && content.length > 0) {
                String respCode = new String(content, SyncDataHelper.DEFAULT_CHARSET_NAME);
                state = UserRegistrationState.fromErrorVal(respCode);
            }
            if (state == null) {
                throw new ServerException("No valid response");
            }
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new NetworkErrorException(ex);
        }
        if (state == UserRegistrationState.USERNAME_IN_USE) {
            // Create a new username when alredy in use (concurrent catch of
            // username)
            retry = true;
        }
        retryCount--;
    } while (retry && retryCount > 0);

    return new Pair<UserRegistrationState, String>(state, username);
}

From source file:com.magestore.app.pos.api.m1.config.POSConfigDataAccessM1.java

private String decryptRSAToString(String encryptedBase64, String privateKey) {
    String decryptedString = "";
    try {/*from  w w  w  .ja va 2s  .com*/
        String rStart = privateKey.replace("-----BEGIN PUBLIC KEY-----", "");
        String rEnd = rStart.replace("-----END PUBLIC KEY-----", "");
        rEnd = rEnd.replaceAll("\r", "");
        rEnd = rEnd.replaceAll("\n", "");
        rEnd = rEnd.replaceAll("\t", "");
        rEnd = rEnd.replaceAll(" ", "");
        KeyFactory keyFac = KeyFactory.getInstance("RSA");

        PublicKey publicKey = keyFac
                .generatePublic(new X509EncodedKeySpec(Base64.decode(rEnd.toString(), Base64.DEFAULT)));

        // get an RSA cipher object and print the provider
        final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        // encrypt the plain text using the public key
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        byte[] encryptedBytes = Base64.decode(encryptedBase64, Base64.DEFAULT);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        decryptedString = new String(decryptedBytes);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return decryptedString;
}

From source file:jp.app_mart.billing.AppmartHelper.java

/**
 * ?//w w  w  .  j a  v a  2 s.  co m
 * @param serviceId
 * @param developId
 * @param strLicenseKey
 * @param strPublicKey
 * @return
 */
public static String createEncryptedData(String serviceId, String developId, String strLicenseKey,
        String strPublicKey) {
    final String SEP_SYMBOL = "&";
    StringBuilder infoDataSB = new StringBuilder();
    infoDataSB.append(serviceId).append(SEP_SYMBOL);
    // ?ID 
    infoDataSB.append(developId).append(SEP_SYMBOL);
    // 
    infoDataSB.append(strLicenseKey);
    String strEncryInfoData = "";
    try {
        KeyFactory keyFac = KeyFactory.getInstance("RSA");
        KeySpec keySpec = new X509EncodedKeySpec(Base64.decode(strPublicKey.getBytes(), Base64.DEFAULT));
        Key publicKey = keyFac.generatePublic(keySpec);
        if (publicKey != null) {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] EncryInfoData = cipher.doFinal(infoDataSB.toString().getBytes());
            strEncryInfoData = new String(Base64.encode(EncryInfoData, Base64.DEFAULT));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        strEncryInfoData = "";
        Log.e("AppmartHelper", "?");
    }
    return strEncryInfoData.replaceAll("(\\r|\\n)", "");
}

From source file:com.madrobot.net.client.XMLRPCClient.java

/**
 * Call method with optional parameters. This is general method. If you want to call your method with 0-8
 * parameters, you can use more convenience call() methods
 * /*from   www .j a v a  2 s . com*/
 * @param method
 *            name of method to call
 * @param params
 *            parameters to pass to method (may be null if method has no parameters)
 * @return deserialized method return value
 * @throws XMLRPCException
 */
@SuppressWarnings("unchecked")
public Object callEx(String method, Object[] params) throws XMLRPCException {
    try {
        // prepare POST body
        String body = methodCall(method, params);

        // set POST body
        HttpEntity entity = new StringEntity(body);
        postMethod.setEntity(entity);

        // This code slightly tweaked from the code by erickok in issue #6
        // Force preemptive authentication
        // This makes sure there is an 'Authentication: ' header being send before trying and failing and retrying
        // by the basic authentication mechanism of DefaultHttpClient
        if (this.httpPreAuth == true) {
            String auth = this.username + ":" + this.password;
            postMethod.addHeader("Authorization",
                    "Basic " + Base64.encode(auth.getBytes(), Base64.DEFAULT).toString());
        }

        // Log.d(Tag.LOG, "ros HTTP POST");
        // execute HTTP POST request
        HttpResponse response = client.execute(postMethod);
        // Log.d(Tag.LOG, "ros HTTP POSTed");

        // check status code
        int statusCode = response.getStatusLine().getStatusCode();
        // Log.d(Tag.LOG, "ros status code:" + statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            throw new XMLRPCException("HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK);
        }

        // parse response stuff
        //
        // setup pull parser
        XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
        entity = response.getEntity();
        Reader reader = new InputStreamReader(new BufferedInputStream(entity.getContent()));
        // for testing purposes only
        // reader = new
        // StringReader("<?xml version='1.0'?><methodResponse><params><param><value>\n\n\n</value></param></params></methodResponse>");
        pullParser.setInput(reader);

        // lets start pulling...
        pullParser.nextTag();
        pullParser.require(XmlPullParser.START_TAG, null, Tag.METHOD_RESPONSE);

        pullParser.nextTag(); // either Tag.PARAMS (<params>) or Tag.FAULT (<fault>)
        String tag = pullParser.getName();
        if (tag.equals(Tag.PARAMS)) {
            // normal response
            pullParser.nextTag(); // Tag.PARAM (<param>)
            pullParser.require(XmlPullParser.START_TAG, null, Tag.PARAM);
            pullParser.nextTag(); // Tag.VALUE (<value>)
            // no parser.require() here since its called in XMLRPCSerializer.deserialize() below

            // deserialize result
            Object obj = iXMLRPCSerializer.deserialize(pullParser);
            entity.consumeContent();
            return obj;
        } else if (tag.equals(Tag.FAULT)) {
            // fault response
            pullParser.nextTag(); // Tag.VALUE (<value>)
            // no parser.require() here since its called in XMLRPCSerializer.deserialize() below

            // deserialize fault result
            Map<String, Object> map = (Map<String, Object>) iXMLRPCSerializer.deserialize(pullParser);
            String faultString = (String) map.get(Tag.FAULT_STRING);
            int faultCode = (Integer) map.get(Tag.FAULT_CODE);
            entity.consumeContent();
            throw new XMLRPCFault(faultString, faultCode);
        } else {
            entity.consumeContent();
            throw new XMLRPCException(
                    "Bad tag <" + tag + "> in XMLRPC response - neither <params> nor <fault>");
        }
    } catch (XMLRPCException e) {
        // catch & propagate XMLRPCException/XMLRPCFault
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        // wrap any other Exception(s) around XMLRPCException
        throw new XMLRPCException(e);
    }
}

From source file:com.polyvi.xface.extension.XAppExt.java

private String drawableToBase64(Drawable drawable) {
    int width = drawable.getIntrinsicWidth();
    int height = drawable.getIntrinsicHeight();
    Bitmap bitmap = Bitmap.createBitmap(width, height,
            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, width, height);
    drawable.draw(canvas);/*from   w w  w . ja v  a 2s . co  m*/
    String result = null;
    ByteArrayOutputStream baos = null;
    try {
        if (bitmap != null) {
            baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            baos.flush();
            baos.close();
            byte[] bitmapBytes = baos.toByteArray();
            result = XBase64.encodeToString(bitmapBytes, Base64.DEFAULT);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (baos != null) {
                baos.flush();
                baos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:com.pdftron.pdf.utils.Utils.java

public static String decryptIt(Context context, String value) {
    String cryptoPass = context.getString(context.getApplicationInfo().labelRes);
    try {//from w  w  w  . j a v a 2  s .co m
        DESKeySpec keySpec = new DESKeySpec(cryptoPass.getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        byte[] encrypedPwdBytes = Base64.decode(value, Base64.DEFAULT);
        // cipher is not thread safe
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes));

        String decrypedValue = new String(decrypedValueBytes);
        Log.d("MiscUtils", "Decrypted: " + value + " -> " + decrypedValue);
        return decrypedValue;

    } catch (Exception e) {
        Log.e(e.getClass().getName(), e.getMessage());
    }
    return value;
}

From source file:org.uoyabause.android.YabauseHandler.java

void doReportCurrentGame(int rating, String message, boolean screenshot) {
    current_report = new ReportContents();
    current_report._rating = rating;//  ww  w. ja  va2 s  .com
    current_report._message = message;
    current_report._screenshot = screenshot;
    _report_status = REPORT_STATE_INIT;

    String gameinfo = YabauseRunnable.getGameinfo();
    if (gameinfo != null) {

        try {

            showDialog();
            AsyncReport asyncTask = new AsyncReport(this);
            current_game_info = new JSONObject(gameinfo);

            DateFormat dateFormat = new SimpleDateFormat("_yyyy_MM_dd_HH_mm_ss");
            Date date = new Date();

            String screen_shot_save_path = YabauseStorage.getStorage().getScreenshotPath()
                    + YabauseRunnable.getCurrentGameCode() + dateFormat.format(date) + ".png";

            if (YabauseRunnable.screenshot(screen_shot_save_path) != 0) {
                dismissDialog();
                return;
            }

            InputStream inputStream = new FileInputStream(screen_shot_save_path);//You can get an inputStream using any IO API
            byte[] bytes;
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
                dismissDialog();
                return;
            }
            bytes = output.toByteArray();
            String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);

            JSONObject jsonObjimg = new JSONObject();
            jsonObjimg.put("data", encodedString);
            jsonObjimg.put("filename", screen_shot_save_path);
            jsonObjimg.put("content_type", "image/png");
            JSONObject jsonObjgame = current_game_info.getJSONObject("game");
            jsonObjgame.put("title_image", jsonObjimg);

            if (screenshot) {
                current_report._screenshot_base64 = encodedString;
                current_report._screenshot_save_path = screen_shot_save_path;
            }
            //asyncTask.execute("http://192.168.0.7:3000/api/", YabauseRunnable.getCurrentGameCode());
            asyncTask.execute("http://www.uoyabause.org/api/", YabauseRunnable.getCurrentGameCode());

            return;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}