AES加密時遇到的坑(windows和linux下加密結果會多出\n等)

 

AES加密的正確姿勢如下(已驗證,沒問題):
import com.ucar.supergw.common.exception.SupergwException;
import com.ucar.supergw.common.exception.code.SystemErrorCode;
import com.ucar.supergw.common.exception.util.AssertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {
    /** 日誌記錄器 */
    private static final Logger LOGGER = LoggerFactory.getLogger(AESUtil.class);

    /**
     *
     * @param sSrc 明文字符串
     * @param keyStr 加密祕鑰
     * @param ivStr 加密向量
     * @param charset 編碼
     * @return
     */
    public static String encrypt(String sSrc, String keyStr, String ivStr, String charset) {
        AssertUtil.isNotBlank(sSrc, SystemErrorCode.ILLEGAL_PARAMETER, "加密字符串爲空");
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(keyStr.getBytes(), "AES");
            // "算法/模式/補碼方式"
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

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

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

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

            String str = new BASE64Encoder().encode(encrypted);
            //注意:linux環境下加密時,會自動補\r \n到加密數據裏面
            //str = str.replaceAll("\r\n", "");
            //str = str.replaceAll("\n", "");
            str = str.replaceAll(System.getProperty("line.separator"), "");
            return str;
        } catch (Exception e) {
            LOGGER.error("AESUtil 加密失敗",e);
            throw new SupergwException(SystemErrorCode.ENCRYPT_ERROR, "加密失敗", e);
        }
    }

    /**
     * AES 解密
     *
     * @param sSrc 密文字符串
     * @param sKey 加密祕鑰
     * @param ivStr 加密向量
     * @param charset 編碼
     * @return
     */
    public static String decrypt(String sSrc, String sKey, String ivStr, String charset) {
        AssertUtil.isNotBlank(sSrc, SystemErrorCode.ILLEGAL_PARAMETER, "解密字符串爲空");
        try {
            byte[] raw = sKey.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, charset);
            //originalString = originalString.replaceAll("\r\n", "");
            //originalString = originalString.replaceAll("\n", "");
            originalString = originalString.replaceAll(System.getProperty("line.separator"), "");
            return originalString;
        } catch (Exception ex) {
            LOGGER.error("AESUtil 解密失敗",ex);
            throw new SupergwException(SystemErrorCode.DECRYPT_ERROR, "解密失敗", ex);
        }
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章