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:Main.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static String decryptStringImpl(Context context, final String encryptedText) {
    String plainText = null;/*from w w  w .  j a  va2 s. c o  m*/
    try {
        final KeyStore keyStore = getKeyStore(context);

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(KEY_ALIAS, null);

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

        CipherInputStream cipherInputStream = new CipherInputStream(
                new ByteArrayInputStream(Base64.decode(encryptedText, Base64.DEFAULT)), cipher);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int b;
        while ((b = cipherInputStream.read()) != -1) {
            outputStream.write(b);
        }
        outputStream.close();
        plainText = outputStream.toString("UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return plainText;
}

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

public static void writeObj(FileOutputStream fo, Context context, IdentitiesManager identitiesManager,
        MObject object) {//from  w w  w.  j  ava 2 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.android.emailcommon.mail.Base64Body.java

/**
 * This method consumes the input stream, so can only be called once
 * @param out Stream to write to/* w  ww .  ja v a2 s  . c om*/
 * @throws IllegalStateException If called more than once
 * @throws IOException
 * @throws MessagingException
 */
@Override
public void writeTo(OutputStream out) throws IllegalStateException, IOException, MessagingException {
    if (mAlreadyWritten) {
        throw new IllegalStateException("Base64Body can only be written once");
    }
    mAlreadyWritten = true;
    try {
        final Base64OutputStream b64out = new Base64OutputStream(out, Base64.DEFAULT);
        IOUtils.copyLarge(mSource, b64out);
    } finally {
        mSource.close();
    }
}

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

public static String encodeTobase64(Bitmap image) {
    Bitmap bmImage = image;// www  .ja v a  2s.com

    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.//  ww  w.j a va 2  s  .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:Main.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static String encryptStringImpl(Context context, final String plainText) {
    String encryptedText = plainText;
    try {/*from w  w  w  .j a  v a 2s .  c  om*/
        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:illab.nabal.util.Util.java

/**
 * Extract Base64-encoded string from file content.
 * //from  w  ww .ja va  2  s. c o 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;
}

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 {/* ww w . jav a2  s.co  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.drisoftie.cwdroid.util.CredentialUtils.java

public static String deobfuscateFromBase64(byte[] key, String basePassword) {
    String result = null;/* w  w w .j  a va 2s  . c o m*/
    try {
        byte[] cleared = Base64.decode(basePassword, Base64.DEFAULT);
        byte[] decrypted = decrypt(key, cleared);
        result = new String(decrypted, CharEncoding.UTF_8);
    } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException
            | IllegalBlockSizeException | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:org.sigimera.app.android.backend.network.LoginHttpHelper.java

@Override
protected Boolean doInBackground(String... params) {
    HttpClient httpclient = new MyHttpClient(ApplicationController.getInstance().getApplicationContext());
    HttpPost request = new HttpPost(HOST);
    request.addHeader("Host", "api.sigimera.org:443");

    /**/*w w  w . j a  v  a2  s  . c o  m*/
     * Basic Authentication for the auth_token fetching:
     * 
     * Authorization: Basic QWxhZGluOnNlc2FtIG9wZW4=
     */
    StringBuffer authString = new StringBuffer();
    authString.append(params[0]);
    authString.append(":");
    authString.append(params[1]);
    String basicAuthentication = "Basic "
            + Base64.encodeToString(authString.toString().getBytes(), Base64.DEFAULT);
    request.addHeader("Authorization", basicAuthentication);

    try {
        HttpResponse result = httpclient.execute(request);

        JSONObject json_response = new JSONObject(
                new BufferedReader(new InputStreamReader(result.getEntity().getContent())).readLine());
        if (json_response.has("auth_token")) {
            SharedPreferences.Editor editor = ApplicationController.getInstance().getSharedPreferences().edit();
            editor.putString("auth_token", json_response.getString("auth_token"));
            return editor.commit();
        } else if (json_response.has("error")) {
            return false;
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return false;
}