aes encryption tools

public class AESUtils {
    // algorithm / mode / padding
    private static final String CipherMode = "AES/CBC/PKCS5Padding";
    // Hi钥
    private static String DEFAULST_SECURITY_KEY = "69a183bbca2d9a01914d2dfa34455742";

    private static final String encodFormat = "UTF-8";

    /**
     * Create key
     *
     * @Param key
     * @return
     */
    private static SecretKeySpec createKey(String key) {
        key = key == null ? "" : key;
        StringBuilder sb = new StringBuilder(16);
        sb.append(key);
        while (sb.length() < 16) {
            sb.append("0");
        }
        if (sb.length() > 16) {
            sb.setLength(16);
        }

        byte[] data = null;
        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        }
        return new SecretKeySpec(data, "AES");
    }

    /**
     * Create an initialization vector
     *
     * @param password
     * @return
     */
    private static IvParameterSpec createIV(String password) {
        password = password == null ? "" : password;
        StringBuilder sb = new StringBuilder(16);
        sb.append(password);
        while (sb.length() < 16) {
            sb.append("0");
        }
        if (sb.length() > 16) {
            sb.setLength(16);
        }

        byte[] data = null;
        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        }
        return new IvParameterSpec(data);
    }

    /**
     * AES-128 / CBC algorithm to encrypt data bytes
     *
     * @param content
     * @Param password key
     * @Param iv initialization vector
     * @return byte[]
     */
    public static byte[] aes128CBCEncrypt(byte[] content, String password, String iv) {
        try {
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, createKey(password), createIV(iv));
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return null;
    }


    /**
     * AES-128 / CBC algorithm decryption byte array
     *
     * @param content
     * @Param password key
     * @Param iv initialization vector
     * @return byte[]
     */
    public static byte[] aes128CBCDecrypt(byte[] content, String password, String iv) {
        try {
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, createKey(password), createIV(iv));
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return null;
    }


    /**
     * AES-128 encryption string
     *
     * @param content
     * @return
     */
    public static String encrypt(String content) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(DEFAULST_SECURITY_KEY.getBytes(encodFormat)));
            byte[] bytes = kgen.generateKey().getEncoded();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(bytes, "AES"));
            byte[] result = cipher.doFinal(content.getBytes(encodFormat));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < result.length; i++) {
                String hex = Integer.toHexString(result[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return null;
    }

    /**
     * AES-128 CBC encryption, transcoding encrypted using Base64
     *
     * @Param content to be encrypted content
     * @param encodingFormat
     * @Param key the key
     * @Param initVector initialization vector
     * @return
     * @throws Exception
     */
    public static String aesCBCEncrypt(String content, String encodingFormat, String key, String initVector) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(encodingFormat), "AES");
            // CBC mode requires an IV vector, to increase the strength of the encryption algorithm
            IvParameterSpec vector = new IvParameterSpec(initVector.getBytes(encodingFormat));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, vector);
            byte[] encrypted = cipher.doFinal(content.getBytes(encodingFormat));
            // here to use BASE64 to do transcoding.
            String result = new BASE64Encoder().encode(encrypted);
            return result;
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return null;
    }

    /**
     * AES-128 CBC mode decrypting
     *
     * @Param content to be decrypted Base64 string
     * @param encodingFormat
     * @Param key the key
     * @Param initVector initialization vector
     * @return
     */
    public static String aesCBCDecrypt(String content, String encodingFormat, String key, String initVector) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(encodingFormat), "AES");
            IvParameterSpec vector = new IvParameterSpec(initVector.getBytes());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, vector);
            // first with base64 encoding, since the corresponding decoding encrypted using Base64
            byte[] base64Bytes = new BASE64Decoder().decodeBuffer(content);
            byte[] original = cipher.doFinal(base64Bytes);
            String result = new String(original, encodingFormat);
            return result;
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return null;
    }

    /**
     * Encryption general content
     *
     * */
    public static String encrypt(String content, String key) {
        if (isEmpty(key)) {
            return encrypt(content);
        }
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(key.getBytes(encodFormat)));
            byte[] bytes = kgen.generateKey().getEncoded();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(bytes, "AES"));
            byte[] result = cipher.doFinal(content.getBytes(encodFormat));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < result.length; i++) {
                String hex = Integer.toHexString(result[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace ();
        }

        return null;
    }

    /**
     * Decryption
     *
     * @param content
     * @return
     */
    public static String decrypt(String content) {
        if (isEmpty(content)) {
            return null;
        }
        byte[] bytes = new byte[content.length() / 2];
        for (int i = 0; i < content.length() / 2; i++) {
            int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
            bytes[i] = (byte) (high * 16 + low);
        }
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(DEFAULST_SECURITY_KEY.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] result = cipher.doFinal(bytes);
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace ();
        }

        return null;
    }

    /**
     * Decryption
     *
     * @param content
     * @param securityKey
     * @return
     */
    public static String decrypt(String content, String securityKey) {

        if (isEmpty(securityKey)) {
            return decrypt(content);
        }
        byte[] bytes = new byte[content.length() / 2];
        for (int i = 0; i < content.length() / 2; i++) {
            int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
            bytes[i] = (byte) (high * 16 + low);
        }
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(securityKey.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] result = cipher.doFinal(bytes);
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace ();
        }

        return null;
    }

    private static boolean equal(byte[] a1, byte[] a2) {
        if (a1 != null && a2 != null && a1.length == a2.length) {
            for (int i = 0; i < a1.length; i++) {
                if (a1[i] != a2[i]) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    private static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }


    public static void main(String... args) throws UnsupportedEncodingException {

       /* String initVector = "AaBbCcDd1234!@#$";
        String key = "WwXxYyZz1234!@#$";

        int total = 100000;
        int run = 0;
        int count = 0;
        String[] strArr = new String[]{
                "//////\\\\+++、、",
                "+++、、//////\\++!",
                "++!@#%¥……,。、……&*(",
                "【】)&(\\\" + \"中国",
                "In fact,"
                "& (\\\" + \ "Chinese yo who's actually 122 of you"
                "12343567"};
        Random random = new Random(System.currentTimeMillis());
        for (int i = 0; i < total; i++) {
            run++;
            StringBuilder builder = new StringBuilder();
            builder.append(random.nextInt(strArr.length));
            builder.append(random.nextInt(strArr.length));
            builder.append(random.nextInt(strArr.length));
            builder.append(random.nextInt(strArr.length));
            builder.append(random.nextInt(strArr.length));
            byte[] original = builder.toString().getBytes("UTF-8");
            byte[] encrypted = aes128CBCEncrypt(original, key, initVector);
            byte[] decrypted = aes128CBCDecrypt(encrypted, key, initVector);
            if (equal(original, decrypted)) {
                count++;
            } else {
                System.out.println ( "inconsistent after encryption string");
                System.out.println ( "original string:" + Arrays.toString (encrypted));
                System.out.println ( "decryption string:" + Arrays.toString (decrypted));
            }
        }
        if (total == count) {
            System.out.println ( "everything passed");
        } else {
            System.out.println ( "data encryption and decryption defects");
        }

        System.out.println ( "The total number of runs is:" + run); * /
       String result= aesCBCDecrypt("cArgNYmA0cCFwKRV7B5FBvrKBSW4G8M+Qi/xqO0GDP4=","utf-8","69a183bbca2d9a01914d2dfa34455742","69a183bbca2d9a01");
        System.out.println("result"+result);


    }

}

Guess you like

Origin www.cnblogs.com/liangb/p/12096736.html