1 package encrypt;
 2 
 3 import java.security.Key;
 4 import java.security.SecureRandom;
 5 import java.util.Base64;
 6 import java.util.Base64.Decoder;
 7 import java.util.Base64.Encoder;
 8 
 9 import javax.crypto.Cipher;
10 import javax.crypto.KeyGenerator;
11 
12 public class DESUtil {
13     private static Key key;
14     private static String KEY_STR="myKey";//密钥
15     static{
16         try {
17             KeyGenerator generator = KeyGenerator.getInstance("DES");
18             generator.init(new SecureRandom(KEY_STR.getBytes()));
19             key = generator.generateKey();
20             generator=null;
21         } catch (Exception e) {
22             
23         }
24     }
25     
26     public static String getEncryptString(String str){
27         Encoder base64Encoder = Base64.getEncoder();
28         try {
29             byte[] strBytes = str.getBytes("UTF-8");
30             Cipher cipher = Cipher.getInstance("DES");
31             cipher.init(Cipher.ENCRYPT_MODE, key);
32             byte[] encryptStrBytes = cipher.doFinal(strBytes);
33             return base64Encoder.encodeToString(encryptStrBytes);
34         } catch (Exception e) {
35             e.printStackTrace();
36         }
37         return null; 
38     }
39     
40     public static String getDecryptString(String str){
41         Decoder base64Decoder = Base64.getDecoder();
42         try {
43             byte[] strBytes = base64Decoder.decode(str);
44             Cipher cipher = Cipher.getInstance("DES");
45             cipher.init(cipher.DECRYPT_MODE, key);
46             byte[] decryptStrBytes = cipher.doFinal(strBytes);
47             return new String(decryptStrBytes,"UTF-8");
48         } catch (Exception e) {
49         }
50         return null;
51         
52     }
53     public static void main(String[] args) {
54         System.out.println(DESUtil.getEncryptString("147258"));
55         System.out.println(DESUtil.getDecryptString("VUhJSh5OPvI="));
56     }
57 }

https://www.cnblogs.com/wulm/p/6907197.html

 

posted on 2018-04-30 16:39  取个名字咋这难  阅读(266)  评论(0编辑  收藏  举报