· 5 years ago · Mar 17, 2020, 10:08 AM
1package code;
2
3import java.nio.ByteBuffer;
4import java.security.InvalidAlgorithmParameterException;
5import java.security.InvalidKeyException;
6import java.security.NoSuchAlgorithmException;
7
8import javax.crypto.BadPaddingException;
9import javax.crypto.Cipher;
10import javax.crypto.IllegalBlockSizeException;
11import javax.crypto.NoSuchPaddingException;
12import javax.crypto.SecretKey;
13import javax.crypto.spec.GCMParameterSpec;
14import javax.crypto.spec.SecretKeySpec;
15
16public class GCM {
17
18 private static final int KEY_LENGTH_IN_BYTES = 16;
19
20 public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
21 InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
22 ByteArrayGenerator generator = new ByteArrayGenerator();
23
24 byte[] key = generator.generateRandomByteArray(KEY_LENGTH_IN_BYTES);
25 SecretKey secretKey = new SecretKeySpec(key, "AES");
26
27 byte[] iv = generator.generateRandomByteArray(12);
28
29 final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
30 GCMParameterSpec parameterSpec = new GCMParameterSpec(KEY_LENGTH_IN_BYTES * 8, iv);
31 cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);
32
33
34 byte[] associatedData = generator.generateRandomByteArray(50);
35 if (associatedData != null) {
36 cipher.updateAAD(associatedData);
37 }
38
39 byte[] cipherText = cipher.doFinal("Super woopy secret".getBytes());
40
41 System.out.println(new String(cipherText));
42 // ENC finished
43
44
45 ByteBuffer byteBuffer = ByteBuffer.allocate(4 + iv.length + cipherText.length);
46 byteBuffer.putInt(iv.length);
47 byteBuffer.put(iv);
48 byteBuffer.put(cipherText);
49
50
51
52
53
54 // Transmission start
55 byte[] cipherMessage = byteBuffer.array();
56 // Transmission completed
57
58
59
60 ByteBuffer byteBuffer2 = ByteBuffer.wrap(cipherMessage);
61 int ivLength = byteBuffer2.getInt();
62 if(ivLength < 12 || ivLength >= 16) { // check input parameter
63 throw new IllegalArgumentException("invalid iv length");
64 }
65 byte[] iv2 = new byte[ivLength];
66 byteBuffer2.get(iv2);
67 byte[] cipherText2 = new byte[byteBuffer2.remaining()];
68 byteBuffer2.get(cipherText2);// same as loop .get() -> und in byte array schreiben
69
70
71
72 final Cipher cipher2 = Cipher.getInstance("AES/GCM/NoPadding");
73 GCMParameterSpec parameterSpec2 = new GCMParameterSpec(KEY_LENGTH_IN_BYTES * 8, iv2);
74 cipher2.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), parameterSpec2);
75
76 if (associatedData != null) {
77 cipher2.updateAAD(associatedData);
78 }
79
80 byte[] decryptedCipherText = cipher2.doFinal(cipherText2);
81 System.out.println(decryptedCipherText);
82 System.out.println(new String(decryptedCipherText));
83 }
84
85}