AES加密

   常见的加密方法有MD5、RSA、AES,今天我们来说说AES加密,没啥好说的,直接给大家上demo。

 1 package com.ecshop.common.util;
 2 
 3 
 4 import sun.misc.BASE64Decoder;
 5 import sun.misc.BASE64Encoder;
 6 
 7 import javax.crypto.Cipher;
 8 import javax.crypto.spec.IvParameterSpec;
 9 import javax.crypto.spec.SecretKeySpec;
10 
11 
12 public class AESUtil {
13     //算法
14     private static final String ALGORITHM  = "AES";
15     //默认的加密算法
16     private static final String CIPHER_ALGORITHM  = "AES/CBC/PKCS5Padding";
17     // 编码
18     private static final String ENCODING = "UTF-8";
19     // 密匙
20     private static final String KEY = "a70648d869329dab";
21     // 偏移量
22     private static final String OFFSET = "0102030405060708";
23 
24     /**
25      * AES加密
26      * @param data
27      * @return
28      * @throws Exception
29      */
30     public static String encrypt(String data) throws Exception {
31         // 初始化cipher
32         Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
33         //转化成JAVA的密钥格式
34         SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM);
35         //使用CBC模式,需要一个向量iv,可增加加密算法的强度
36         IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());
37         cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
38         byte[] encrypted = cipher.doFinal(data.getBytes(ENCODING));
39         //此处使用BASE64做转码。
40         String result = new BASE64Encoder().encode(encrypted);
41         return result;
42     }
43 
44     /**
45      * AES解密
46      * @param data
47      * @return
48      * @throws Exception
49      */
50     public static String decrypt(String data) throws Exception {
51         Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
52         SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM);
53         //使用CBC模式,需要一个向量iv,可增加加密算法的强度
54         IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());
55         cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
56         byte[] buffer = new BASE64Decoder().decodeBuffer(data);
57         byte[] encrypted = cipher.doFinal(buffer);
58         //此处使用BASE64做转码。
59         String result = new String(encrypted, ENCODING);
60         return result;
61     }
62 
63     public static void main(String[] args) {
64         String s1 = "1122";
65         String str = "";
66         try {
67              str = AESUtil.encrypt(s1);
68             System.out.println("111111:"+str);
69         } catch (Exception e) {
70             e.printStackTrace();
71         }
72 
73         String result = "";
74         try {
75             result = AESUtil.decrypt(str);
76             System.out.println("222222:"+result);
77         } catch (Exception e) {
78             e.printStackTrace();
79         }
80 
81     }
82 }

 

posted @ 2018-09-11 11:56  小柴胡颗粒  阅读(3360)  评论(0编辑  收藏  举报