Encrypts the text using AES - Android java.security

Android examples for java.security:AES

Description

Encrypts the text using AES

Demo Code


//package com.java2s;
import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    /**//from w  ww  . j av a  2  s  .c o  m
     * Encrypts the text
     *
     * @param seed          The secret/seed key
     * @param textToEncrypt The text you want to encrypt
     * @return Encrypted data if successful, or null if unsuccessful
     */
    public static String encrypt(String seed, String textToEncrypt) {
        byte[] encryptedText;
        try {
            byte[] keyData = seed.getBytes();
            SecretKey ks = new SecretKeySpec(keyData, "AES");
            Cipher c = Cipher.getInstance("AES");
            c.init(Cipher.ENCRYPT_MODE, ks);
            encryptedText = c.doFinal(textToEncrypt.getBytes("UTF-8"));
            return Base64.encodeToString(encryptedText, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related Tutorials