zoukankan      html  css  js  c++  java
  • JAVA Aes加解密详解

    上篇随笔留了一个问题,两种加密结果不一样?

    其实是内部实现方式不一样,具体见注释

     1  /**
     2      * 提供密钥和向量进行加密
     3      *
     4      * @param sSrc
     5      * @param key
     6      * @param iv
     7      * @return
     8      * @throws Exception
     9      */
    10     public static String Encrypt(String sSrc, byte[] key, byte[] iv) throws Exception {
    11         SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");// 根据给定的字节数组构造一个密钥
    12         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/补码方式"
    13         IvParameterSpec _iv = new IvParameterSpec(iv);// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
    14         cipher.init(Cipher.ENCRYPT_MODE, skeySpec, _iv);//用密钥和一组算法参数初始化此 Cipher
    15         byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));//按单部分操作加密或解密数据,或者结束一个多部分操作。
    16         return Base64.encodeBase64String(encrypted);
    17     }
     1  /**
     2      * 加密
     3      * @param content
     4      * @param keyBytes
     5      * @param iv
     6      * @return
     7      * @throws Exception
     8      */
     9     public String AES_CBC_Encrypt(byte[] content, byte[] keyBytes, byte[] iv) throws Exception{
    10         try{
    11             KeyGenerator keyGenerator= KeyGenerator.getInstance("AES");//返回生成指定算法的秘密密钥的 KeyGenerator 对象
    12             keyGenerator.init(128, new SecureRandom(keyBytes) );//使用用户提供的随机源初始化此密钥生成器,使其具有确定的密钥大小
    13             SecretKey key=keyGenerator.generateKey();// 生成一个密钥。
    14             Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
    15             cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
    16             byte[] result=cipher.doFinal(content);
    17             return Base64.encodeBase64String(result);
    18         }catch (Exception e) {
    19             e.printStackTrace();
    20             throw e;
    21         }
    22     }
  • 相关阅读:
    js 字符串中提取ip地址
    echart lengend 选中事件
    反射与注解
    clientX、clientY、offsetLeft、offsetTop、offsetWidth、offsetHeight
    图片放大和缩小
    拖拽文字辅助线对齐
    文字随着鼠标移动而移动(文字拖拽移动)
    Java 数组转 List 的三种方式及使用场景
    【Docker(二)】Docker镜像、容器、仓库命令详解
    【Docker(一)】走进Docker的第一步
  • 原文地址:https://www.cnblogs.com/duanxianyouyang/p/6541610.html
Copyright © 2011-2022 走看看