· 5 years ago · Jan 10, 2020, 11:44 AM
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.FileNotFoundException;
10import java.io.FileOutputStream;
11import java.io.IOException;
12import java.io.InputStream;
13import java.io.OutputStream;
14import java.util.ArrayList;
15import java.util.Scanner;
16
17import javax.crypto.Cipher;
18import javax.crypto.CipherInputStream;
19import javax.crypto.CipherOutputStream;
20import javax.crypto.SecretKey;
21import javax.crypto.SecretKeyFactory;
22import javax.crypto.spec.DESKeySpec;
23
24public class DES {
25
26 FileInputStream fis;
27 FileOutputStream fos;
28 static String key = "SofianeArtsitbzzzf";
29 ArrayList<String> text;
30 String f;
31 public DES(String file) throws FileNotFoundException, Throwable{
32 fis = new FileInputStream(file);
33 FileOutputStream fos = new FileOutputStream("C:\\Users\\meder\\Desktop\\9raya\\crypto\\encrypted.txt");
34 encrypt(key, fis, fos);
35
36 FileInputStream fis2 = new FileInputStream("C:\\Users\\meder\\Desktop\\9raya\\crypto\\encrypted.txt");
37 FileOutputStream fos2 = new FileOutputStream("C:\\Users\\meder\\Desktop\\9raya\\crypto\\decrypted.txt");
38 decrypt(key, fis2, fos2);
39
40 }
41 public static void main(String[] args) throws Throwable {
42 Scanner scanner = new Scanner( System.in);
43
44 System.out.println("donner moi le chemin absolut du fichier : ");
45
46 String f = scanner.nextLine();
47 DES d= new DES(f);
48
49 }
50
51 public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
52 encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
53 }
54
55 public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
56 encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
57 }
58
59 public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
60
61 DESKeySpec dks = new DESKeySpec(key.getBytes());
62 SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
63 SecretKey desKey = skf.generateSecret(dks);
64 Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE
65
66 if (mode == Cipher.ENCRYPT_MODE) {
67 cipher.init(Cipher.ENCRYPT_MODE, desKey);
68 CipherInputStream cis = new CipherInputStream(is, cipher);
69 doCopy(cis, os);
70 } else if (mode == Cipher.DECRYPT_MODE) {
71 cipher.init(Cipher.DECRYPT_MODE, desKey);
72 CipherOutputStream cos = new CipherOutputStream(os, cipher);
73 doCopy(is, cos);
74 }
75 }
76
77 public static void doCopy(InputStream is, OutputStream os) throws IOException {
78 byte[] bytes = new byte[64];
79 int numBytes;
80 while ((numBytes = is.read(bytes)) != -1) {
81 os.write(bytes, 0, numBytes);
82 }
83 os.flush();
84 os.close();
85 is.close();
86 }
87
88}