Java通过使用向量 iv 实现AES算法,CBC模式

public class AESIV {

    private final static String key = "nLnE4JFFbF6eAzjF";
    private final static String iv = "EJ9iIPhzB4I5UDfv";

    public static void main(String[] args) throws Exception {

         String enStr = Encrypt("123213122",key,iv);
         System.out.println("加密的字符串:"+enStr);
         String deStr = Decrypt(enStr,key,iv);
         System.out.println("解密的字符串:"+deStr);
    }

    

    //加密
    private static String Encrypt(String sstr,String skey,String siv) throws Exception {
        if (skey==null){
            log.info("key is null");
            return null;
        }
        if (skey.length()!=16){
            log.info("key is not 16 of length");
        }
        byte[] keyByte = skey.getBytes("utf-8");
        SecretKeySpec keySpec = new SecretKeySpec(keyByte,"AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//算法/模式/补码方式
        byte[] ivByte = siv.getBytes("utf-8");
        IvParameterSpec iv = new IvParameterSpec(ivByte);   //使用CBC模式,需要一个向量iv,可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE,keySpec,iv);
        byte[] encrype = cipher.doFinal(sstr.getBytes());
        return Base64.getEncoder().encodeToString(encrype);      //此处使用BASE64做转码功能,同时能起到2次加密的作用。
    }
    
    //解密
    private static String Decrypt(String sstr,String skey,String siv) throws Exception {
        try {
                if (skey==null){
                    log.info("key is null");
                    return null;
                }
                if (skey.length()!=16){
                    log.info("key is not 16 of length");
                }
                byte[] keyByte = skey.getBytes("utf-8");
                SecretKeySpec keySpec = new SecretKeySpec(keyByte,"AES");
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//算法/模式/补码方式
                IvParameterSpec iv = new IvParameterSpec(siv.getBytes());   //使用CBC模式,需要一个向量iv,可增加加密算法的强度
                cipher.init(Cipher.DECRYPT_MODE,keySpec,iv);
                byte[] encrype = Base64.getDecoder().decode(sstr);

                byte[] origin = cipher.doFinal(encrype);
                String str = new String(origin);
                return str;

            }catch (Exception e){
                return null;
        }
        
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值