• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Java ChaCha20 Encryption and Decryption Example | Symmetric Encryption

April 23, 2019 by javainterviewpoint Leave a Comment

ChaCha20 is a stream cipher designed by Daniel J. Bernstein, ChaCha20 is a variant of the Salsa20 family of stream ciphers and widely used as an alternative to AES Encryption Algorithm. The 20 round stream cipher ChaCha20 is consistently faster and not sensitive to timing attacks as AES Algorithm. Java 11 has added support to ChaCha20 and ChaCha20 Poly1305 [AEAD]

What is ChaCha20 Stream Cipher?

Chacha20 is mainly used for encryption, its core is a pseudo-random number generator. ChaCha20 is based upon Add-Rotate-XOR (ARX) Operations, which are CPU friendly instructions. The ciphertext is obtained by XOR’ing the plain text with a pseudo-random stream. Both the ChaCha20 and ChaCha20-Poly1305 will implement the CipherSpi API within the SunJCE provider

Currently, JDK supports the key length of 256 bit only, if we try to use a different key length we will be getting an error like “Key length for ChaCha20 must be 256 bits”

Exception in thread "main" java.security.InvalidParameterException: Key length for ChaCha20 must be 256 bits
	at java.base/com.sun.crypto.provider.KeyGeneratorCore$ChaCha20KeyGenerator.engineInit(KeyGeneratorCore.java:230)
	at java.base/javax.crypto.KeyGenerator.init(KeyGenerator.java:540)
	at java.base/javax.crypto.KeyGenerator.init(KeyGenerator.java:517)
	at com.javainterviewpoint.ChaCha20_Encrytpion.main(ChaCha20Example.java:18)

Java ChaCha20 Encryption and Decryption Example

Java ChaCha20 Encryption and Decryption Example

package com.javainterviewpoint;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.ChaCha20ParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class ChaCha20_Encrytpion
{
	static String plainText = "This is a plain text which will be encrypted by ChaCha20 Algorithm";

	public static void main(String[] args) throws Exception
	{
		KeyGenerator keyGenerator = KeyGenerator.getInstance("ChaCha20");
		keyGenerator.init(256);

		// Generate Key
		SecretKey key = keyGenerator.generateKey();

		System.out.println("Original Text  : " + plainText);

		byte[] cipherText = encrypt(plainText.getBytes(), key);
		System.out.println("Encrypted Text : " + Base64.getEncoder().encodeToString(cipherText));

		String decryptedText = decrypt(cipherText, key);
		System.out.println("DeCrypted Text : " + decryptedText);

	}

	public static byte[] encrypt(byte[] plaintext, SecretKey key) throws Exception
	{
		byte[] nonceBytes = new byte[12];
		int counter = 5;
		
		// Get Cipher Instance
		Cipher cipher = Cipher.getInstance("ChaCha20");

		// Create ChaCha20ParameterSpec
		ChaCha20ParameterSpec paramSpec = new ChaCha20ParameterSpec(nonceBytes, counter);
				
		// Create SecretKeySpec
		SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "ChaCha20");

		// Initialize Cipher for ENCRYPT_MODE
		cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec);

		// Perform Encryption
		byte[] cipherText = cipher.doFinal(plaintext);

		return cipherText;
	}

	public static String decrypt(byte[] cipherText, SecretKey key) throws Exception
	{
		byte[] nonceBytes = new byte[12];
		int counter = 5;

		// Get Cipher Instance
		Cipher cipher = Cipher.getInstance("ChaCha20");

		// Create ChaCha20ParameterSpec
		ChaCha20ParameterSpec paramSpec = new ChaCha20ParameterSpec(nonceBytes, counter);
				
		// Create SecretKeySpec
		SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "ChaCha20");

		// Initialize Cipher for DECRYPT_MODE
		cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);

		// Perform Decryption
		byte[] decryptedText = cipher.doFinal(cipherText);

		return new String(decryptedText);
	}
}
  • KeyGenerator Class generates the symmetric encryption keys, we will obtain the KeyGenerator class instance by calling the getInstance() method passing the name of the algorithm as a parameter, in our case it is ChaCha20
KeyGenerator keyGenerator = KeyGenerator.getInstance("ChaCha20");
  • Once the KeyGenerator instance is created, we need to initialize it by calling its init() method, we need to pass the key size in bits to generate. Currently, Java 11 supports 256-bit key only.
keyGenerator.init(256);
  • Once the KeyGenerator is initialized, we can generate the symmetric SecretKey by calling the generateKey() method on top of the KeyGenerator instance.
SecretKey key = keyGenerator.generateKey();
  • We have a declared 12-byte nonce and initialized the counter value to 5. The nonce value must be 96 bits in length (12 bytes), any other length cannot be used as it results in an exception. The counter value can be any positive or negative integer.
byte[] nonceBytes = new byte[12];
int counter = 5;
  • Cipher class is the actual class which handles the encryption and decryption. Cipher class instance is created by calling the getInstance() method by passing the Cipher name as the parameter, in our case, it is ChaCha20 which is the name of the encryption algorithm.
Cipher cipher = Cipher.getInstance("ChaCha20");
  • We can also pass in parameter like “ChaCha20/None/NoPadding”. No other modes or padding values other than “None” and “NoPadding” will be accepted. If we try to use any other modes or padding we will be getting an error like “Mode must be None” or “Padding must be NoPadding”.
  • ChaCha20ParameterSpec specifies the parameter which should be used with the ChaCha20 algorithm, the parameters are 12-byte nonce and a 32-bit counter integer.
ChaCha20ParameterSpec paramSpec = new ChaCha20ParameterSpec(nonceBytes, counter);
  • The SecretKeySpec converts byte data into a secret key which is suitable to be passed to init() method of the Cipher class.
  • SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "ChaCha20");
  • Once the Cipher class instance is created we need to initialize it by calling the init() method. The init() method requires three parameters.
    • Mode – Cipher.ENCRYPT_MODE for encryption or Cipher.DECRYPT_MODE for decryption.
    • Key – SecretKeySpec is the key here
    • AlgorithmParameterSpec – we will be passing ChaCha20ParameterSpec [ChaCha20ParameterSpec  implements AlgorithmParameterSpec]
cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);
  • In order to perform encryption, we need to call the doFinal() method on top of the cipher instance passing the plainText as the parameter.
byte[] cipherText = cipher.doFinal(plaintext);
  • We need to encode the cipherText with Base64 encoding, in order to prevent modification when the cipherText is transferred.
Base64.getEncoder().encodeToString(cipherText)
  • In order to perform decryption, we need to pass the cipherText to the doFinal() method of the Cipher instance
byte[] decryptedText = cipher.doFinal(cipherText);

Output:

Original Text  : This is a plain text which will be encrypted by ChaCha20 Algorithm
Encrypted Text : 0aljGw8VOeU+eMyRC4eQekYOIUehWSUEpHHc23OHcjlZnAU5fTSKZln1hgbA2iJADwR+D1ktypILYiOCXxDLJSg+
DeCrypted Text : This is a plain text which will be encrypted by ChaCha20 Algorithm

Other interesting articles which you may like …

  • RSA Encryption and Decryption
  • AES 256 Encryption and Decryption
  • AES 128 Encryption and Decryption
  • Java URL Encode and Decode Example
  • Java Salted Password Hashing
  • Google Tink Example – Google Cryptography
  • Constructor in Java
  • Private Constructors in Java
  • Java Constructor Chaining with example
  • Java – Constructor in an Interface?
  • Constructor.newInstance() method
  • Parameterized Constructor in Java
  • Java 8 – Lambda Expressions
  • Java 8 – ForEach Example
  • Java 8 Default Methods in Interface
  • Multiple Inheritance in Java 8 through Interface
  • Java 9 – jdeprscan
  • Private Methods in Interfaces Java 9
  • Java Method Overloading Example
  • Java Constructor Overloading Example
  • Java this keyword | Core Java Tutorial
  • Java super keyword
  • Abstract Class in Java
  • Interface in Java and Uses of Interface in Java
  • What is Marker Interface
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • Java Autoboxing and Unboxing Examples
  • Use of Java Transient Keyword – Serailization Example
  • Use of static Keyword in Java
  • What is Method Overriding in Java
  • Encapsulation in Java with Example
  • Final Keyword in Java | Java Tutorial
  • Java Static Import
  • Java – How System.out.println() really work?
  • Java Ternary operator
  • Java newInstance() method

Filed Under: Core Java, Java Tagged With: ChaCha20, ChaCha20 Encryption, ChaCha20 Encryption and Decryption, Java ChaCha20, Java ChaCha20 Encryption, Stream Cipher

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·