· 7 years ago · May 14, 2018, 01:56 PM
1package com.test;
2
3import org.junit.Test;
4
5import javax.crypto.Cipher;
6import javax.crypto.CipherOutputStream;
7import javax.crypto.spec.SecretKeySpec;
8import java.io.*;
9import java.util.zip.GZIPOutputStream;
10
11public class CipherExample {
12
13 String fileIn = "file.dat";
14 String fileOut1 = "file1.dat";
15 String fileOut2 = "file2.dat";
16 String fileOut3 = "file3.dat";
17 String fileOut4 = "file4.sec.zip";
18 String fileOut5 = "file5.sec.zip";
19
20 String secretKey = "1234567812345678";
21
22 private Cipher getCipher(String key) throws Exception
23 {
24 SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
25 Cipher cipher = Cipher.getInstance("AES");
26 cipher.init(Cipher.ENCRYPT_MODE, keySpec);
27
28 return cipher;
29 }
30
31 private void copy(InputStream inStream, OutputStream outStream) throws IOException
32 {
33 int b;
34 while ((b = inStream.read()) > 0 )
35 {
36 outStream.write(b);
37 }
38 }
39
40 @Test
41 public void doCopy() throws Exception
42 {
43 InputStream inStream = new FileInputStream(fileIn);
44 OutputStream outStream = new FileOutputStream(fileOut1);
45
46 copy(inStream, outStream);
47 }
48
49 @Test
50 public void doZip() throws Exception
51 {
52 InputStream inStream = new FileInputStream(fileIn);
53 OutputStream outStream = new GZIPOutputStream(new FileOutputStream(fileOut2));
54
55 copy(inStream, outStream);
56
57 inStream.close();
58 outStream.close();
59 }
60
61 @Test
62 public void doCipher() throws Exception
63 {
64 InputStream inStream = new FileInputStream(fileIn);
65 OutputStream outStream = new CipherOutputStream(new FileOutputStream(fileOut3), getCipher(secretKey));
66
67 copy(inStream, outStream);
68
69 inStream.close();
70 outStream.close();
71 }
72
73 @Test
74 public void doAll() throws Exception
75 {
76 InputStream inStream = new FileInputStream(fileIn);
77 OutputStream outStream = new GZIPOutputStream(new CipherOutputStream(new FileOutputStream(fileOut4), getCipher(secretKey)));
78
79 copy(inStream, outStream);
80
81 inStream.close();
82 outStream.close();
83 }
84
85 @Test
86 public void doAll2() throws Exception
87 {
88 InputStream inStream = new FileInputStream(fileIn);
89 OutputStream outStream = new CipherOutputStream(new GZIPOutputStream(new FileOutputStream(fileOut5)), getCipher(secretKey));
90
91 copy(inStream, outStream);
92
93 inStream.close();
94 outStream.close();
95 }
96
97 //W DOMU OTWORZ ZASZYFROWANE PLIKI ODCZYTAJ JE
98}