· 5 years ago · Jan 05, 2020, 07:16 PM
1/*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6package des;
7
8import java.io.FileInputStream;
9import java.io.FileOutputStream;
10import java.io.IOException;
11import java.io.InputStream;
12import java.io.OutputStream;
13
14import javax.crypto.Cipher;
15import javax.crypto.CipherInputStream;
16import javax.crypto.CipherOutputStream;
17import javax.crypto.SecretKey;
18import javax.crypto.SecretKeyFactory;
19import javax.crypto.spec.DESKeySpec;
20
21public class DES {
22
23	public static void main(String[] args) {
24		try {
25			String key = "SofianeArtsitbzzzf"; // needs to be at least 8 characters for DES
26
27			FileInputStream fis = new FileInputStream("C:\\Users\\meder\\Desktop\\9raya\\crypto\\input.txt");
28			FileOutputStream fos = new FileOutputStream("C:\\Users\\meder\\Desktop\\9raya\\crypto\\encrypted.txt");
29			encrypt(key, fis, fos);
30
31			FileInputStream fis2 = new FileInputStream("C:\\Users\\meder\\Desktop\\9raya\\crypto\\encrypted.txt");
32			FileOutputStream fos2 = new FileOutputStream("C:\\Users\\meder\\Desktop\\9raya\\crypto\\decrypted.txt");
33			decrypt(key, fis2, fos2);
34		} catch (Throwable e) {
35		}
36	}
37
38	public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
39		encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
40	}
41
42	public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
43		encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
44	}
45
46	public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
47
48		DESKeySpec dks = new DESKeySpec(key.getBytes());
49		SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
50		SecretKey desKey = skf.generateSecret(dks);
51		Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE
52
53		if (mode == Cipher.ENCRYPT_MODE) {
54			cipher.init(Cipher.ENCRYPT_MODE, desKey);
55			CipherInputStream cis = new CipherInputStream(is, cipher);
56			doCopy(cis, os);
57		} else if (mode == Cipher.DECRYPT_MODE) {
58			cipher.init(Cipher.DECRYPT_MODE, desKey);
59			CipherOutputStream cos = new CipherOutputStream(os, cipher);
60			doCopy(is, cos);
61		}
62	}
63
64	public static void doCopy(InputStream is, OutputStream os) throws IOException {
65		byte[] bytes = new byte[64];
66		int numBytes;
67		while ((numBytes = is.read(bytes)) != -1) {
68			os.write(bytes, 0, numBytes);
69		}
70		os.flush();
71		os.close();
72		is.close();
73	}
74
75}
76/**
77 *
78 * @author meder
79 
80public class DES {
81
82    /**
83     * @param args the command line arguments
84     
85  //  public static void main(String[] args) {
86        // TODO code application logic here
87        
88    }
89    
90}