Java11: ChaCha20 Encryption
Java 11 comes with ChaCha20 steam cipher. Let’s see how to use it.
package com.nuwan.java11;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.ChaCha20ParameterSpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class ChaCha20Encryption {
public static void main(String[] args) throws Exception {
String input = "Java & ChaCha20 encryption example.";
ChaCha20 chaCha20 = new ChaCha20();
SecretKey key = getKey();
byte[] nonce =getNonce();
int counter = 1;
ChaCha20 cipher = new ChaCha20();
byte[] cText=cipher.encrypt(input.getBytes(),key,nonce,counter);
System.out.println(new String(cText)); byte[] ptext=cipher.decrypt(cText,key,nonce,counter);
System.out.println(new String( ptext));
}
private static byte[] getNonce() {
byte[] newNonce = new byte[12];
new SecureRandom().nextBytes(newNonce);
return newNonce;
}
private static SecretKey getKey() throws NoSuchAlgorithmException {
KeyGenerator keyGen=KeyGenerator.getInstance("ChaCha20");
keyGen.init(256, SecureRandom.getInstanceStrong());
return keyGen.generateKey();
}
}
class ChaCha20{
public byte[] encrypt(byte[] pText, SecretKey key, byte[] nonce, int counter) throws Exception {
Cipher cipher = Cipher.getInstance("ChaCha20");
ChaCha20ParameterSpec param=new ChaCha20ParameterSpec(nonce, counter);
cipher.init(Cipher.ENCRYPT_MODE,key,param);
byte[] encryptedText=cipher.doFinal(pText);
return encryptedText;
}
public byte[] decrypt(byte[] cText, SecretKey key, byte[] nonce, int counter ) throws Exception {
Cipher cipher=Cipher.getInstance("ChaCha20");
ChaCha20ParameterSpec param=new ChaCha20ParameterSpec(nonce, counter);
cipher.init(Cipher.DECRYPT_MODE,key,param);
byte[] decryptedText = cipher.doFinal(cText);
return decryptedText;
}
}
Ref: https://mkyong.com/java/java-11-chacha20-stream-cipher-examples/
Get Nuwan Zen’s stories in your inbox
Join Medium for free to get updates from this writer.
Don’t forget read my other writings:



![[IronHold] — Spring Boot Source Code Analysis: Finding Credentials, SQL Injection, PrivEsc, and…](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*2yaTo73YRGo1GknAUJNfPg.jpeg)



