· 7 years ago · Dec 11, 2018, 02:00 PM
1
2import java.io.UnsupportedEncodingException;
3import java.security.InvalidKeyException;
4
5import java.security.NoSuchAlgorithmException;
6
7
8import javax.crypto.*;
9
10
11import com.sun.mail.util.BASE64DecoderStream;
12
13import com.sun.mail.util.BASE64EncoderStream;
14
15public class des {
16
17
18
19
20 private static Cipher ecipher;
21
22 private static Cipher dcipher;
23
24
25
26 private static SecretKey key;
27
28
29
30 public static void main(String[] args) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
31
32
33
34 try {
35
36
37
38
39 key = KeyGenerator.getInstance("DES").generateKey();
40
41 ecipher = Cipher.getInstance("DES");
42
43 dcipher = Cipher.getInstance("DES");
44
45 ecipher.init(Cipher.ENCRYPT_MODE, key);
46
47 dcipher.init(Cipher.DECRYPT_MODE, key);
48
49 String encrypted = encrypt("This is a classified message!");
50
51 String decrypted = decrypt(encrypted);
52
53 System.out.println("Decrypted: " + decrypted);
54
55 }
56
57 catch (NoSuchAlgorithmException e) {
58
59 System.out.println("No Such Algorithm:" + e.getMessage());
60
61 return;
62
63 }
64
65 catch (NoSuchPaddingException e) {
66
67 System.out.println("No Such Padding:" + e.getMessage());
68
69 return;
70
71 }
72
73 catch (InvalidKeyException e) {
74
75 System.out.println("Invalid Key:" + e.getMessage());
76
77 return;
78
79 }
80
81
82
83 }
84
85
86
87 public static String encrypt(String str) throws UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
88
89
90
91 try {
92
93
94 byte[] utf8 = str.getBytes("UTF8");
95
96 byte[] enc = ecipher.doFinal(utf8);
97
98 enc = BASE64EncoderStream.encode(enc);
99
100 return new String(enc);
101
102 }
103
104 catch (Exception e) {
105
106 e.printStackTrace();
107
108 }
109
110 return null;
111
112 }
113
114
115
116 public static String decrypt(String str) throws UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
117
118 try {
119
120 byte[] dec = BASE64DecoderStream.decode(str.getBytes());
121
122 byte[] utf8 = dcipher.doFinal(dec);
123
124 return new String(utf8, "UTF8");
125
126 }
127
128
129
130 catch (Exception e) {
131
132 e.printStackTrace();
133
134 }
135
136 return null;
137
138 }
139
140 }
141
142}