以前經常使用兩種加密算法:Base64和Md5,前者容易破解,後者不可逆。java
AES採用對稱加密方式,破解難度很是大,在可逆的基礎上,能很好的保證數據的安全性。算法
這裏介紹Java中實現AES加密算法的加密與解密實現:spring
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.springframework.util.Base64Utils; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class AesUtil { public static void main(String[] args) throws UnsupportedEncodingException { for (int i = 0; i < 10; i++) { String key = generateKey(); // 提早生成的一個key String ps = encode(key, "123"); System.out.println("加密: " + ps); String res = decode(key, ps); System.out.println("解密: " + res); } } /** * 生成key * @return */ public static String generateKey() { try { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(new SecureRandom()); SecretKey secretKey = keyGenerator.generateKey(); byte[] byteKey = secretKey.getEncoded(); return Hex.encodeHexString(byteKey); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } /** * AES加密 * @param thisKey * @param data * @return */ public static String encode(String thisKey, String data) { try { // 轉換KEY Key key = new SecretKeySpec(Hex.decodeHex(thisKey),"AES"); //System.out.println(thisKey); // 加密 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] result = cipher.doFinal(data.getBytes()); return Hex.encodeHexString(result); } catch (Exception e) { e.printStackTrace(); } return null; } /** * AES解密 * @param thisKey * @param data * @return */ public static String decode(String thisKey, String data) { try { // 轉換KEY Key key = new SecretKeySpec(Hex.decodeHex(thisKey),"AES"); // 解密 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] result = cipher.doFinal(Hex.decodeHex(data)); return new String(result); } catch (Exception e) { e.printStackTrace(); } return null; } }