Sitemap
Nuwan Zen

Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!

Java11: ChaCha20 Encryption

2 min readApr 5, 2021
Press enter or click to view image in full size
Photo by Ham Kris on Unsplash

Java 11 comes with ChaCha20 steam cipher. Let’s see how to use it.

Press enter or click to view image in full size
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;
}
}
Press enter or click to view image in full size

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:

--

--

Nuwan Zen
Nuwan Zen

Written by Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!