天天看點

java

public class AESUtils {

    public static final String AES_GIV   = "ASwsqwerty1uDs";//定義16為偏移向量

    public static Log          logger    = LogFactory.getLog(AESUtils.class);

    /**

     * 加密

     * @param String sSrc需要加密的參數

     * @param String sKey密鑰16位長度的String

     * @return String 加密後的資料

     */

    public static String Encrypt(String sSrc, String sKey) throws Exception {

        if (sKey == null) {

            logger.warn("Key為空null");

            return null;

        }

        // 判斷Key是否為16位

        if (sKey.length() != 16) {

            logger.warn("Key長度不是16位");

        byte[] raw = sKey.getBytes();

        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/補碼方式"

        IvParameterSpec iv = new IvParameterSpec(AES_GIV.getBytes());// 使用CBC模式,需要一個向量iv,可增加加密算法的強度

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

        byte[] encrypted = cipher.doFinal(sSrc.getBytes());

        return new BASE64Encoder().encode(encrypted);// 此處使用BASE64做轉碼功能,同時能起到2次加密的作用。

    }

     * 解密

     * @param String sSrc需要解密的參數

     * @return String 解密後的資料

    public static String Decrypt(String sSrc, String sKey) throws Exception {

        try {

            // 判斷Key是否正确

            if (sKey == null) {

                logger.warn("Key為空null");

                return null;

            }

            // 判斷Key是否為16位

            if (sKey.length() != 16) {

                logger.warn("Key長度不是16位");

            byte[] raw = sKey.getBytes("ASCII");

            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            IvParameterSpec iv = new IvParameterSpec(AES_GIV.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密

            try {

                byte[] original = cipher.doFinal(encrypted1);

                String originalString = new String(original);

                return originalString;

            } catch (Exception e) {

                logger.error("Decrypt error", e);

        } catch (Exception e) {

            logger.error("Decrypt error", e);

--------------------------測試--------------------

測試時傳密鑰和需要加解密的參數