encrypt Base64 String - Android java.lang

Android examples for java.lang:String Base64

Description

encrypt Base64 String

Demo Code


import android.text.TextUtils;
import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main{
    private static final String UTF8 = "UTF-8";
    static String encryptBase64(String text, String encryptKey,
            String encryptIv) {/*w  ww. ja  v  a2  s .  co m*/
        byte[] crypted = TOGCipherUtil.encrypt(text, encryptKey, encryptIv);
        String resultStr = Base64.encodeToString(crypted, Base64.NO_WRAP);
        return resultStr;

    }
    static byte[] encrypt(String text, String encryptKey, String encryptIv) {

        if (TextUtils.isEmpty(text)) {
            return null;
        }
        byte[] byteResult = null;
        try {
            byte[] byteText = text.getBytes(UTF8);
            byte[] byteKey = encryptKey.getBytes(UTF8);
            byte[] byteIv = encryptIv.getBytes(UTF8);
            SecretKeySpec key = new SecretKeySpec(byteKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(byteIv);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, iv);
            byteResult = cipher.doFinal(byteText);
            return byteResult;
        } catch (Exception e) {
        }

        return byteResult;
    }
}

Related Tutorials