星空网 > 软件开发 > Java

自写AES加密解密工具类

此类主要用于加密与解密,采用128位ECB模式,PKCS5Padding填充补位。

可使用方法为加密返回二进制encryptBin(content, key)、加密返回十六进制encryptHex(content, key)、二进制内容解密decryptBin(content, key)、十六进制内容解密decryptHex(content, key)。

content是需要加密的字符串,key是密钥,随意一个字符串。

 1 package com.test; 2  3 import java.io.UnsupportedEncodingException; 4 import java.security.InvalidKeyException; 5 import java.security.NoSuchAlgorithmException; 6 import java.security.SecureRandom; 7  8 import javax.crypto.BadPaddingException; 9 import javax.crypto.Cipher; 10 import javax.crypto.IllegalBlockSizeException; 11 import javax.crypto.KeyGenerator; 12 import javax.crypto.NoSuchPaddingException; 13 import javax.crypto.SecretKey; 14 import javax.crypto.spec.SecretKeySpec; 15  16 import org.apache.commons.logging.Log; 17 import org.apache.commons.logging.LogFactory; 18  19 public class AESCode { 20    21   private static final String algorithm = "AES"; 22   private static final String transformation = "AES/ECB/PKCS5Padding"; 23   private static final String charset = "utf-8"; 24    25   private static final Log _log = LogFactory.getLog(AESCode.class); 26    27   /** 28    * 获取key 填充密匙 获取加密的密匙数据 29    *  30    * @paramString key 31    * @return byte[] enCodeFormat; 32    * @author panjianghong 2016-8-29 33    * */ 34   private static byte[] getEnCodeFormat(String key){ 35  36     try { 37       KeyGenerator kgen = KeyGenerator.getInstance("AES"); 38       kgen.init(128, new SecureRandom(key.getBytes())); 39       SecretKey secretKey = kgen.generateKey(); 40       byte[] enCodeFormat = secretKey.getEncoded(); 41       return enCodeFormat; 42     } catch (NoSuchAlgorithmException e) { 43       _log.error("获取密匙数据失败!"); 44     }  45     return null; 46   } 47    48    49    50   /** 51    * 获取加密数据的二进制字符串数据 52    *  53    * @param content 54    * @param enCodeFormat 55    * @return String  56    * @author panjianghong 2016-8-29 57    * */ 58   public static String encryptBin(String content, String key){ 59      60     try { 61       byte[] byteConten = encrypt(content, key); 62       return byte2BinString(byteConten); 63     } catch (Exception e) { 64       _log.error("获取二进制加密数据失败!"); 65     } 66     return null; 67   } 68    69    70    71   /** 72    * 获取加密数据的十六进制字符串数据 73    *  74    * @param content 75    * @param enCodeFormat 76    * @return String  77    * @author panjianghong 2016-8-29 78    * */ 79   public static String encryptHex(String content, String key){ 80      81     try { 82       byte[] byteConten = encrypt(content, key); 83       return byte2HexString(byteConten); 84     } catch (Exception e) { 85       _log.error("获取十六进制加密数据失败!"); 86     } 87     return null; 88   } 89    90  91   /** 92    * 获取文件的加密数据 93    * 返回加密数据的字节数组 byte[]  94    *  95    * @param content 96    * @param enCodeFormat 97    * @return byte[] byteResoult  98    * @author panjianghong 2016-8-29 99    * */100   private static byte[] encrypt(String content, String key){101     102     try {103       SecretKeySpec secretyKey = new SecretKeySpec(getEnCodeFormat(key), algorithm);104       Cipher cipher = Cipher.getInstance(transformation);105       byte[] byteContent = content.getBytes(charset);106       cipher.init(Cipher.ENCRYPT_MODE, secretyKey);107       byte[] byteResoult = cipher.doFinal(byteContent);108       return byteResoult;109     } catch (InvalidKeyException e) {110       _log.error("获取加密数据的字节数组失败!");111     } catch (NoSuchAlgorithmException e) {112       _log.error("获取加密数据的字节数组失败!");113     } catch (NoSuchPaddingException e) {114       _log.error("获取加密数据的字节数组失败!");115     } catch (UnsupportedEncodingException e) {116       _log.error("获取加密数据的字节数组失败!");117     } catch (IllegalBlockSizeException e) {118       _log.error("获取加密数据的字节数组失败!");119     } catch (BadPaddingException e) {120       _log.error("获取加密数据的字节数组失败!");121     }122     123     return null;124   }125   126   /**127    * 以二进制字符串数据进行解密128    * 129    * @param content130    * @param enCodeFormat131    * @return String132    * @author panjianghong 2016-8-29133    * */134   135   public static String decryptBin(String binContent, String key){136     137     try {138       SecretKeySpec secretyKey = new SecretKeySpec(getEnCodeFormat(key), algorithm);139       Cipher cipher = Cipher.getInstance(transformation);140       cipher.init(Cipher.DECRYPT_MODE, secretyKey);141       byte[] byteResoult = cipher.doFinal(binString2Byte(binContent));142       try {143         return new String(byteResoult,"utf-8");144       } catch (UnsupportedEncodingException e) {145         _log.error("解密二进制数据失败!");146         return null;147       }148     } catch (InvalidKeyException e) {149       _log.error("解密二进制数据失败!");150     } catch (NoSuchAlgorithmException e) {151       _log.error("解密二进制数据失败!");152     } catch (NoSuchPaddingException e) {153       _log.error("解密二进制数据失败!");154     } catch (IllegalBlockSizeException e) {155       _log.error("解密二进制数据失败!");156     } catch (BadPaddingException e) {157       _log.error("解密二进制数据失败!");158     }159     160     return null;161   }162   163   /**164    * 以十六进制字符串数据进行解密165    * 166    * @param content167    * @param enCodeFormat168    * @return String169    * @author panjianghong 2016-8-29170    * */171   public static String decryptHex(String binContent, String key){172     173     try {174       SecretKeySpec secretyKey = new SecretKeySpec(getEnCodeFormat(key), algorithm);175       Cipher cipher = Cipher.getInstance(transformation);176       cipher.init(Cipher.DECRYPT_MODE, secretyKey);177       byte[] byteResoult = cipher.doFinal(hexString2Byte(binContent));178       try {179         return new String(byteResoult,"utf-8");180       } catch (UnsupportedEncodingException e) {181         _log.error("解密十六进制数据失败!");182         return null;183       }184     } catch (InvalidKeyException e) {185       _log.error("解密十六进制数据失败!");186     } catch (NoSuchAlgorithmException e) {187       _log.error("解密十六进制数据失败!");188     } catch (NoSuchPaddingException e) {189       _log.error("解密十六进制数据失败!");190     } catch (IllegalBlockSizeException e) {191       _log.error("解密十六进制数据失败!");192     } catch (BadPaddingException e) {193       _log.error("解密十六进制数据失败!");194     }195     196     return null;197   }198   199   200   201   202   /**203    * 字节数组转化成二进制数204    * @param content205    * @return string206    * @author panjianghong 2016-8-29207    * */208   private static String byte2BinString(byte[] content){209     if(null == content){210       _log.error("需要转换的参数为空!");211       return null;212     }213     214     return hexString2BinString(byte2HexString(content));215   }  216   217   /**218    * 字节数组转化成十六进制数的小写形式219    * @param content220    * @return string221    * @author panjianghong 2016-8-29222    * */223   private static String byte2HexString(byte[] content){224     if(null == content){225       _log.error("需要转换的参数为空!");226       return null;227     }228     229     StringBuffer sb = new StringBuffer();230     for (int i = 0; i < content.length; i++) {231       String hex = Integer.toHexString(content[i] & 0xFF); 232       if (hex.length() == 1) {233         hex = '0' + hex;234       }235       sb.append(hex.toLowerCase());236     }237     238     return sb.toString();239   }240   241   /**242    * 十六进制数转化成二进制数243    * @param content244    * @return string245    * @author panjianghong 2016-8-29246    * */247   private static String hexString2BinString(String content){248     249     if (null == content || content.length() % 2 != 0) {250       _log.error("需要转换的参数为空或者参数长度不是2的倍数!");251       return null; 252     }253       254     StringBuffer bString = new StringBuffer();255     StringBuffer tmp = new StringBuffer(); 256     for (int i = 0; i < content.length(); i++) 257     { 258       tmp.append("0000").append(Integer.toBinaryString(Integer.parseInt(content.substring(i, i + 1), 16))); 259       bString.append(tmp.toString().substring(tmp.toString().length() - 4)); 260       tmp.delete(0, tmp.toString().length());261     } 262     return bString.toString(); 263   }264   /**265    * 二进制数转化成十六进制数266    * @param content267    * @return string268    * @author panjianghong 2016-8-29269    * */270   private static String BinString2hexString(String content){271     272     if (null == content || content.equals("") || content.length() % 8 != 0){273       _log.error("需要转换的参数为空或者参数长度不是8的倍数!");274       return null; 275     }276       277     StringBuffer tmp = new StringBuffer(); 278     int iTmp = 0; 279     for (int i = 0; i < content.length(); i += 4) 280     { 281       iTmp = 0; 282       for (int j = 0; j < 4; j++) 283       { 284         iTmp += Integer.parseInt(content.substring(i + j, i + j + 1)) << (4 - j - 1); 285       } 286       tmp.append(Integer.toHexString(iTmp)); 287     } 288     return tmp.toString();  289   }290     291   292   /**293    * 16进制数转化成字节数组294    * @param content295    * @return string296    * @author panjianghong 2016-8-29297    * */298   private static byte[] hexString2Byte(String content){299     if (content.length() < 1){300       _log.error("需要转换的参数为空或者参数长度<1!");301       return null;302      }303         304     byte[] byteRresult = new byte[content.length() / 2];305     for (int i = 0; i < content.length() / 2; i++) {306       int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);307       int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);308       byteRresult[i] = (byte) (high * 16 + low);309     }310     return byteRresult;311   }312   313   /**314    * 二进制数转化成字节数组315    * @param content316    * @return string317    * @author panjianghong 2016-8-29318    * */319   private static byte[] binString2Byte(String content){320     if (content.length() < 1){321       _log.error("需要转换的参数为空或者参数长度<1!");322       return null;323      }324         325     return hexString2Byte(BinString2hexString(content));326   }327   328 }

 




原标题:自写AES加密解密工具类

关键词:加密

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流