· 6 years ago · Mar 18, 2019, 04:54 AM
1import javax.crypto.*;
2import javax.crypto.spec.DESKeySpec;
3import java.util.Arrays;
4
5public class TripleDES {
6
7 enum MODE {
8 ENCRYPT(0), DECRYPT(1);
9 int code;
10
11 MODE(int code) {
12 this.code = code;
13 }
14 }
15
16 public static byte[] encrypt(String plaintext, String rawkey) throws Exception {
17 return _trip(plaintext.getBytes(), rawkey.getBytes(), MODE.ENCRYPT);
18 }
19
20 public static String decrypt(byte[] encrypted, String rawkey) throws Exception {
21 String res = "";
22
23 for (byte b : _trip(encrypted, rawkey.getBytes(), MODE.DECRYPT))
24 res += String.format("%c", b);
25
26 return res;
27 }
28
29 private static SecretKey prepKey(byte[] key) throws Exception {
30 DESKeySpec dks = new DESKeySpec(key);
31 SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
32 return skf.generateSecret(dks);
33 }
34
35 private static byte[] _trip(byte[] input, byte[] key, MODE mode) throws Exception {
36 int process[][] = {
37 {Cipher.ENCRYPT_MODE, Cipher.DECRYPT_MODE, Cipher.ENCRYPT_MODE}, // encrypt
38 {Cipher.DECRYPT_MODE, Cipher.ENCRYPT_MODE, Cipher.DECRYPT_MODE}}; // decrypt
39 byte[] res = input;
40
41 for (int i = 0; i < 3; i++)
42 res = _digest(res, Arrays.copyOfRange(key, 0 * 8, (i + 1) * 8), process[mode.code][i]);
43
44 return res;
45 }
46
47 private static byte[] _digest(byte[] plain, byte[] key, int mode) throws Exception {
48 Cipher cipher = Cipher.getInstance("DES");
49 cipher.init(mode, prepKey(key));
50 return cipher.doFinal(plain);
51 }
52
53 public static void main(String[] args) {
54 String plaintext = "Did you hear about the restaurant on the moon?",
55 passphrase = "Good food, no atmosphere";
56 try {
57 byte[] encrypted = TripleDES.encrypt(plaintext, passphrase);
58 System.out.println(TripleDES.decrypt(encrypted, passphrase));
59
60 } catch (Exception e) {
61 e.printStackTrace();
62 }
63 }
64}