AES加解密方法


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;

/**
 * @Author http://torey611.gitee.io/li-tao-feng/
 * @Email torey6061@qq.com
 * @Date 2021/10/24 22:10
 * @描述:
 */
public class AES {

    private static final Log log = LogFactory.getLog(AES.class);
    /**
     *
     * @author ngh
     * AES128 算法
     *
     * CBC 模式
     *
     * PKCS7Padding 填充模式
     *
     * CBC模式需要添加偏移量参数iv,必须16位
     * 密钥 sessionKey,必须16位
     *
     * 介于java 不支持PKCS7Padding,只支持PKCS5Padding 但是PKCS7Padding 和 PKCS5Padding 没有什么区别
     * 要实现在java端用PKCS7Padding填充,需要用到bouncycastle组件来实现
     */
    private final String sessionKey = "1c01cde95c8aad00";
    // 偏移量 16位
    private final String iv = "1c01cde95c8ab100";

    // 算法名称
    final String KEY_ALGORITHM = "AES";
    // 加解密算法/模式/填充方式
    final String algorithmStr = "AES/CBC/PKCS7Padding";
    // 加解密 密钥 16位

    byte[] ivByte;
    byte[] keybytes;
    private Key key;
    private Cipher cipher;
    boolean isInited = false;

    public void init() {
        // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
        keybytes = sessionKey.getBytes();
        ivByte = iv.getBytes();
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        key = new SecretKeySpec(keybytes, KEY_ALGORITHM);
        try {
            // 初始化cipher
            cipher = Cipher.getInstance(algorithmStr, "BC");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 加密方法
     *
     * @param content
     *            要加密的字符串
     *            加密密钥
     * @return
     */
    public String encrypt(String content) {
        byte[] encryptedText = null;
        byte[] contentByte = new byte[0];
        try {
            contentByte = content.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        init();
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivByte));
            encryptedText = cipher.doFinal(contentByte);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("加密错误:",e);
        }
        return new String(Hex.encode(encryptedText));
    }
    /**
     * 解密方法
     *
     * @param encryptedData
     *            要解密的字符串
     *            解密密钥
     * @return
     */
    public String decrypt(String encryptedData) {
        byte[] encryptedText = null;
        byte[] encryptedDataByte = Hex.decode(encryptedData);
        init();
        try {
            cipher.init(Cipher.DECRYPT_MODE, key, generateIV(ivByte));
            encryptedText = cipher.doFinal(encryptedDataByte);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("解密错误:"+encryptedData,e);
        }
        try {
            return new String(encryptedText,"utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("解密错误:"+encryptedData,e);
        }
        return null;
    }

    //生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }

    public static void main(String[] args) {
        AES aes = new AES();

        //加密字符串
        String content = "孟飞快跑";
        System.out.println("加密前的:" + content);
//        System.out.println("加密密钥:" + new String(keybytes));
        // 加密方法
        String enc = aes.encrypt(content);
        System.out.println("加密后的内容:" + enc);
//		enc ="5B48732975FAAF500735C70AC129443C";
        // 解密方法
        String dec = aes.decrypt("94bd5c15707c1cb97006f31b1cc254296fdb1b1d79cab24b6223997fa4e6173dd2615f52c4c2e866a4f5a20bcb24212ec26eded1e21366944781e2dca8001751fe4caec18f779bde76233a877dc52cb62e3af91852c9ea6a45f6f1a97c90ccc13457cabdb0c4f5626ad960dc78d4d0c24b27a8729b2aaa69dfa81981ccf693b2f86f98680467460644801b876402a77e270fb6dd7f6ae1430a2b6490d840933bbaf5ce5dc0bd8b38b9c55a7f46dca20ed272f95f897ef4127d4306acf0c89afcdffa3591efa2eca2c16779b8b91bf9d618c1ace1cf27dba5b41fddcec269cbad575639b5f070c4882586b509d8302dc0c8fd9d67ccb30a56a818e52e19c42f8b7914e555844ddfdd8c428629e911a17a66589d7979658d773adb40c37ee95e65ffbd3ef9721efd0275ad23cc73745d018057cab9f26ebbad92978461f8f5e1442bc848d47ebf095596bad0638880d53bfa4e4f22d28621f9e7af57c1c0bdabfdeba42df91233815f754fc5cba3e18547");
        System.out.println("解密后的内容:" + dec);
//		String key ="ztooaxcx~!@#$?";
//		String value ="{data:1351}";
//		System.out.println(DigestUtil.getMD5(value+key));
    }


    /**
     * 解密方法
     *
     * @param encryptedData
     *            要解密的字符串
     *            解密密钥
     * @return
     */
    public String decrypt2(String encryptedData, String session_key, String iv) {
        byte[] encrypted64 = Base64.decodeBase64(encryptedData);
        byte[] key64 = Base64.decodeBase64(session_key);
        byte[] iv64 = Base64.decodeBase64(iv);
        byte[] encryptedText = null;
        try {
            Security.addProvider(new BouncyCastleProvider());
            KeyGenerator.getInstance(KEY_ALGORITHM).init(128);
            Key key = new SecretKeySpec(key64, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(algorithmStr);
            cipher.init(Cipher.DECRYPT_MODE, key, generateIV(iv64));
            encryptedText = cipher.doFinal(encrypted64);
            return new String(encryptedText, "utf-8");
        } catch (Exception e) {
            log.error("解密微信手机号失败:" + encryptedData, e);
        }
        return null;
    }

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值