@File
2020-04-10T03:41:29.000000Z
字数 1829
阅读 138
骚操作
public class AES {/*** 模式 ECB/CBC*/private static String MODE = "ECB";/*** 算法*/private static String RIJNDAEL = "PKCS5Padding";/*** key 长度(不能改)*/private static int KEY_LENGTH = 16;/*** 加密* @param sSrc 需要加密字符串* @param sKey 秘钥* @return 加密的结果字符串* @throws Exception*/public static String encrypt(String sSrc, String sKey) throws Exception {if (sKey == null) {System.out.print("Key为空null");return null;}// 判断Key是否为16位if (sKey.length() != KEY_LENGTH) {sKey = resetKey(sKey);}byte[] raw = sKey.getBytes("utf-8");SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");//"算法/模式/补码方式"Cipher cipher = Cipher.getInstance("AES/"+MODE+"/"+RIJNDAEL);cipher.init(Cipher.ENCRYPT_MODE, skeySpec);byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));//此处使用BASE64做转码功能,同时能起到2次加密的作用。return new BASE64Encoder().encode(encrypted);}/*** 解密* @param sSrc 被加密的字符串* @param sKey 秘钥* @return 源字符串* @throws Exception*/public static String decrypt(String sSrc, String sKey) throws Exception {try {// 判断Key是否正确if (sKey == null) {System.out.print("Key为空null");return null;}// 判断Key是否为16位if (sKey.length() != KEY_LENGTH) {sKey = resetKey(sKey);}byte[] raw = sKey.getBytes("utf-8");SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");Cipher cipher = Cipher.getInstance("AES/"+MODE+"/"+RIJNDAEL);cipher.init(Cipher.DECRYPT_MODE, skeySpec);//先用base64解密byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);try {byte[] original = cipher.doFinal(encrypted1);String originalString = new String(original,"utf-8");return originalString;} catch (Exception e) {System.out.println(e.toString());return null;}} catch (Exception ex) {System.out.println(ex.toString());return null;}}/*** 秘钥补位和消位逻辑* @param key 秘钥* @return 16位长度的字符*/private static String resetKey(String key){String newKey;int len = key.length();// 多于16位if(len > KEY_LENGTH){newKey = key.substring(len-KEY_LENGTH);}// 小于16位else{char[] tmpArr = new char[KEY_LENGTH-len];Arrays.fill(tmpArr,'0');newKey = key + new String(tmpArr);}return newKey;}}