AES encrypt Data with password - Java Security

Java examples for Security:AES

Description

AES encrypt Data with password

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 {/* ww w  .  j  a v  a 2 s .  c o  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 = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); 
    }
}

Related Tutorials