Android AES Encrypt encrypt(byte[] key, byte[] src)

Here you can find the source of encrypt(byte[] key, byte[] src)

Description

encrypt

Declaration

private static byte[] encrypt(byte[] key, byte[] src) throws Exception 

Method Source 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;
import android.os.Build;

public class Main {
    private final static String HEX = "0123456789ABCDEF";

    public static String encrypt(String key, String src) throws Exception {
        byte[] rawKey = getRawKey(key.getBytes());
        byte[] result = encrypt(rawKey, src.getBytes());
        return toHex(result);
    }//from  w  w w . ja va  2s .  c  o m

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

    private static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = null;
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
        } else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
        } else {
            sr = SecureRandom.getInstance("SHA1PRNG");
        }
        sr.setSeed(seed);
        kgen.init(256, sr); //256 bits or 128 bits,192bits  
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        return raw;
    }

    public static String toHex(String txt) {
        return toHex(txt.getBytes());
    }

    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }
}

Related

  1. encrypt(byte[] data, Key key)
  2. encrypt(byte[] data, Key key, String cipherAlgorithm)
  3. encrypt(byte[] data, byte[] key)
  4. encrypt(byte[] data, byte[] key, String cipherAlgorithm)
  5. encrypt(byte[] key, byte[] src)
  6. encrypt(byte[] raw, byte[] clear)
  7. encrypt(byte[] raw, byte[] clear)
  8. encrypt(byte[] raw, byte[] clear)
  9. encrypt(byte[] raw, byte[] clear)