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