· 7 years ago · Jun 05, 2018, 05:22 PM
1public class Main {
2
3 public static void main(String[] args) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
4 SecureRandom sr = new SecureRandom();
5 sr.generateSeed(128);
6 byte[] sKeyBytes = new byte[16];
7 sr.nextBytes(sKeyBytes);
8 SecretKey sKey = new SecretKeySpec(sKeyBytes, "AES");
9 byte[] iv = new byte[16];
10 sr.nextBytes(iv);
11 IvParameterSpec ips = new IvParameterSpec(iv);
12
13 File f = new File("bla.txt");
14 byte[] array = Files.readAllBytes(f.toPath());
15 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
16 c.init(Cipher.ENCRYPT_MODE, sKey, ips);
17 File f2 = new File("wynik.enc");
18
19 FileOutputStream fos = new FileOutputStream(f2);
20 CipherOutputStream cos = new CipherOutputStream(fos, c);
21 cos.write(array);
22 cos.close();
23 fos.close();
24
25 Cipher c2 = Cipher.getInstance("AES/CBC/PKCS5Padding");
26 c2.init(Cipher.DECRYPT_MODE, sKey, ips);
27 FileInputStream fis = new FileInputStream(f2);
28 CipherInputStream cis = new CipherInputStream(fis, c2);
29 byte[] array2 = new byte[1024];
30 cis.read(array2);
31 cis.close();
32 fis.close();
33
34 FileOutputStream fos2 = new FileOutputStream("nowy.txt");
35 fos2.write(array2);
36 fos2.close();
37 }
38}