1 package unit; 2 import javax.crypto.Cipher; 3 import javax.crypto.spec.IvParameterSpec; 4 import javax.crypto.spec.SecretKeySpec; 5 6 import org.apache.commons.codec.binary.Base64; 7 /** 8 * AES/CBC/PKCS5Padding 对称加密 9 * @author jia 10 * 11 */ 12 public class AES_CBC { 13 14 private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; 15 /** 16 * 数据加密 17 * @param srcData 18 * @param key 19 * @param iv 20 * @return 21 */ 22 public static String encrypt(String srcData,byte[] key,byte[] iv) 23 { 24 SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); 25 Cipher cipher; 26 String encodeBase64String = null; 27 try { 28 cipher = Cipher.getInstance(ALGORITHM); 29 cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv)); 30 byte[] encData = cipher.doFinal(srcData.getBytes()); 31 encodeBase64String = Base64.encodeBase64String(encData); 32 } catch (Exception e) { 33 e.printStackTrace(); 34 } 35 return encodeBase64String; 36 } 37 38 /** 39 * 数据解密 40 * @param encDataStr 41 * @param key 42 * @param iv 43 * @return 44 */ 45 public static String decrypt(String encDataStr,byte[] key,byte[] iv) 46 { 47 byte[] encData = Base64.decodeBase64(encDataStr); 48 SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); 49 Cipher cipher; 50 byte[] decbbdt = null; 51 try { 52 cipher = Cipher.getInstance(ALGORITHM); 53 cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv)); 54 decbbdt = cipher.doFinal(encData); 55 } catch (Exception e) { 56 e.printStackTrace(); 57 } 58 return new String(decbbdt); 59 } 60 61 public static void main(String[] args) throws Exception { 62 String str = "fot4Ginq4iey7kLUUmA+dA=="; 63 byte[] s = Base64.decodeBase64(str); 64 String s2 = "12345678ilkljklkjv"; 65 String iv = "1234567890123456"; 66 System.out.println("加密前: "+s2); 67 String encrypt = AES_CBC.encrypt(s2, s, iv.getBytes()); 68 System.out.println("加密后: "+new String(encrypt)); 69 String decrypt = AES_CBC.decrypt(encrypt, s, iv.getBytes()); 70 System.out.println("解密后: "+decrypt); 71 } 72 }
时间: 2024-11-03 05:26:31