AES encrypt Data - Android java.security

Android examples for java.security:AES

Description

AES encrypt Data

Demo Code


//package com.java2s;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Main {

    private static final String CipherMode = "AES";

    public static byte[] encryptData(byte[] content, String password) {
        try {//from  www . java2 s.  co m
            SecretKeySpec key = generateAESKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encryptData(String content, String password) {
        byte[] data = null;
        try {
            data = content.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = encryptData(data, password);
        String result = byte2hex(data);
        return result;
    }

    private static SecretKeySpec generateAESKey(String password) {
        byte[] data = null;
        StringBuilder sb = new StringBuilder();
        sb.append(password);
        while (sb.length() < 16)
            sb.append("0");
        if (sb.length() > 16)
            sb.setLength(16);
        try {
            data = sb.toString().getBytes("UTF-8");
            return new SecretKeySpec(data, "AES");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String byte2hex(byte[] b) { // ???????
        StringBuffer sb = new StringBuffer(b.length * 2);
        String tmp = "";
        for (int n = 0; n < b.length; n++) {
            // ?????????????
            tmp = (Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); // ?????
    }
}

Related Tutorials