Android AES Encrypt aesEncode(String seed, String cleartext)

Here you can find the source of aesEncode(String seed, String cleartext)

Description

aes Encode

Declaration

public static String aesEncode(String seed, String cleartext)
            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 aesEncode(String seed, String cleartext)
            throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = encrypt(rawKey, cleartext.getBytes());
        return toHex(result);
    }// w  w  w  .  j ava2 s  . c o  m

    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;
    }

    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;
    }

    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. encryptToBase64Text(String key, String src)
  2. encryptToBytes(String key, String src)
  3. encryptUrlEncode(String dataPassword, String cleartext)
  4. encryptWithKey(String key, String src)
  5. crypt(byte[] text, byte[] key, int mode)
  6. encrypt(byte[] raw, byte[] clear)
  7. encrypt(Context context, String text)
  8. encrypt(Context context, String text)
  9. encryptedData(String userkey, String userData)