1 package unit; 2 3 import javax.crypto.Cipher; 4 import javax.crypto.spec.SecretKeySpec; 5 6 import org.apache.commons.codec.binary.Base64; 7 8 /** 9 * AES/ECB/NoPadding 加密 10 * @author jia 11 */ 12 public class AES_ECB { 13 private static String Padding = "AES/ECB/NoPadding"; 14 /** 15 * 数据加密 16 * @param data 17 * @return 18 */ 19 public static byte[] encrypt(byte[] data, byte[] key){ 20 byte[] original = null; 21 try { 22 SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); 23 Cipher cipher = Cipher.getInstance(Padding); 24 cipher.init(Cipher.ENCRYPT_MODE, skeySpec); 25 original = cipher.doFinal(data); 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } 29 return original; 30 } 31 32 /** 33 * 数据解密 34 * @param encData 35 * @return 36 */ 37 public static String decrypt(String encData, String key) { 38 byte[] decodeBase64 = Base64.decodeBase64(encData); 39 byte[] original = null; 40 try { 41 SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES"); 42 Cipher cipher = Cipher.getInstance(Padding); 43 cipher.init(Cipher.DECRYPT_MODE, skeySpec); 44 original = cipher.doFinal(decodeBase64); 45 } catch (Exception e) { 46 e.printStackTrace(); 47 } 48 return new String(original).trim(); 49 } 50 51 public static void main(String[] args) throws Exception { 52 // String str = "20171017095514800000000000000000"; 53 // String key = "f5663bc2165b9b50"; 54 // byte[] encrypt_data = encrypt(str.getBytes(), key.getBytes()); 55 // String s = decrypt(encrypt_data, key); 56 // System.out.println("加密前: : "+str); 57 // System.out.println("密文: : "+encrypt_data); 58 // System.out.println("解密后: "+s); 59 } 60 }