DES加解密

Posted -1007813544

tags:

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

 

 

 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加解密的主要内容,如果未能解决你的问题,请参考以下文章

3DES加解密示例

一个java的DES加解密类转换成C#

求 js和PHP版的 DES加解密程序

实现与JS相同的Des加解密算法

LKT系列加密芯片DES加解密以及OpenSSL DES接口实现加解密

python笔记66 - DES/CBC/pkcs5padding加解密(pyDes)