· 7 years ago · Mar 28, 2018, 11: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, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
22
23 //--------------------- vytvoreni random IV --------------------------------------- (6)
24 this.IV = new byte[16];
25 SecureRandom sRND = new SecureRandom();
26 sRND.nextBytes(IV);
27 IvParameterSpec ivspec = new IvParameterSpec(IV);
28 //--------------------- vytvoreni random IV ---------------------------------------
29 byte[] bEnc = null;
30
31 // --------------------- vytvorit instanci tÅ™Ãdy Cipher, inicializovat a použÃt --- (4)
32 SecretKey key = new SecretKeySpec(bKey, 0,bKey.length, "AES");
33 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
34 cipher.init(Cipher.ENCRYPT_MODE, key, ivspec);
35 bEnc = cipher.doFinal(data);
36
37 // --------------------- vytvorit instanci tÅ™Ãdy Cipher, inicializovat a použÃt ---
38 return bEnc;
39
40 }
41
42 public byte[] decrypt(byte[] data, byte[] bKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
43 byte[] bDec = null;
44 //SecureRandom sRND = new SecureRandom();
45
46 //this.IV = new byte[16];
47 //System.arraycopy(data, 0, IV, 0, IV.length);
48 //sRND.nextBytes(IV);
49 IvParameterSpec ivspec = new IvParameterSpec(IV);
50
51 // --------------------- vytvorit instanci tÅ™Ãdy Cipher, inicializovat a použÃt --- (5)
52 SecretKey key = new SecretKeySpec(bKey, 0,bKey.length, "AES");
53 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
54 cipher.init(Cipher.DECRYPT_MODE, key, ivspec);
55
56
57
58 bDec = cipher.doFinal(data);
59 // --------------------- vytvorit instanci tÅ™Ãdy Cipher, inicializovat a použÃt ---
60 return bDec;
61
62 }
63
64}