码迷,mamicode.com
首页 > 其他好文 > 详细

DES加解密

时间:2018-04-30 17:56:02      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:new   vax   rate   ace   tac   style   code   except   turn   

 

 

 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 }

 

DES加解密

标签:new   vax   rate   ace   tac   style   code   except   turn   

原文地址:https://www.cnblogs.com/-1007813544/p/8973956.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!