· 6 years ago · Jul 20, 2019, 06:28 PM
1import java.io.FileInputStream;
2import java.io.FileOutputStream;
3import java.io.IOException;
4import java.io.InputStream;
5import java.io.OutputStream;
6
7import javax.crypto.Cipher;
8import javax.crypto.CipherInputStream;
9import javax.crypto.CipherOutputStream;
10import javax.crypto.SecretKey;
11import javax.crypto.SecretKeyFactory;
12import javax.crypto.spec.DESKeySpec;
13
14public class DES {
15
16 public static void main(String[] args) {
17 try {
18 String key = "password"; // needs to be at least 8 characters for DES
19
20 FileInputStream fis = new FileInputStream("original.txt");
21 FileOutputStream fos = new FileOutputStream("encrypted.txt");
22 encrypt(key, fis, fos);
23
24 FileInputStream fis2 = new FileInputStream("encrypted.txt");
25 FileOutputStream fos2 = new FileOutputStream("decrypted.txt");
26 decrypt(key, fis2, fos2);
27 } catch (Throwable e) {
28 e.printStackTrace();
29 }
30 }
31
32 public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
33 encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
34 }
35
36 public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
37 encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
38 }
39
40 public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
41
42 DESKeySpec dks = new DESKeySpec(key.getBytes());
43 SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
44 SecretKey desKey = skf.generateSecret(dks);
45 Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE
46
47 if (mode == Cipher.ENCRYPT_MODE) {
48 cipher.init(Cipher.ENCRYPT_MODE, desKey);
49 CipherInputStream cis = new CipherInputStream(is, cipher);
50 doCopy(cis, os);
51 } else if (mode == Cipher.DECRYPT_MODE) {
52 cipher.init(Cipher.DECRYPT_MODE, desKey);
53 CipherOutputStream cos = new CipherOutputStream(os, cipher);
54 doCopy(is, cos);
55 }
56 }
57
58 public static void doCopy(InputStream is, OutputStream os) throws IOException {
59 byte[] bytes = new byte[64];
60 int numBytes;
61 while ((numBytes = is.read(bytes)) != -1) {
62 os.write(bytes, 0, numBytes);
63 }
64 os.flush();
65 os.close();
66 is.close();
67 }
68
69}