· 7 years ago · Dec 30, 2018, 04:00 PM
1import javax.crypto.*;
2import java.io.File;
3import java.io.IOException;
4import java.io.UnsupportedEncodingException;
5import java.net.URI;
6import java.nio.charset.StandardCharsets;
7import java.nio.file.Files;
8import java.security.InvalidKeyException;
9import java.security.NoSuchAlgorithmException;
10import java.security.SecureRandom;
11
12public class Test1 {
13
14
15
16 Cipher cipher;
17 SecretKey secretKey;
18 byte[] plainText = "Zaszyfrowana wiadomość".getBytes("UTF-8");
19
20 URI uri;
21
22 public Test1() throws NoSuchPaddingException, NoSuchAlgorithmException, IOException, BadPaddingException, InvalidKeyException, IllegalBlockSizeException {
23
24 cipher = Cipher.getInstance("AES");
25
26 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
27 SecureRandom secureRandom = new SecureRandom();
28 int keyBitSize = 256;
29 keyGenerator.init(keyBitSize,secureRandom);
30
31 secretKey = keyGenerator.generateKey();
32
33 File f = new File("C:\\Users\\Max\\Documents\\GitHub\\Playground\\res\\sztos.jpg");
34 byte[] fileContent = Files.readAllBytes(f.toPath());
35 byte[] encryptedFileContent = szyfruj(fileContent);
36 File fEncrypted = new File("C:\\Users\\Max\\Documents\\GitHub\\Playground\\res\\sztosEncrypted.txt");
37
38 byte[] dectyptedFileContent = deszyfruj(encryptedFileContent);
39 File f1 = new File("C:\\Users\\Max\\Documents\\GitHub\\Playground\\res\\sztos1.jpg");
40
41
42
43 try {
44 Files.write(f1.toPath(), dectyptedFileContent);
45
46 Files.write(fEncrypted.toPath(), encryptedFileContent);
47 } catch (IOException e) {
48 e.printStackTrace();
49 }
50
51 }
52
53 public byte[] szyfruj() throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
54
55 cipher.init(Cipher.ENCRYPT_MODE,secretKey);
56 byte[] cipherText= cipher.doFinal(plainText);
57
58 //showPlease(cipherText);
59 //showPlease(new String(cipherText, StandardCharsets.UTF_8));
60
61 return cipherText;
62 }
63
64 public byte[] szyfruj(byte[] plainText) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
65
66 cipher.init(Cipher.ENCRYPT_MODE,secretKey);
67 byte[] cipherText= cipher.doFinal(plainText);
68
69 showPlease(cipherText);
70 //showPlease(new String(cipherText, StandardCharsets.UTF_8));
71
72 return cipherText;
73 }
74
75 public byte[] deszyfruj(byte[] plainText) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
76
77 cipher.init(Cipher.DECRYPT_MODE,secretKey);
78 byte[] cipherText= cipher.doFinal(plainText);
79 showPlease(cipherText);
80 showPlease(new String(cipherText, StandardCharsets.UTF_8));
81 return cipherText;
82 }
83
84 public void showPlease(byte[] args){
85 for (byte b : args
86 ) {
87 System.out.print(b);
88 }
89 System.out.println();
90 }
91
92
93 public void showPlease(String args){
94 System.out.println(args);
95 }
96
97
98}