Java實現(xiàn)AES加密

  • AES加密為對稱加密算法,即加密和解密都使用同一個密鑰進行。

AES是分組加密,就是說它將明文分成固定的分組,對固定大小的分組加密的算法。

  • AES每次處理128位的輸入,但是一般的輸入都不止128位的輸入,所以一般我們要選擇合適的模式。(即在編碼中選擇的模式)
    • 模式是將數(shù)據(jù)分組串起來從而使得任意數(shù)據(jù)都能被加密的算法
  • 填充: 填充的作用是在加密前將普通文本拓展到需要的長度,關鍵在于填充的數(shù)據(jù)能夠在解密后正確的移除。

AES加密Java實現(xiàn):

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AESUtils {
    private static final String ENCRY_ALGORITHM = "AES";

    /**
     * 加密算法/加密模式/填充類型
     * 本例采用AES加密,ECB加密模式,PKCS5Padding填充
     */
    private static final String CIPHER_MODE = "AES/ECB/PKCS5Padding";

    /**
     * 設置iv偏移量
     * 本例采用ECB加密模式,不需要設置iv偏移量
     */
    private static final String IV_ = null;

    /**
     * 設置加密字符集
     * 本例采用 UTF-8 字符集
     */
    private static final String CHARACTER = "UTF-8";

    /**
     * 設置加密密碼處理長度。
     * 不足此長度補0;
     */
    private static final int PWD_SIZE = 16;


    /**
     * 密碼處理方法(將String轉換為byte[])
     * 如果加解密出問題,
     * 請先查看本方法,排除密碼長度不足填充0字節(jié),導致密碼不一致
     *
     * @param password 待處理的密碼
     * @return
     * @throws UnsupportedEncodingException
     */
    private static byte[] pwdHandler(String password) throws UnsupportedEncodingException {
        byte[] data = null;
        if (password != null) {
            byte[] bytes = password.getBytes(CHARACTER);
            if (password.length() < PWD_SIZE) {
                System.arraycopy(bytes, 0, data = new byte[PWD_SIZE], 0, bytes.length);
            } else {
                data = bytes;
            }
        }
        return data;
    }


    /**
     * 原始加密
     *
     * @param clearTextBytes 明文字節(jié)數(shù)組,待加密的字節(jié)數(shù)組
     * @param pwdBytes       加密密碼字節(jié)數(shù)組
     * @return 返回加密后的密文字節(jié)數(shù)組,加密錯誤返回null
     */
    public static byte[] encrypt(byte[] clearTextBytes, byte[] pwdBytes) {
        try {
            // 1 獲取加密密鑰
            SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);

            // 2 獲取Cipher實例
            Cipher cipher = Cipher.getInstance(CIPHER_MODE);

            // 查看數(shù)據(jù)塊位數(shù) 默認為16(byte) * 8 =128 bit
//            System.out.println("數(shù)據(jù)塊位數(shù)(byte):" + cipher.getBlockSize());

            // 3 初始化Cipher實例。設置執(zhí)行模式以及加密密鑰
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);

            // 4 執(zhí)行
            byte[] cipherTextBytes = cipher.doFinal(clearTextBytes);

            // 5 返回密文字符集
            return cipherTextBytes;

        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static byte[] decrypt(byte[] cipherTextBytes, byte[] pwdBytes) {

        try {
            // 1 獲取解密密鑰
            SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);

            // 2 獲取Cipher實例
            Cipher cipher = Cipher.getInstance(CIPHER_MODE);

            // 查看數(shù)據(jù)塊位數(shù) 默認為16(byte) * 8 =128 bit
//            System.out.println("數(shù)據(jù)塊位數(shù)(byte):" + cipher.getBlockSize());

            // 3 初始化Cipher實例。設置執(zhí)行模式以及加密密鑰
            cipher.init(Cipher.DECRYPT_MODE, keySpec);

            // 4 執(zhí)行
            byte[] clearTextBytes = cipher.doFinal(cipherTextBytes);

            // 5 返回明文字符集
            return clearTextBytes;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解密錯誤 返回null
        return null;
    }

    //======================>BASE64<======================

    /**
     * BASE64加密
     *
     * @param clearText 明文,待加密的內容
     * @param password  密碼,加密的密碼
     * @return 返回密文,加密后得到的內容。加密錯誤返回null
     */
    public static String encryptBase64(String clearText, String password) {
        try {
            // 1 獲取加密密文字節(jié)數(shù)組
            byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));

            // 2 對密文字節(jié)數(shù)組進行BASE64 encoder 得到 BASE6輸出的密文
            BASE64Encoder base64Encoder = new BASE64Encoder();
            String cipherText = base64Encoder.encode(cipherTextBytes);

            // 3 返回BASE64輸出的密文
            return cipherText;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 加密錯誤 返回null
        return null;
    }


    /**
     * BASE64解密
     *
     * @param cipherText 密文,帶解密的內容
     * @param password   密碼,解密的密碼
     * @return 返回明文,解密后得到的內容。解密錯誤返回null
     */
    public static String decryptBase64(String cipherText, String password) {
        try {
            // 1 對 BASE64輸出的密文進行BASE64 decodebuffer 得到密文字節(jié)數(shù)組
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] cipherTextBytes = base64Decoder.decodeBuffer(cipherText);

            // 2 對密文字節(jié)數(shù)組進行解密 得到明文字節(jié)數(shù)組
            byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));

            // 3 根據(jù) CHARACTER 轉碼,返回明文字符串
            return new String(clearTextBytes, CHARACTER);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解密錯誤返回null
        return null;
    }


    /**
     * HEX加密
     *
     * @param clearText 明文,待加密的內容
     * @param password  密碼,加密的密碼
     * @return 返回密文,加密后得到的內容。加密錯誤返回null
     */
    public static String encryptHex(String clearText, String password) {
        try {
            // 1 獲取加密密文字節(jié)數(shù)組
            byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));

            // 2 對密文字節(jié)數(shù)組進行 轉換為 HEX輸出密文
            String cipherText = byte2hex(cipherTextBytes);

            // 3 返回 HEX輸出密文
            return cipherText;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 加密錯誤返回null
        return null;
    }

    /**
     * HEX解密
     *
     * @param cipherText 密文,帶解密的內容
     * @param password   密碼,解密的密碼
     * @return 返回明文,解密后得到的內容。解密錯誤返回null
     */
    public static String decryptHex(String cipherText, String password) {
        try {
            // 1 將HEX輸出密文 轉為密文字節(jié)數(shù)組
            byte[] cipherTextBytes = hex2byte(cipherText);

            // 2 將密文字節(jié)數(shù)組進行解密 得到明文字節(jié)數(shù)組
            byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));

            // 3 根據(jù) CHARACTER 轉碼,返回明文字符串
            return new String(clearTextBytes, CHARACTER);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解密錯誤返回null
        return null;
    }

    /*字節(jié)數(shù)組轉成16進制字符串  */
    public static String byte2hex(byte[] bytes) { // 一個字節(jié)的數(shù),
        StringBuffer sb = new StringBuffer(bytes.length * 2);
        String tmp = "";
        for (int n = 0; n < bytes.length; n++) {
            // 整數(shù)轉成十六進制表示
            tmp = (java.lang.Integer.toHexString(bytes[n] & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); // 轉成大寫
    }

    /*將hex字符串轉換成字節(jié)數(shù)組 */
    private static byte[] hex2byte(String str) {
        if (str == null || str.length() < 2) {
            return new byte[0];
        }
        str = str.toLowerCase();
        int l = str.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            String tmp = str.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }

}

參考鏈接:AES模式和填充
【JAVA】AES加密 簡單實現(xiàn) AES-128/ECB/PKCS5Padding

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容