· 7 years ago · Nov 20, 2018, 09:32 PM
1package com.javacodegeeks.snippets.core;
2
3import java.io.FileInputStream;
4import java.io.FileOutputStream;
5import java.io.InputStream;
6import java.io.OutputStream;
7import java.security.Security;
8import java.security.spec.AlgorithmParameterSpec;
9
10import javax.crypto.Cipher;
11import javax.crypto.CipherInputStream;
12import javax.crypto.CipherOutputStream;
13import javax.crypto.KeyGenerator;
14import javax.crypto.SecretKey;
15import javax.crypto.spec.IvParameterSpec;
16
17public class Main {
18
19 static Cipher ce;
20 static Cipher cd;
21
22 public static void main(String args[]) throws Exception {
23
24 Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
25
26 SecretKey skey = KeyGenerator.getInstance("DES").generateKey();
27
28 byte[] initializationVector = new byte[]{0x10, 0x10, 0x01, 0x04, 0x01, 0x01, 0x01, 0x02};
29
30 AlgorithmParameterSpec algParameters = new IvParameterSpec(initializationVector);
31
32 ce = Cipher.getInstance("DES/CBC/PKCS5Padding");
33
34 cd = Cipher.getInstance("DES/CBC/PKCS5Padding");
35
36 ce.init(Cipher.ENCRYPT_MODE, skey, algParameters);
37
38 cd.init(Cipher.DECRYPT_MODE, skey, algParameters);
39
40 FileInputStream is = new FileInputStream("C:/Users/nikos7/Desktop/output.txt");
41
42 FileOutputStream os = new FileOutputStream("C:/Users/nikos7/Desktop/output2.txt");
43
44 int dataSize = is.available();
45
46 byte[] inbytes = new byte[dataSize];
47
48 is.read(inbytes);
49
50 String str2 = new String(inbytes);
51
52 System.out.println("Input file contentn" + str2 + "n");
53
54 write_encode(inbytes, os);
55
56 os.flush();
57
58 is.close();
59
60 os.close();
61
62 System.out.println("Ecrypted Content to output2.txtn");
63
64 is = new FileInputStream("C:/Users/nikos7/Desktop/output2.txt");
65
66 byte[] decBytes = new byte[dataSize];
67
68 read_decode(decBytes, is);
69
70 is.close();
71
72 String str = new String(decBytes);
73
74 System.out.println("Decrypted file contents:n" + str);
75
76 }
77
78 public static void write_encode(byte[] bytes, OutputStream output) throws Exception {
79
80 CipherOutputStream cOutputStream = new CipherOutputStream(output, ce);
81
82 cOutputStream.write(bytes, 0, bytes.length);
83
84 cOutputStream.close();
85 }
86
87 public static void read_decode(byte[] bytes, InputStream input) throws Exception {
88
89 CipherInputStream cInputStream = new CipherInputStream(input, cd);
90
91 int position = 0, i;
92
93 while ((i = cInputStream.read()) != -1) {
94
95bytes[position] = (byte) i;
96
97position++;
98
99 }
100 }
101}