Example usage for android.util Base64 encodeToString

List of usage examples for android.util Base64 encodeToString

Introduction

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

Prototype

public static String encodeToString(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated String with the result.

Usage

From source file:mobisocial.musubi.ui.util.FeedHTML.java

public static void writeObj(FileOutputStream fo, Context context, IdentitiesManager identitiesManager,
        MObject object) {//from   www.j  a v a2 s .  c om
    //TODO: it would be better to put the export code inside the obj handlers
    MIdentity ident = identitiesManager.getIdentityForId(object.identityId_);
    if (ident == null)
        return;
    PrintWriter w = new PrintWriter(fo);
    w.print("<div>");
    w.print("<div style=\"float:left\">");

    w.print("<img src=\"data:image/jpeg;base64,");
    Bitmap thumb = UiUtil.safeGetContactThumbnail(context, identitiesManager, ident);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    thumb.compress(CompressFormat.JPEG, 90, bos);
    w.print(Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT));
    w.print("\">");

    w.print("</div>");
    w.print("<div>");
    w.print("<h6>");
    w.print(UiUtil.safeNameForIdentity(ident));
    w.print("</h6>");

    try {
        if (object.type_.equals(StatusObj.TYPE)) {
            w.print(new JSONObject(object.json_).getString(StatusObj.TEXT));
        } else if (object.type_.equals(PictureObj.TYPE)) {
            w.print("<img src=\"data:image/jpeg;base64,");
            w.print(Base64.encodeToString(object.raw_, Base64.DEFAULT));
            w.print("\">");
        } else {
            throw new RuntimeException("unsupported type " + object.type_);
        }

    } catch (Throwable t) {
        Log.e("HTML EXPORT", "failed to process obj", t);
        w.print("<i>only visibile in musubi</i>");
    }
    w.print("</div>");
    w.print("</div>");

    w.print("</body>");
    w.print("</html>");
    w.flush();
}

From source file:com.jeffreyawest.http.HTTPAdapterImpl.java

@Override
public String GET(String pURL, String pUsername, String pPassword, String pAccept,
        HashMap<String, String> pAdditionalHeaders) {

    Log.v(LOG_TAG, "GET()");

    // Making HTTP request
    HttpGet httpGet = new HttpGet(pURL);
    httpGet.setHeader(ACCEPT_HEADER_KEY, "application/json");

    if (pUsername != null || pPassword != null) {
        String authorizationString = "Basic "
                + Base64.encodeToString((pUsername + ":" + pPassword).getBytes(), Base64.NO_WRAP);
        httpGet.setHeader("Authorization", authorizationString);
        Log.v(LOG_TAG, "Setting AUTH header: " + authorizationString);
    }/*from w ww . j  ava  2  s.c  o m*/

    String result = null;

    try {
        result = doHTTPMethod(httpGet);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

From source file:Main.java

private static String generateSignature(String base, String type, String nonce, String timestamp, String token,
        String tokenSecret, String verifier, ArrayList<String> parameters)
        throws NoSuchAlgorithmException, InvalidKeyException {
    String encodedBase = Uri.encode(base);

    StringBuilder builder = new StringBuilder();

    //Create an array of all the parameters
    //So that we can sort them
    //OAuth requires that we sort all parameters
    ArrayList<String> sortingArray = new ArrayList<String>();

    sortingArray.add("oauth_consumer_key=" + oauthConsumerKey);
    sortingArray.add("oauth_nonce=" + nonce);
    sortingArray.add("oauth_signature_method=HMAC-SHA1");
    sortingArray.add("oauth_timestamp=" + timestamp);
    sortingArray.add("oauth_version=1.0");

    if (parameters != null) {
        sortingArray.addAll(parameters);
    }//  www. j av  a  2  s. c o  m

    if (token != "" && token != null) {
        sortingArray.add("oauth_token=" + token);
    }
    if (verifier != "" && verifier != null) {
        sortingArray.add("oauth_verifier=" + verifier);
    }

    Collections.sort(sortingArray);

    //Append all parameters to the builder in the right order
    for (int i = 0; i < sortingArray.size(); i++) {
        if (i > 0)
            builder.append("&" + sortingArray.get(i));
        else
            builder.append(sortingArray.get(i));

    }

    String params = builder.toString();
    //Percent encoded the whole url
    String encodedParams = Uri.encode(params);

    String completeUrl = type + "&" + encodedBase + "&" + encodedParams;

    String completeSecret = oauthSecretKey;

    if (tokenSecret != null && tokenSecret != "") {
        completeSecret = completeSecret + "&" + tokenSecret;
    } else {
        completeSecret = completeSecret + "&";
    }

    Log.v("Complete URL: ", completeUrl);
    Log.v("Complete Key: ", completeSecret);

    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(completeSecret.getBytes(), mac.getAlgorithm());
    mac.init(secret);
    byte[] sig = mac.doFinal(completeUrl.getBytes());

    String signature = Base64.encodeToString(sig, 0);
    signature = signature.replace("+", "%2b"); //Specifically encode all +s to %2b

    return signature;
}

From source file:com.lewie9021.videothumbnail.VideoThumbnail.java

public static String encodeTobase64(Bitmap image) {
    Bitmap bmImage = image;//w ww.j av a 2  s  .c o  m

    ByteArrayOutputStream byteArrayData = new ByteArrayOutputStream();
    bmImage.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayData);
    byte[] byteData = byteArrayData.toByteArray();
    String encodedImage = Base64.encodeToString(byteData, Base64.DEFAULT);

    return encodedImage;
}

From source file:im.whistle.crypt.Crypt.java

/**
 * Generates a private/public key pair./*from   w  w  w.  ja v  a2s . c  o m*/
 * @param args Arguments, element at 0 is the key size
 * @param callback Callback
 */
public static void genkeys(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        Log.i("whistle", "Generating key pair ...");
        PRNGProvider.init(); // Ensure OpenSSL fix
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        int bits = args.getInt(0);
        int exp = args.getInt(1);
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(bits, BigInteger.valueOf(exp)));
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        String priv = "-----BEGIN RSA PRIVATE KEY-----\n"
                + Base64.encodeToString(keyPair.getPrivate().getEncoded(), Base64.DEFAULT).trim()
                + "\n-----END RSA PRIVATE KEY-----";
        String pub = "-----BEGIN PUBLIC KEY-----\n"
                + Base64.encodeToString(keyPair.getPublic().getEncoded(), Base64.DEFAULT).trim()
                + "\n-----END PUBLIC KEY-----";
        JSONArray res = new JSONArray();
        res.put(priv);
        res.put(pub);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Key pair generation failed: " + ex.getMessage());
        callback.error(ex);
    }
}

From source file:com.mimo.service.api.MimoHttpConnection.java

/**
 * Function for Making HTTP "get" request and getting server response.
 * //w w  w .  jav a 2 s  . c  o  m
 * @param p_url
 *            - Http Url
 * @throws ClientProtocolException
 * @throws IOException
 * @return HttpResponse- Returns the HttpResponse.
 */
public static synchronized HttpResponse getHttpUrlConnection(String p_url)
        throws ClientProtocolException, IOException // throws
// CustomException
{

    DefaultHttpClient m_httpClient = new DefaultHttpClient();
    HttpGet m_get = new HttpGet(p_url);

    String m_authString = MimoAPIConstants.USERNAME + ":" + MimoAPIConstants.PASSWORD;
    String m_authStringEnc = Base64.encodeToString(m_authString.getBytes(), Base64.NO_WRAP);
    m_get.addHeader(MimoAPIConstants.HEADER_TEXT_AUTHORIZATION,
            MimoAPIConstants.HEADER_TEXT_BASIC + m_authStringEnc);
    HttpResponse m_response = null;

    try {
        m_response = m_httpClient.execute(m_get);
    } catch (IllegalStateException e) {
        if (MimoAPIConstants.DEBUG) {
            Log.e(TAG, e.getMessage());
        }
    }

    return m_response;
}

From source file:cn.sharesdk.analysis.net.NetworkHelper.java

public static String Base64Gzip(String str) {
    ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    String result = null;//from w  w w  . j  ava2s  .  c o m
    // gzip
    GZIPOutputStream gos;
    try {
        gos = new GZIPOutputStream(baos);
        int count;
        byte data[] = new byte[1024];
        while ((count = bais.read(data, 0, 1024)) != -1) {
            gos.write(data, 0, count);
        }
        gos.finish();
        gos.close();

        byte[] output = baos.toByteArray();
        baos.flush();
        baos.close();
        bais.close();

        result = Base64.encodeToString(output, Base64.NO_WRAP);

    } catch (IOException e) {
        e.printStackTrace();
        Ln.e("NetworkHelper", "Base64Gzip == >>", e);
    }

    //Ln.i("after base64gizp", result);
    return result;
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static String encryptStringImpl(Context context, final String plainText) {
    String encryptedText = plainText;
    try {/*  w  w  w .  j  a  v a2  s  . co m*/
        final KeyStore keyStore = getKeyStore(context);

        PublicKey publicKey = keyStore.getCertificate(KEY_ALIAS).getPublicKey();

        String algorithm = ALGORITHM_OLD;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            algorithm = ALGORITHM;
        }
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
        cipherOutputStream.write(plainText.getBytes("UTF-8"));
        cipherOutputStream.close();

        byte[] bytes = outputStream.toByteArray();
        encryptedText = Base64.encodeToString(bytes, Base64.DEFAULT);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return encryptedText;
}

From source file:org.addhen.birudo.data.net.BaseHttpClient.java

public static String base64Encode(String str) {
    byte[] bytes = str.getBytes();
    return Base64.encodeToString(bytes, Base64.NO_WRAP);
}

From source file:illab.nabal.util.Util.java

/**
 * Extract Base64-encoded string from file content.
 * /*from w w w  .  j  a  v a  2 s.  co m*/
 * @param photoPath absoulte system path of photo
 * @param maxSize max file size in kilobytes
 * @return Base64-encoded string of file content
 * @throws Exception
 */
public static String extractBase64StringFromFile(String photoPath, int maxSize) throws Exception {

    String imageContent = "";

    File file = new File(photoPath);

    if (file.length() > maxSize * 1024) {
        throw new SystemException("File size must be less than " + maxSize + " kilobytes.");
    }

    byte[] buffer = new byte[(int) file.length()];
    InputStream ios = null;
    try {
        ios = new FileInputStream(file);
        if (ios.read(buffer) == -1) {
            throw new IOException("EOF reached while trying to read the whole file");
        }
    } finally {
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
        }
    }
    imageContent = Base64.encodeToString(buffer, Base64.DEFAULT);
    //Log.d(TAG, "imageContent :\n" + imageContent);

    return imageContent;
}