· 7 years ago · Mar 17, 2018, 06:40 AM
1/*
2 * DES encrypting/decrypting for text data
3 */
4
5
6import java.security.*;
7import javax.crypto.*;
8
9public class SimpleDESCryptoProvider {
10
11 public static final String seed = "AM6ROFFBABFAKILLEMALL";
12
13 public static String decrypt(String src)
14 {
15
16 try{
17 javax.crypto.spec.SecretKeySpec
18 key = new javax.crypto.spec.SecretKeySpec(getRawKey(), "DES");
19 Cipher ecipher = Cipher.getInstance("DES");
20 ecipher.init(Cipher.DECRYPT_MODE, key);
21
22 byte[] utf8 = toByte(src);
23
24 // Descrypt
25 byte[] dec= ecipher.doFinal(utf8);
26
27 return new String( dec );
28 }
29 catch(Exception exc )
30 {
31 try{
32 exc.printStackTrace();
33 }catch(Exception exc2){}
34
35 }
36 return src;
37
38 }
39
40 public static String encrypt(String src)
41 {
42 try{
43 javax.crypto.spec.SecretKeySpec
44 key = new javax.crypto.spec.SecretKeySpec(getRawKey(), "DES");
45 Cipher ecipher = Cipher.getInstance("DES");
46 ecipher.init(Cipher.ENCRYPT_MODE, key);
47
48 byte[] utf8 = src.getBytes("UTF8");
49
50 // Encrypt
51 byte[] enc = ecipher.doFinal(utf8);
52
53 return toHex(enc);
54 }
55 catch(Exception exc )
56 {
57 try{
58 exc.printStackTrace();
59 }catch(Exception exc2){}
60
61 }
62 return src;
63 }
64
65 private static byte[] getRawKey() throws Exception {
66 KeyGenerator kgen = KeyGenerator.getInstance("DES");
67 SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
68 sr.setSeed(seed.getBytes());
69 kgen.init(56, sr);
70 SecretKey skey = kgen.generateKey();
71 byte[] raw = skey.getEncoded();
72 return raw;
73 }
74
75 // Ñти методы иÑпользуютÑÑ Ð´Ð»Ñ ÐºÐ¾Ð½Ð²ÐµÑ€Ñ‚Ð°Ñ†Ð¸Ð¸ байтов в ASCII Ñимволы
76
77 public static String toHex(String txt) {
78 return toHex(txt.getBytes());
79 }
80 public static String fromHex(String hex) {
81 return new String(toByte(hex));
82 }
83
84 public static byte[] toByte(String hexString) {
85 int len = hexString.length()/2;
86 byte[] result = new byte[len];
87 for (int i = 0; i < len; i++)
88 result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
89 return result;
90 }
91
92 public static String toHex(byte[] buf) {
93 if (buf == null)
94 return "";
95 StringBuffer result = new StringBuffer(2*buf.length);
96 for (int i = 0; i < buf.length; i++) {
97 appendHex(result, buf[i]);
98 }
99 return result.toString();
100 }
101 private final static String HEX = "0123456789ABCDEF";
102 private static void appendHex(StringBuffer sb, byte b) {
103 sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
104 }
105}
106ИÑпользование клаÑÑа может выглÑдеть Ñледующим образом:
107
108String s = "Привет.";
109 String d = SimpleDESCryptoProvider.encrypt(s);
110 System.out.println(d);
111 s = SimpleDESCryptoProvider.decrypt(d);
112 System.out.println(s);