encrypt By AES - Android java.security

Android examples for java.security:AES

Description

encrypt By AES

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;
import android.text.TextUtils;

public class Main {
    private static final String AES_SEED = "COM.sfsdU.SNS";
    private final static String HEX = "0123456789ABCDEF";

    public static String encryptByAES(String source) {
        //        return source;
        if (TextUtils.isEmpty(source)) {
            return source;
        }/*from ww  w  .  j  a  va  2 s. c  o  m*/

        try {
            return encryptByAES(AES_SEED, source);
        } catch (Exception e) {
            e.printStackTrace();
            return source;
        }
    }

    /**
     * @param seed
     * @param cleartext
     * @return
     * @throws Exception
     */
    private static String encryptByAES(String seed, String cleartext)
            throws Exception {
        byte[] rawKey = getRawKeyByAES(seed.getBytes());
        byte[] result = encryptByAES(rawKey, cleartext.getBytes());
        return toHex(result);
    }

    private static byte[] encryptByAES(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[] getRawKeyByAES(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
        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 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 Tutorials