Example usage for android.util Base64 encode

List of usage examples for android.util Base64 encode

Introduction

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

Prototype

public static byte[] encode(byte[] input, int flags) 

Source Link

Document

Base64-encode the given data and return a newly allocated byte[] with the result.

Usage

From source file:org.creativecommons.thelist.utils.FileHelper.java

public static String getByteArrayFromFile(Context context, Uri uri) {
    byte[] fileBytes;
    String fileString = null;//from w ww  . ja v  a 2s  .  c o m
    InputStream inStream = null;
    ByteArrayOutputStream outStream = null;

    if (uri.getScheme().equals("content")) {
        try {
            inStream = context.getContentResolver().openInputStream(uri);
            outStream = new ByteArrayOutputStream();

            byte[] bytesFromFile = new byte[1024 * 1024]; // buffer size (1 MB)
            int bytesRead = inStream.read(bytesFromFile);
            while (bytesRead != -1) {
                outStream.write(bytesFromFile, 0, bytesRead);
                bytesRead = inStream.read(bytesFromFile);
            }

            fileBytes = outStream.toByteArray();
            fileString = new String(Base64.encode(fileBytes, Base64.DEFAULT));
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        } finally {
            try {
                inStream.close();
                outStream.close();
            } catch (IOException e) {
                /*( Intentionally blank */ }
        }
    } else {
        try {
            File file = new File(uri.getPath());
            FileInputStream fileInput = new FileInputStream(file);
            fileBytes = IOUtils.toByteArray(fileInput);
            fileString = new String(Base64.encode(fileBytes, Base64.DEFAULT));
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
    }

    return fileString;
}

From source file:Main.java

public static byte[] generateRequestToken(byte[] countryCode, byte[] phoneNumber)
        throws NoSuchAlgorithmException {

    String signature = "MIIDMjCCAvCgAwIBAgIETCU2pDALBgcqhkjOOAQDBQAwfDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFDASBgNVBAcTC1NhbnRhIENsYXJhMRYwFAYDVQQKEw1XaGF0c0FwcCBJbmMuMRQwEgYDVQQLEwtFbmdpbmVlcmluZzEUMBIGA1UEAxMLQnJpYW4gQWN0b24wHhcNMTAwNjI1MjMwNzE2WhcNNDQ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.  ja  v  a2  s. c  o  m*/

    byte[] data = concat(
            concat(Base64.decode(signature, Base64.DEFAULT), Base64.decode(classesMd5, Base64.DEFAULT)),
            phoneNumber);

    byte[] opad = new byte[64];
    byte[] ipad = new byte[64];
    for (int i = 0; i < opad.length; i++) {
        opad[i] = 0x5C;
        ipad[i] = 0x36;
    }

    for (int i = 0; i < 64; i++) {
        opad[i] = (byte) ((opad[i] & 0xFF) ^ (key2[i] & 0xFF));
        ipad[i] = (byte) ((ipad[i] & 0xFF) ^ (key2[i] & 0xFF));
    }

    data = concat(ipad, data);

    MessageDigest md = MessageDigest.getInstance("SHA-1");
    md.update(data);
    byte[] firstHash = md.digest();

    data = concat(opad, firstHash);
    md = MessageDigest.getInstance("SHA-1");
    md.update(data);
    byte[] secondHash = md.digest();

    return Base64.encode(secondHash, Base64.DEFAULT | Base64.NO_WRAP);
}

From source file:com.eugene.fithealthmaingit.FatSecretSearchAndGet.FatSecretGetMethod.java

private static String sign(String method, String uri, String[] params) {
    String[] p = { method, Uri.encode(uri), Uri.encode(paramify(params)) };
    String s = join(p, "&");
    SecretKey sk = new SecretKeySpec(Globals.APP_SECRET.getBytes(), Globals.HMAC_SHA1_ALGORITHM);
    try {/*from   w w  w.  jav  a  2  s.c  o  m*/
        Mac m = Mac.getInstance(Globals.HMAC_SHA1_ALGORITHM);
        m.init(sk);
        return Uri.encode(new String(Base64.encode(m.doFinal(s.getBytes()), Base64.DEFAULT)).trim());
    } catch (java.security.NoSuchAlgorithmException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    } catch (java.security.InvalidKeyException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    }
}

From source file:com.redwoodsystems.android.apps.utils.HttpUtil.java

public static String getAuthHeader(String userName, String password) {
    String s = userName + ":" + password;
    String authHdr = "Basic " + Base64.encode(s.getBytes(), Base64.DEFAULT);
    return authHdr;
}

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

/**
 * Get HMACSHA1-encoded OAuth 1.0a signature string.
 * //from   www.  ja v  a 2s  .co m
 * @param secretKey - secret key to encode basestring with
 * @param baseString - signature base string 
 * @return oauthSignature - HMAC-SHA1 encoded signature string
 * @throws Exception
 */
public static String getHmacSha1Signature(String secretKey, String baseString) throws Exception {
    String oauthSignature = null;

    // #################### IMPORTANT ####################
    // the secret key is the concatenated values (each first encoded per Parameter 
    // Encoding) of the Consumer Secret and Token Secret, separated by an '&' character 
    // (ASCII code 38) even if empty.

    if (StringHelper.isAllFull(secretKey, baseString) == true) {
        byte[] keyBytes = secretKey.getBytes(HTTP.UTF_8);
        SecretKey keySpec = new SecretKeySpec(keyBytes, HMAC_SHA1);
        Mac mac = Mac.getInstance(HMAC_SHA1);
        mac.init(keySpec);
        oauthSignature = new String(Base64.encode(mac.doFinal(baseString.getBytes(HTTP.UTF_8)), Base64.DEFAULT),
                HTTP.UTF_8).trim();
    }
    return oauthSignature;
}

From source file:github.nisrulz.optimushttp.HttpReq.java

@Override
protected String doInBackground(HttpReqPkg... params) {

    URL url;/*from   w  w w . j a  va2 s.  c o  m*/
    BufferedReader reader = null;

    String username = params[0].getUsername();
    String password = params[0].getPassword();
    String authStringEnc = null;

    if (username != null && password != null) {
        String authString = username + ":" + password;

        byte[] authEncBytes;
        authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
        authStringEnc = new String(authEncBytes);
    }

    String uri = params[0].getUri();

    if (params[0].getMethod().equals("GET")) {
        uri += "?" + params[0].getEncodedParams();
    }

    try {
        StringBuilder sb;
        // create the HttpURLConnection
        url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        if (authStringEnc != null) {
            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }

        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")
                || params[0].getMethod().equals("DELETE")) {
            // enable writing output to this url
            connection.setDoOutput(true);
        }

        if (params[0].getMethod().equals("POST")) {
            connection.setRequestMethod("POST");
        } else if (params[0].getMethod().equals("GET")) {
            connection.setRequestMethod("GET");
        } else if (params[0].getMethod().equals("PUT")) {
            connection.setRequestMethod("PUT");
        } else if (params[0].getMethod().equals("DELETE")) {
            connection.setRequestMethod("DELETE");
        }

        // give it x seconds to respond
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setRequestProperty("Content-Type", contentType);

        for (int i = 0; i < headerMap.size(); i++) {
            connection.setRequestProperty(headerMap.keyAt(i), headerMap.valueAt(i));
        }

        connection.setRequestProperty("Content-Length", "" + params[0].getEncodedParams().getBytes().length);

        connection.connect();
        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(params[0].getEncodedParams());
            writer.flush();
            writer.close();
        }

        // read the output from the server
        InputStream in;
        resCode = connection.getResponseCode();
        resMsg = connection.getResponseMessage();
        if (resCode != HttpURLConnection.HTTP_OK) {
            in = connection.getErrorStream();
        } else {
            in = connection.getInputStream();
        }
        reader = new BufferedReader(new InputStreamReader(in));
        sb = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        sb.append(resCode).append(" : ").append(resMsg);
        return sb.toString();
    } catch (Exception e) {
        listener.onFailure(Integer.toString(resCode) + " : " + resMsg);
        e.printStackTrace();
    } finally {
        // close the reader; this can throw an exception too, so
        // wrap it in another try/catch block.
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    return null;
}

From source file:de.knufficast.flattr.FlattrApi.java

private void login() {
    try {/*from  ww w  .  j a va 2  s.c  o  m*/
        JSONObject json = new JSONObject();
        json.put("code", config.getAuthCode());
        json.put("grant_type", "authorization_code");
        json.put("redirect_uri", "knufficastoauth://");
        // the client ID and secret are used as username and password
        // encode username and password using base64 user:password (BASIC auth for
        // http)
        String userPassword = "Basic " + new String(Base64.encode(
                (CONSTANTS.getClientId() + ":" + CONSTANTS.getClientSecret()).getBytes(), Base64.NO_WRAP));
        JSONObject response = postAuthorized(LOGIN_URL, json, userPassword);
        if (response.getString("access_token") != null) {
            config.setAccessToken(response.getString("access_token"));
            config.setFlattrStatus(FlattrStatus.AUTHENTICATED);
        } else {
            config.resetAuthentication();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        config.resetAuthentication();
    }
}

From source file:connection.HttpReq.java

@Override
protected String doInBackground(HttpReqPkg... params) {

    URL url;//from   w w w.jav  a2 s  .c  om
    BufferedReader reader = null;

    String username = params[0].getUsername();
    String password = params[0].getPassword();
    String authStringEnc = null;

    if (username != null && password != null) {
        String authString = username + ":" + password;

        byte[] authEncBytes;
        authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
        authStringEnc = new String(authEncBytes);
    }

    String uri = params[0].getUri();

    if (params[0].getMethod().equals("GET")) {
        uri += "?" + params[0].getEncodedParams();
    }

    try {
        StringBuilder sb;
        // create the HttpURLConnection
        url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        if (authStringEnc != null) {
            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }

        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")
                || params[0].getMethod().equals("DELETE")) {
            // enable writing output to this url
            connection.setDoOutput(true);
        }

        if (params[0].getMethod().equals("POST")) {
            connection.setRequestMethod("POST");
        } else if (params[0].getMethod().equals("GET")) {
            connection.setRequestMethod("GET");
        } else if (params[0].getMethod().equals("PUT")) {
            connection.setRequestMethod("PUT");
        } else if (params[0].getMethod().equals("DELETE")) {
            connection.setRequestMethod("DELETE");
        }

        // give it x seconds to respond
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setRequestProperty("Content-Type", contentType);

        for (int i = 0; i < headerMap.size(); i++) {
            connection.setRequestProperty(headerMap.keyAt(i), headerMap.valueAt(i));
        }

        connection.setRequestProperty("Content-Length", "" + params[0].getEncodedParams().getBytes().length);

        connection.connect();
        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            String httpParams = params[0].getEncodedParams();

            if (contentType.equals(OptimusHTTP.CONTENT_TYPE_JSON)) {
                httpParams = httpParams.replace("=", " ");
            }

            writer.write(httpParams);
            writer.flush();
            writer.close();
        }

        // read the output from the server
        InputStream in;
        resCode = connection.getResponseCode();
        resMsg = connection.getResponseMessage();
        if (resCode != HttpURLConnection.HTTP_OK) {
            in = connection.getErrorStream();
        } else {
            in = connection.getInputStream();
        }
        reader = new BufferedReader(new InputStreamReader(in));
        sb = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        sb.append(resCode).append(" : ").append(resMsg);
        return sb.toString();
    } catch (Exception e) {
        listener.onFailure(Integer.toString(resCode) + " : " + resMsg);
        e.printStackTrace();
    } finally {
        // close the reader; this can throw an exception too, so
        // wrap it in another try/catch block.
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    return null;
}

From source file:com.hkm.Application.appWork.java

private void showpackagesigning() {
    PackageInfo packageInfo;//from  w  ww.j  a v  a 2s.  c  om
    try {
        packageInfo = getPackageManager().getPackageInfo("com.hkm.oc.app", PackageManager.GET_SIGNATURES);
        for (Signature signature : packageInfo.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            String key = new String(Base64.encode(md.digest(), 0));
            // String key = new String(Base64.encodeBytes(md.digest()));
            Log.e("Hash key", sha1Hash(key));
        }
    } catch (PackageManager.NameNotFoundException e1) {
        Log.e("Name not found", e1.toString());
    } catch (NoSuchAlgorithmException e) {
        Log.e("No such an algorithm", e.toString());
    } catch (Exception e) {
        Log.e("Exception", e.toString());
    }
}

From source file:org.apache.cordova.crypt.Crypt.java

public String encrypt(String data, String publickey) throws Exception {
    publickey = publickey.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");

    try {//from   ww  w . j av  a  2  s .  co  m
        byte[] publickeyRaw = Base64.decode(publickey, Base64.DEFAULT);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publickeyRaw);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PublicKey pub = fact.generatePublic(keySpec);

        byte[] text = data.getBytes(Charset.forName("UTF-8"));

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, pub);
        byte[] cipherString = cipher.doFinal(text);

        return new String(Base64.encode(cipherString, Base64.DEFAULT));

    } catch (Exception e) {
        Log.w("Crypt", e);
        return null;
    }
}