AES encrypt String - Android java.security

Android examples for java.security:AES

Description

AES encrypt String

Demo Code

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

public class Main{

    public static String encrypt(String text) throws Exception {
        return Base64.encodeToString(getCipher(Cipher.ENCRYPT_MODE)
                .doFinal(padString(text).getBytes()), Base64.NO_PADDING);
    }//from w w w.j a va2s  .c om
    private static Cipher getCipher(int ENCRYPT_MODE) throws Exception {

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(ENCRYPT_MODE, new SecretKeySpec(SECRET_KEY.getBytes(),
                ALGORITHM), new IvParameterSpec(SECRET_IV.getBytes()));

        return cipher;
    }
    private static String padString(String source) {
        int size = 16;
        int padLength = size - (source.length() % size);

        for (int i = 0; i < padLength; i++)
            source += ' ';

        return source;
    }

}

Related Tutorials