· 7 years ago · Mar 28, 2018, 07:32 AM
1package mkri;
2
3import java.security.InvalidAlgorithmParameterException;
4import java.security.InvalidKeyException;
5import java.security.NoSuchAlgorithmException;
6import java.security.SecureRandom;
7import java.security.spec.AlgorithmParameterSpec;
8
9import javax.crypto.BadPaddingException;
10import javax.crypto.Cipher;
11import javax.crypto.IllegalBlockSizeException;
12import javax.crypto.KeyGenerator;
13import javax.crypto.NoSuchPaddingException;
14import javax.crypto.SecretKey;
15import javax.crypto.spec.IvParameterSpec;
16import javax.crypto.spec.SecretKeySpec;
17
18public class Encryption {
19
20 private byte[] IV;
21 public byte[] encrypt(byte[] data, byte[] bKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
22
23 //--------------------- vytvoreni random IV --------------------------------------- (6)
24
25
26 int ivSize = 16;
27 IV = new byte[ivSize];
28 SecureRandom random = new SecureRandom();
29 random.nextBytes(IV);
30 IvParameterSpec ivParameterSpec = new IvParameterSpec(IV);
31
32
33
34 //--------------------- vytvoreni random IV ---------------------------------------
35 byte[] bEnc = null;
36
37 // --------------------- vytvorit instanci tÅ™Ãdy Cipher, inicializovat a použÃt --- (4)
38
39
40 SecretKey originalKey = new SecretKeySpec(bKey, 0, bKey.length, "AES");
41
42 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
43
44 c.init(Cipher.ENCRYPT_MODE, originalKey, ivParameterSpec);
45
46 bEnc = c.doFinal(data);
47 // --------------------- vytvorit instanci tÅ™Ãdy Cipher, inicializovat a použÃt ---
48 return bEnc;
49
50 }
51
52 public byte[] decrypt(byte[] data, byte[] bKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
53
54 byte[] bDec = null;
55 // --------------------- vytvorit instanci tÅ™Ãdy Cipher, inicializovat a použÃt --- (5)
56
57 int ivSize = 16;
58 IV = new byte[ivSize];
59
60 System.arraycopy(data, 0, IV, 0, IV.length);
61 IvParameterSpec ivParameterSpec = new IvParameterSpec(IV);
62
63 SecretKey originalKey = new SecretKeySpec(bKey, 0, bKey.length, "AES");
64
65 Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
66 //c.init(Cipher.ENCRYPT_MODE, key);
67 c.init(Cipher.DECRYPT_MODE, originalKey, ivParameterSpec);
68
69 bDec = c.doFinal(data);
70
71
72 // --------------------- vytvorit instanci tÅ™Ãdy Cipher, inicializovat a použÃt ---
73 return bDec;
74
75 }
76
77}