· 7 years ago · Jun 28, 2018, 09:12 AM
1import javax.crypto.*;
2import javax.crypto.spec.GCMParameterSpec;
3import java.nio.ByteBuffer;
4import java.nio.charset.StandardCharsets;
5import java.security.SecureRandom;
6import java.util.Arrays;
7import javax.crypto.spec.SecretKeySpec;
8
9public class Crypto{
10 public static final int AES_KEY_SIZE = 128; // in bits
11 public static final int GCM_NONCE_LENGTH = 12; // in bytes
12 public static final int GCM_TAG_LENGTH = 16; // in bytes
13 public static final String SECRET_KEY = "5508805566732388";
14
15 public static void main(String[] args)throws Exception{
16 String plainText = "Hello there!";
17 byte[] plainTextBytes = plainText.getBytes();
18
19 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE");
20
21 SecureRandom random = SecureRandom.getInstanceStrong();
22 byte[] iv = new byte[GCM_NONCE_LENGTH];
23 random.nextBytes(iv);
24 GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
25
26 byte[] secretKeyBytes = SECRET_KEY.getBytes();
27 SecretKey key = new SecretKeySpec(secretKeyBytes, 0, secretKeyBytes.length, "AES");
28
29 //
30 System.out.println("Before encryption");
31 System.out.println("Plain text is: " + new String(plainTextBytes, StandardCharsets.UTF_8));
32 System.out.println("Iv is: " + new String(iv, StandardCharsets.UTF_8));
33 //
34
35 //Encryption
36 cipher.init(cipher.ENCRYPT_MODE, key, spec);
37 cipher.updateAAD(iv);
38 byte[] encryptedData = cipher.doFinal(plainTextBytes);
39
40 byte[] authTag = Arrays.copyOfRange (encryptedData, encryptedData.length-16, encryptedData.length);
41
42 //
43 System.out.println("After encryption");
44 System.out.println("Encrypted data is: " + new String(encryptedData, StandardCharsets.UTF_8));
45 System.out.println("Iv is: " + new String(iv, StandardCharsets.UTF_8));
46 System.out.println("authTag is: " + new String(authTag, StandardCharsets.UTF_8));
47 //
48
49 //Decryption
50 cipher.init(cipher.DECRYPT_MODE, key, spec);
51 cipher.updateAAD(iv);
52 byte[] decryptedData = cipher.doFinal(encryptedData);
53
54 //
55 System.out.println("After Decryption");
56 System.out.println("decrypted data is: " + new String(decryptedData, StandardCharsets.UTF_8));
57 //
58 }
59}