· 9 years ago · Oct 20, 2016, 04:58 AM
1import java.security.MessageDigest;
2import java.util.Arrays;
3
4import javax.crypto.Cipher;
5import javax.crypto.SecretKey;
6import javax.crypto.spec.IvParameterSpec;
7import javax.crypto.spec.SecretKeySpec;
8
9public class TripleDESTest {
10
11 public static void main(String[] args) throws Exception {
12
13 String text = "kyle boon";
14
15 byte[] codedtext = new TripleDESTest().encrypt(text);
16 String decodedtext = new TripleDESTest().decrypt(codedtext);
17
18 System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
19 System.out.println(decodedtext); // This correctly shows "kyle boon"
20 }
21
22 public byte[] encrypt(String message) throws Exception {
23 final MessageDigest md = MessageDigest.getInstance("md5");
24 final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
25 .getBytes("utf-8"));
26 final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
27 for (int j = 0, k = 16; j < 8;) {
28 keyBytes[k++] = keyBytes[j++];
29 }
30
31 final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
32 final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
33 final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
34 cipher.init(Cipher.ENCRYPT_MODE, key, iv);
35
36 final byte[] plainTextBytes = message.getBytes("utf-8");
37 final byte[] cipherText = cipher.doFinal(plainTextBytes);
38 // final String encodedCipherText = new sun.misc.BASE64Encoder()
39 // .encode(cipherText);
40
41 return cipherText;
42 }
43
44 public String decrypt(byte[] message) throws Exception {
45 final MessageDigest md = MessageDigest.getInstance("md5");
46 final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
47 .getBytes("utf-8"));
48 final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
49 for (int j = 0, k = 16; j < 8;) {
50 keyBytes[k++] = keyBytes[j++];
51 }
52
53 final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
54 final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
55 final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
56 decipher.init(Cipher.DECRYPT_MODE, key, iv);
57
58 // final byte[] encData = new
59 // sun.misc.BASE64Decoder().decodeBuffer(message);
60 final byte[] plainText = decipher.doFinal(message);
61
62 return new String(plainText, "UTF-8");
63 }
64}