AES/CBC/PKCS5Padding对称加密

Posted 林**

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AES/CBC/PKCS5Padding对称加密相关的知识,希望对你有一定的参考价值。

 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 }

 

以上是关于AES/CBC/PKCS5Padding对称加密的主要内容,如果未能解决你的问题,请参考以下文章

AES/CBC/PKCS5Padding 与 AES/CBC/PKCS7Padding 与 256 密钥大小性能 java

nodejs中aes-128-cbc加密和解密

AES加密解密在JAVA和ANDROID下互通

Java中的AES加解密

AES/CBC/PKCS5 填充 |替代 PHP OpenSSL 中的 mcrypt_get_block_size()

区块链概念解读:非对称加密