AES encrypt To Bytes - Android java.security

Android examples for java.security:AES

Description

AES encrypt To Bytes

Demo Code


//package com.java2s;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static byte[] encryptToBytes(String key, String src)
            throws Exception {
        byte[] rawKey = getRawKey(key);
        return encrypt(rawKey, src.getBytes());
    }//from  w ww. ja v a2  s .  c om

    private static byte[] getRawKey(String key) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(key.getBytes());
        kgen.init(256, sr);
        SecretKey skey = kgen.generateKey();
        return skey.getEncoded();
    }

    private static byte[] encrypt(byte[] key, byte[] src) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        return cipher.doFinal(src);
    }
}

Related Tutorials