Android AES Encrypt encrypt(byte[] raw, byte[] clear)

Here you can find the source of encrypt(byte[] raw, byte[] clear)

Description

encrypt

Declaration

private static byte[] encrypt(byte[] raw, byte[] clear)
            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;

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

    public static String encrypt(String seed, String cleartext)
            throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = encrypt(rawKey, cleartext.getBytes());
        return toHex(result);
    }/*from w w  w . j ava 2  s  . co m*/

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

    private static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
        kgen.init(128, sr); // 192 and 256 bits may not be available
        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, byte[] key)
  2. encrypt(byte[] data, byte[] key, String cipherAlgorithm)
  3. encrypt(byte[] key, byte[] src)
  4. encrypt(byte[] key, byte[] src)
  5. encrypt(byte[] raw, byte[] clear)
  6. encrypt(byte[] raw, byte[] clear)
  7. encrypt(byte[] raw, byte[] clear)
  8. encrypt(byte[] source)
  9. encryptBase64(String content, String key)