java中AES加解密

public class AESUtils {

        private static  final String initVector = "57635e22b48356ad";

/**
     * 解密
     *
     * @param key
     * @param encrypted
     * @return
     */
    public static String decrypt(String key, String encrypted) {
        try {
            IvParameterSpec iv = new
                    IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new
                    SecretKeySpec(key.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] original =
                    cipher.doFinal(Base64.decodeBase64(encrypted));
            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 加密
     *
     * @param key
     * @param value
     * @return
     */
    public static String encrypt(String key, String value) {
        try {
            IvParameterSpec iv = new
                    IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new
                    SecretKeySpec(key.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(value.getBytes("UTF-8"));
            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}

 

posted @ 2023-01-30 10:20  天戈  阅读(117)  评论(0编辑  收藏  举报