Aes加密算法

AESUtil是一个Java类,用于实现AES加密和解密功能,使用了AES-128-CBC模式,包含了一个固定的加密Key和偏移量(IV)。加密过程包括字节转换、CBC模式设置和Base64编码,解密过程则相反,首先Base64解码,然后进行AES解密。
摘要由CSDN通过智能技术生成
package com.xl.utils;

import com.alibaba.druid.util.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author hfx
 */
public class AESUtil {

    /**
     * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式,key需要为16位。
     */
    public static final String skey = "smkldospd121dass";

    /**
     * 加密偏移量
     */
    private static final String ivParameter = "1016449182184178";

    /**
     * 加密
     * @param encData
     * @return
     * @throws Exception
     */
    public static String Encrypt(String encData) throws Exception {

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = skey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        // 使用CBC模式,需要一个向量iv,可增加加密算法的强度
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
        // 此处使用BASE64做转码。
        return replace(new BASE64Encoder().encode(encrypted)) ;
    }


    /**
     * 解密
     * @param sSrc
     * @return
     */

    public  static String Decrypt(String sSrc ) {
        try {
            byte[] raw = skey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            // 先用base64解密
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }

    
    public static String replace(String str) {
        if (!StringUtils.isEmpty(str)) {
            return str.replaceAll("\r|\n", "");
        }
        return str;
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值