· 6 years ago · Oct 12, 2019, 09:35 PM
1package chaCha20Poly1305Encryption;
2
3import javax.crypto.*;
4import javax.crypto.spec.IvParameterSpec;
5import javax.crypto.spec.SecretKeySpec;
6import java.security.InvalidAlgorithmParameterException;
7import java.security.InvalidKeyException;
8import java.security.NoSuchAlgorithmException;
9import java.security.spec.AlgorithmParameterSpec;
10import java.util.Base64;
11
12public class ChaCha20Poly1305 {
13
14 public static byte[] encrypt(byte[] data, SecretKey key) throws NoSuchPaddingException, NoSuchAlgorithmException,
15 InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
16 if(key == null) throw new InvalidKeyException("SecretKey must NOT be NULL");
17
18 byte[] nonceBytes = new byte[12];
19
20 // Get Cipher Instance
21 Cipher cipher = Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding");
22
23 // Create IvParamterSpec
24 AlgorithmParameterSpec ivParameterSpec = new IvParameterSpec(nonceBytes);
25
26 // Create SecretKeySpec
27 SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "ChaCha20");
28
29 // Initialize Cipher for ENCRYPT_MODE
30 cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);
31
32 // Perform Encryption
33 return cipher.doFinal(data);
34 }
35
36 public static byte[] decrypt(byte[] cipherText, SecretKey key) throws Exception {
37 if(key == null) throw new InvalidKeyException("SecretKey must NOT be NULL");
38 byte[] nonceBytes = new byte[12];
39
40 // Get Cipher Instance
41 Cipher cipher = Cipher.getInstance("ChaCha20-Poly1305/None/NoPadding");
42
43 // Create IvParamterSpec
44 AlgorithmParameterSpec ivParameterSpec = new IvParameterSpec(nonceBytes);
45
46 // Create SecretKeySpec
47 SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "ChaCha20");
48
49 // Initialize Cipher for DECRYPT_MODE
50 cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);
51
52 // Perform Decryption
53 return cipher.doFinal(cipherText);
54 }
55
56 public static void main(String[] args) throws Exception {
57 SecretKey key = ChaCha20Poly1305KeyGenerator.generateKey();
58
59 String testMessage = "hallo!";
60 byte[] encryptedBytes = encrypt(testMessage.getBytes(), key);
61 String decryptedMessage = new String(decrypt(encryptedBytes,key));
62 System.out.println("testMessage: " + testMessage);
63 System.out.println(key.getAlgorithm() + " SecretKey: " + Base64.getEncoder().encodeToString(key.getEncoded()));
64 System.out.println("encryptedBytes: " + Base64.getEncoder().encodeToString(encryptedBytes));
65 System.out.println("decryptedMessage: "+ decryptedMessage);
66
67 }
68}