AES encrypt string by string key - Android java.security

Android examples for java.security:AES

Description

AES encrypt string by string key

Demo Code

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

public class Main{


    public static String encrypt(String data, String key) throws Exception {
        try {/* w  ww. ja v a2s  .  co m*/
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] base64Key = Base64.decode(key, Base64.DEFAULT);
            SecretKeySpec keyspec = new SecretKeySpec(base64Key, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, keyspec);
            byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.encodeToString(encrypted, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}

Related Tutorials