AES decrypt byte array Data with password - Java Security

Java examples for Security:AES

Description

AES decrypt byte array Data with password

Demo Code


//package com.java2s;
import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Main {

    private static final String CipherMode = "AES";

    public static byte[] decryptData(byte[] content, String password) {
        try {//from  w  w  w  .  j a  v  a2  s  . c  o  m
            SecretKeySpec key = generateAESKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decryptData(String content, String password) {
        byte[] data = null;
        try {
            data = hex2byte(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = decryptData(data, password);
        if (data == null)
            return null;
        String result = null;
        try {
            result = new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        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 byte[] hex2byte(String inputString) {
        if (inputString == null || inputString.length() < 2) {
            return new byte[0];
        }
        inputString = inputString.toLowerCase();
        int l = inputString.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            String tmp = inputString.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }
}

Related Tutorials