· 6 years ago · May 06, 2019, 07:20 AM
1import javax.crypto.Cipher;
2import javax.crypto.KeyGenerator;
3import javax.crypto.SecretKey;
4
5class DesEncrypter {
6 Cipher ecipher;
7
8 Cipher dcipher;
9
10 DesEncrypter(SecretKey key) throws Exception {
11 ecipher = Cipher.getInstance("DES");
12 dcipher = Cipher.getInstance("DES");
13 ecipher.init(Cipher.ENCRYPT_MODE, key);
14 dcipher.init(Cipher.DECRYPT_MODE, key);
15 }
16
17 public String encrypt(String str) throws Exception {
18 // Encode the string into bytes using utf-8
19 byte[] utf8 = str.getBytes("UTF8");
20
21 // Encrypt
22 byte[] enc = ecipher.doFinal(utf8);
23
24 // Encode bytes to base64 to get a string
25 return new sun.misc.BASE64Encoder().encode(enc);
26 }
27
28 public String decrypt(String str) throws Exception {
29 // Decode base64 to get bytes
30 byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
31
32 byte[] utf8 = dcipher.doFinal(dec);
33
34 // Decode using utf-8
35 return new String(utf8, "UTF8");
36 }
37}
38
39public class Main {
40 public static void main(String[] argv) throws Exception {
41 SecretKey key = KeyGenerator.getInstance("DES").generateKey();
42 DesEncrypter encrypter = new DesEncrypter(key);
43 String encrypted = encrypter.encrypt("Don't tell anybody!");
44 String decrypted = encrypter.decrypt(encrypted);
45 }
46}