AES加密

 1 package com.dl.network_flow.utils;
 2 
 3 import javax.crypto.Cipher; 
 4 import javax.crypto.spec.IvParameterSpec;
 5 import javax.crypto.spec.SecretKeySpec;
 6 
 7 import sun.misc.BASE64Decoder;
 8 
 9 public class AES256Encryption {
10 
11 //    private static String key = "H5gOs1ZshKZ6WikN";
12 //    private static String iv = "8888159601152533";
13     
14     private static final String key = PropertyUtils.getValue("secreKey");
15     private static final String iv = PropertyUtils.getValue("vector");
16     
17     private static final String KEY_ALGORITHM = "AES";
18     private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
19                                                  
20     /**
21      * 加密 encrypt
22      * @time 2016年2月25日下午4:57:15
23      * @packageName com.dl.network_flow.utils
24      * @return
25      * @throws Exception
26      */
27     public static byte[] encrypt(String data) throws Exception {
28         try {
29 
30             Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
31             int blockSize = cipher.getBlockSize();
32 
33             byte[] dataBytes = data.getBytes();
34             int plaintextLength = dataBytes.length;
35             if (plaintextLength % blockSize != 0) {
36                 plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
37             }
38             byte[] plaintext = new byte[plaintextLength];
39             System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
40 
41             SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM);
42             IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
43 
44             cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
45             byte[] encrypted = cipher.doFinal(plaintext);
46 
47             return encrypted;
48 
49         } catch (Exception e) {
50             e.printStackTrace();
51             return null;
52         }
53     }
54     
55     
56     public static String encodeBytes(byte[] bytes){
57         StringBuffer sbfBuffer = new StringBuffer();
58         for (int i = 0; i < bytes.length; i++) {
59             sbfBuffer.append((char)(((bytes[i]>>4)&0xf)+((int)'a')));
60             sbfBuffer.append((char)(((bytes[i])&0xf)+((int)'a')));
61         }
62         return sbfBuffer.toString();
63     }
64     
65     
66 
67     /**
68      * 解密 desEncrypt
69      * 
70      * @time 2016年2月25日下午4:57:20
71      * @packageName com.dl.network_flow.utils
72      * @param data
73      * @return
74      * @throws Exception
75      */
76     public static String desEncrypt(String data) throws Exception {
77         try {
78             byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);
79 
80             Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
81             SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM);
82             IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
83 
84             cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
85 
86             byte[] original = cipher.doFinal(encrypted1);
87             String originalString = new String(original);
88             System.out.println(originalString.length());
89             return originalString;
90         } catch (Exception e) {
91             e.printStackTrace();
92             return null;
93         }
94     }
95 }
  1 package com.dl.network_flow.utils;
  2 
  3 import java.io.UnsupportedEncodingException;
  4 import java.security.InvalidKeyException;
  5 import java.security.MessageDigest;
  6 import java.security.NoSuchAlgorithmException;
  7 import java.security.SecureRandom;
  8 import javax.crypto.BadPaddingException;
  9 import javax.crypto.Cipher;
 10 import javax.crypto.IllegalBlockSizeException;
 11 import javax.crypto.KeyGenerator;
 12 import javax.crypto.NoSuchPaddingException;
 13 import javax.crypto.SecretKey;
 14 import javax.crypto.spec.SecretKeySpec;
 15  
 16 public class DecriptTest {
 17  
 18     public static String SHA1(String decript) {
 19         try {
 20             MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
 21             digest.update(decript.getBytes());
 22             byte messageDigest[] = digest.digest();
 23             // Create Hex String
 24             StringBuffer hexString = new StringBuffer();
 25             // 字节数组转换为 十六进制 数
 26             for (int i = 0; i < messageDigest.length; i++) {
 27                 String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
 28                 if (shaHex.length() < 2) {
 29                     hexString.append(0);
 30                 }
 31                 hexString.append(shaHex);
 32             }
 33             return hexString.toString();
 34  
 35         } catch (NoSuchAlgorithmException e) {
 36             e.printStackTrace();
 37         }
 38         return "";
 39     }
 40  
 41     public static String SHA(String decript) {
 42         try {
 43             MessageDigest digest = java.security.MessageDigest
 44                     .getInstance("SHA");
 45             digest.update(decript.getBytes());
 46             byte messageDigest[] = digest.digest();
 47             // Create Hex String
 48             StringBuffer hexString = new StringBuffer();
 49             // 字节数组转换为 十六进制 数
 50             for (int i = 0; i < messageDigest.length; i++) {
 51                 String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
 52                 if (shaHex.length() < 2) {
 53                     hexString.append(0);
 54                 }
 55                 hexString.append(shaHex);
 56             }
 57             return hexString.toString();
 58  
 59         } catch (NoSuchAlgorithmException e) {
 60             e.printStackTrace();
 61         }
 62         return "";
 63     }
 64  
 65     public static String MD5(String input) {
 66         try {
 67             // 获得MD5摘要算法的 MessageDigest 对象
 68             MessageDigest mdInst = MessageDigest.getInstance("MD5");
 69             // 使用指定的字节更新摘要
 70             mdInst.update(input.getBytes());
 71             // 获得密文
 72             byte[] md = mdInst.digest();
 73             // 把密文转换成十六进制的字符串形式
 74             StringBuffer hexString = new StringBuffer();
 75             // 字节数组转换为 十六进制 数
 76             for (int i = 0; i < md.length; i++) {
 77                 String shaHex = Integer.toHexString(md[i] & 0xFF);
 78                 if (shaHex.length() < 2) {
 79                     hexString.append(0);
 80                 }
 81                 hexString.append(shaHex);
 82             }
 83             return hexString.toString();
 84         } catch (NoSuchAlgorithmException e) {
 85             e.printStackTrace();
 86         }
 87         return "";
 88     }
 89  
 90     /**
 91      * 加密
 92      *
 93      * @param content
 94      *            需要加密的内容
 95      * @param password
 96      *            加密密码
 97      * @return
 98      */
 99     public static byte[] encryptAES(String content, String password) {
100         try {
101             KeyGenerator kgen = KeyGenerator.getInstance("AES");
102             kgen.init(128, new SecureRandom(password.getBytes()));
103             SecretKey secretKey = kgen.generateKey();
104             byte[] enCodeFormat = secretKey.getEncoded();
105             SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
106             Cipher cipher = Cipher.getInstance("AES");// 创建密码器
107             byte[] byteContent = content.getBytes("utf-8");
108             cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
109             byte[] result = cipher.doFinal(byteContent);
110             return result; // 加密
111         } catch (NoSuchAlgorithmException e) {
112             e.printStackTrace();
113         } catch (NoSuchPaddingException e) {
114             e.printStackTrace();
115         } catch (InvalidKeyException e) {
116             e.printStackTrace();
117         } catch (UnsupportedEncodingException e) {
118             e.printStackTrace();
119         } catch (IllegalBlockSizeException e) {
120             e.printStackTrace();
121         } catch (BadPaddingException e) {
122             e.printStackTrace();
123         }
124         return null;
125     }
126  
127     /**
128      * 解密
129      *
130      * @param content
131      *            待解密内容
132      * @param password
133      *            解密密钥
134      * @return
135      */
136     public static byte[] decryptAES(byte[] content, String password) {
137         try {
138             KeyGenerator kgen = KeyGenerator.getInstance("AES");
139             kgen.init(128, new SecureRandom(password.getBytes()));
140             SecretKey secretKey = kgen.generateKey();
141             byte[] enCodeFormat = secretKey.getEncoded();
142             SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
143             Cipher cipher = Cipher.getInstance("AES");// 创建密码器
144             cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
145             byte[] result = cipher.doFinal(content);
146             return result; // 加密
147         } catch (NoSuchAlgorithmException e) {
148             e.printStackTrace();
149         } catch (NoSuchPaddingException e) {
150             e.printStackTrace();
151         } catch (InvalidKeyException e) {
152             e.printStackTrace();
153         } catch (IllegalBlockSizeException e) {
154             e.printStackTrace();
155         } catch (BadPaddingException e) {
156             e.printStackTrace();
157         }
158         return null;
159     }
160  
161     public static void main(String[] args) {
162         String str = MD5("siyanlvQ");
163         System.out.println(str);
164     }
165 }
 1 /*  strType  SHA-256  SHA-512  */
 2 private String SHA(final String strText, final String strType) {
 3         // 返回值
 4         String strResult = null;
 5 
 6         // 是否是有效字符串
 7         if (strText != null && strText.length() > 0) {
 8             try {
 9                 // SHA 加密开始
10                 // 创建加密对象 并傳入加密類型
11                 MessageDigest messageDigest = MessageDigest
12                         .getInstance(strType);
13                 // 传入要加密的字符串
14                 messageDigest.update(strText.getBytes());
15                 // 得到 byte 類型结果
16                 byte byteBuffer[] = messageDigest.digest();
17 
18                 // 將 byte 转换为 string
19                 StringBuffer strHexString = new StringBuffer();
20                 // 遍歷 byte buffer
21                 for (int i = 0; i < byteBuffer.length; i++) {
22                     String hex = Integer.toHexString(0xff & byteBuffer[i]);
23                     if (hex.length() == 1) {
24                         strHexString.append('0');
25                     }
26                     strHexString.append(hex);
27                 }
28                 // 得到返回結果
29                 strResult = strHexString.toString();
30             } catch (NoSuchAlgorithmException e) {
31                 System.out.println(e.getMessage());
32             }
33         }
34         return strResult;
35     }
原文地址:https://www.cnblogs.com/zfy0098/p/5306380.html