AES 加密 - s9797456/MyCommonCodeSnippets GitHub Wiki

package com.xinle.car.admin.common.util;

import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64;

/**

  • AES 128位加密,加密模式采用CBC,填充模式采用PKCS5Padding方式 */ public class AESUtil {

    /**

    • 加密

    • @param sSrc 加密源

    • @param sKey 加密KEY

    • @return String

    • @throws Exception Exception */ public static String Encrypt(String sSrc, String sKey) { if (sKey == null) { throw new RuntimeException("Key为空null"); } // 判断Key是否为16位 if (sKey.length() != 16) { throw new RuntimeException("Key长度不是16位"); } String result = null; try { byte[] raw = sKey.getBytes("UTF-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher; byte[] encrypted = null; cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // "算法/模式/补码方式" IvParameterSpec iv = new IvParameterSpec(sKey.getBytes("UTF-8"));// 使用CBC模式,需要一个向量iv,可增加加密算法的强度 // "算法/模式/补码方式" cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); encrypted = cipher.doFinal(sSrc.getBytes("UTF-8")); result = Base64.getEncoder().encodeToString(encrypted);// 此处使用BASE64做转码功能,同时能起到2次加密的作用。 result = result.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", ""); } catch (Exception e) { e.printStackTrace(); }

      return result; }

    /**

    • 加密

    • @param sSrc 加密源

    • @param sKey 加密KEY

    • @return String

    • @throws Exception Exception */ public static String Encrypt(String sSrc, String sKey, String sIv) { if (sKey == null) { throw new RuntimeException("Key为空null"); } // 判断Key是否为16位 if (sKey.length() != 16) { throw new RuntimeException("Key长度不是16位"); } String result = null; try { byte[] raw = sKey.getBytes("UTF-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher; byte[] encrypted = null; cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // "算法/模式/补码方式" IvParameterSpec iv = new IvParameterSpec(sIv.getBytes("UTF-8"));// 使用CBC模式,需要一个向量iv,可增加加密算法的强度 // "算法/模式/补码方式" cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); encrypted = cipher.doFinal(sSrc.getBytes("UTF-8")); result = Base64.getEncoder().encodeToString(encrypted);// 此处使用BASE64做转码功能,同时能起到2次加密的作用。 result = result.replaceAll("\r\n", ""); result = result.replaceAll("\n", ""); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); }

      return result; }

    /**

    • 解密

    • @param sSrc 解密源

    • @param sKey 解密KEY

    • @return String

    • @throws Exception Exception */ public static String Decrypt(String sSrc, String sKey) { // 判断Key是否正确 if (sKey == null) { throw new RuntimeException("Key为空null"); } // 判断Key是否为16位 if (sKey.length() != 16) { throw new RuntimeException("Key长度不是16位"); }

      String originalString = null; try { byte[] raw = sKey.getBytes("UTF-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(sKey.getBytes("UTF-8")); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 = Base64.getDecoder().decode(sSrc);// 先用base64解密 byte[] original = cipher.doFinal(encrypted1); originalString = new String(original, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return originalString; }

    /**

    • 解密

    • @param sSrc 解密源

    • @param sKey 解密KEY

    • @return String

    • @throws Exception Exception */ public static String Decrypt(String sSrc, String sKey, String sIv) { // 判断Key是否正确 if (sKey == null) { throw new RuntimeException("Key为空null"); } // 判断Key是否为16位 if (sKey.length() != 16) { throw new RuntimeException("Key长度不是16位"); }

      String originalString = null; try { byte[] raw = sKey.getBytes("UTF-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(sIv.getBytes("UTF-8")); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 = Base64.getDecoder().decode(sSrc);// 先用base64解密 byte[] original = cipher.doFinal(encrypted1); originalString = new String(original, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return originalString; }

    /**

    • 将二进制转换成16进制 / public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /*
    • 将16进制转换为二进制 / public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length()/2]; for (int i = 0;i< hexStr.length()/2; i++) { int high = Integer.parseInt(hexStr.substring(i2, i2+1), 16); int low = Integer.parseInt(hexStr.substring(i2+1, i*2+2), 16); result[i] = (byte) (high * 16 + low); } return result; }

    public static void main(String[] args) { /* * 加密用的Key 可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定 此处使用AES-128-CBC加密模式,key需要为16位。 */ String cKey = "1234567890abcdef"; // 需要加密的字串 String cSrc = "{"total":1,"stationStatusInfo":{"operationID":"123456789","stationID":"111111111111111","connectorStatusInfos":{"connectorID":1,"equipmentID":"10000000000000000000001","status":4,"currentA":0,"currentB":0,"currentC":0,"voltageA":0,"voltageB":0,"voltageC":0,"soc":10,}}}"; System.out.println(cSrc); // 加密 long lStart = System.currentTimeMillis(); String enString = AESUtil.Encrypt(cSrc, cKey); System.out.println("加密后的字串是:" + enString);

     long lUseTime = System.currentTimeMillis() - lStart;
     System.out.println("加密耗时:" + lUseTime + "毫秒");
     // 解密
     lStart = System.currentTimeMillis();
     String DeString = AESUtil.Decrypt(enString, cKey);
     System.out.println("解密后的字串是:" + DeString);
     lUseTime = System.currentTimeMillis() - lStart;
     System.out.println("解密耗时:" + lUseTime + "毫秒");
    
     String data = "d3lXhm9I0vVP1ke9UKKIW3eqgCs00Boyvi2NTFIQ4mwMjqNLYDYlJ1eVZUPXtIvg";
     String data2 = AESUtil.Decrypt(data, cKey);
     System.out.println("解密后的字串是:" + data2);
     System.out.println("解密耗时:" + lUseTime + "毫秒");
    
     String iv = "accbvlpokVaP6oJv";
     System.out.println(iv.length());
    

    } }