· 8 years ago · Dec 12, 2017, 10:04 AM
1import java.io.BufferedReader;
2import java.io.InputStreamReader;
3import javax.crypto.Cipher;
4import javax.crypto.SecretKey;
5import javax.crypto.SecretKeyFactory;
6import javax.crypto.spec.DESKeySpec;
7
8import sun.misc.BASE64Decoder;
9import sun.misc.BASE64Encoder;
10
11
12public class DES {
13 private SecretKey key;
14 public String theKey;
15
16 public DES() {
17 }
18 private void generateKey() throws Exception {
19
20
21 DESKeySpec desKeySpec = new DESKeySpec(theKey.getBytes());
22 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
23 key = keyFactory.generateSecret(desKeySpec);
24 }
25private String encrypt (String message) throws Exception {
26 //Get a chiper object.
27
28 Cipher cipher = Cipher.getInstance("DES");
29
30 cipher.init(Cipher.ENCRYPT_MODE, key);
31
32 //Gets the raw bytes to encrypt, UTFS is needed for
33 //having a standard character set
34 byte[] stringBytes = message.getBytes("UTF8");
35
36 //Encrypt using the cipher
37 byte[] raw = cipher.doFinal (stringBytes);
38
39 //converts to base64 for easier display
40 BASE64Encoder encoder = new BASE64Encoder();
41 String base64 = encoder.encode(raw);
42
43 return base64;
44 }
45
46 private String decrypt(String encrypted) throws Exception {
47
48 //Get a cipher object.
49 Cipher cipher = Cipher.getInstance("DES");
50 cipher.init(Cipher.DECRYPT_MODE, key);
51
52 //decode the Base64 coded message.
53 BASE64Decoder decoder = new BASE64Decoder();
54 byte[] raw = decoder.decodeBuffer(encrypted);
55
56 //decode the message.
57 byte[] stringBytes = cipher.doFinal(raw);
58
59 //converts the decode message to a String
60 String clear = new String(stringBytes, "UTF8");
61 return clear;
62 }
63
64 public static void main(String[] args) {
65 long start;
66 long end;
67 start = System.currentTimeMillis();
68
69
70 String Message="Klasik";
71 String Decrypted;
72 String Encrypted;
73 DES des= new DES();
74 des.theKey="cryptographymode";
75
76 try
77 {
78 des.generateKey();
79 System.out.println("clear message: " + Message);
80 Encrypted=des.encrypt(Message);
81 Decrypted=des.decrypt(Encrypted);
82
83 System.out.println("encrypted message: " + Encrypted);
84 System.out.println("decrypted message: " + Decrypted);
85 end = System.currentTimeMillis();
86 System.out.println("waktu yang dibutuhkan enkripsi adalah:" +(end-start) / 1000.0 +"detik");
87
88
89 } catch (Exception e)
90 {
91 e.printStackTrace();
92}
93}
94}