Introduction to Key Encapsulation Mechanism API in Java
Last Updated :
26 Apr, 2024
Key Encapsulation Mechanism (KEM) is nothing but it is a cryptographic technique used to securely encapsulate the symmetric cryptographic keys within the asymmetric key pairs. In Java, Java Cryptography Architecture (JCA) provides the APIs for implementing the various cryptographic operations which are including the Key Encapsulation Mechanism. Java doesn't have the built-in API specification named the "Key Encapsulation Mechanism API".
Here, we can implement the process of implementing a basic Key Encapsulation Mechanism using Java's Cryptographic APIs.
Prerequisites:
The following are the prerequisites to implement the Key Encapsulation Mechanism API in Java:
- Java Development Kit (JDK)
- Understanding of Java Cryptography Architecture (JCA)
- Knowledge of Asymmetric and Symmetric Cryptography
- Java Cryptography Extension (JCE)
- Security Considerations
- Java IDE (Optional)
Implementation of KEM API in Java
Step 1: Set up Eclipse Project
- Open Eclipse and create a new Java project.
- Name the project as "KeyEncapsulationExample".
Step 2: Generating Asymmetric Key Pair
- Create a Class file and name it as "AsymmetricKeyGenerator" in the src folder.
- Open the Class file and write the below code to implement the Asymmetric Key Generator Pair.
Java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
public class AsymmetricKeyGenerator {
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048); // Key size
return keyGen.generateKeyPair();
}
}
Explanation of the above Program:
Here, Generating Asymmetric Key Pair is generates the RSA asymmetric key pair using the KeyPairGenerator. The size of the key is set to 2048 bits.
Step 3: Generating Symmetric Key
- Create a Class file and name it as "SymmetricKeyGenerator" in src folder.
- Open the Class file and write the below code to implement the Symmetric Key Generator.
Java
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
public class SymmetricKeyGenerator {
public static SecretKey generateSymmetricKey() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // Key size
return keyGen.generateKey();
}
}
Explanation of the above Program:
Here, Generating Symmetric Key is generates a 256-bit AES symmetric key using keyGen object. AES keys are typically 128, 192, or 256 bits in size.
Step 4: Encrypting Symmetric Key with Public Key
- Create a Class file and name it as "KeyEncapsulation" in src folder.
- Open the Class file and write the below code to implement the Encrypting Symmetric Key with Public Key.
Java
import javax.crypto.Cipher;
import java.security.Key;
import java.security.PublicKey;
public class KeyEncapsulation {
public static byte[] encapsulateKey(Key symmetricKey, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(symmetricKey.getEncoded());
}
}
Explanation of the above Program:
- Here, The KeyEncapsulation class contains a method encapsulateKey. This method is encrypts a symmetric key using RSA encryption with the provided public key.
- This method is takes the symmetric key and a public key as input parameters and initializes a cipher for RSA encryption and encrypts the byte array representation of the symmetric key with use the public key.
- Finally, it returns encrypted key as a byte array.
Step 5: Decrypting Encrypted Key with Private Key
- Create a Class file and name it as "KeyDecapsulation" in src folder.
- Open the Class file and write the below code to implement the Decrypting Encrypted Key with Private Key.
Java
import javax.crypto.Cipher;
import java.security.Key;
import java.security.PrivateKey;
public class KeyDecapsulation {
public static byte[] decapsulateKey(byte[] encryptedKey, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedKey);
}
}
Explanation of the above Program:
Here, Decrypting Encrypted Symmetric Key with Private Key is initialize the "Cipher" object for RSA decryption with private key obtained from the key pair. After that, it decrypts the encrypted symmetric key using the RSA decryption.
Step 6: Putting it all Together in Main
- Create a Class file and name it as "Main" in src folder.
- Open the Class file and write the below code.
Java
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.SecretKey;
public class Main {
public static void main(String[] args) throws Exception {
// Step 1: Generate Asymmetric Key Pair
KeyPair keyPair = AsymmetricKeyGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// Step 2: Generate Symmetric Key
SecretKey symmetricKey = SymmetricKeyGenerator.generateSymmetricKey();
// Step 3: Encrypt Symmetric Key with Public Key
byte[] encryptedKey = KeyEncapsulation.encapsulateKey(symmetricKey, publicKey);
// Step 4: Decrypt Encrypted Key with Private Key
byte[] decryptedKey = KeyDecapsulation.decapsulateKey(encryptedKey, privateKey);
// Verify if the keys match
if (java.util.Arrays.equals(symmetricKey.getEncoded(), decryptedKey)) {
System.out.println("Keys match! Encapsulation and Decapsulation successful.");
} else {
System.out.println("Keys don't match! Encapsulation and Decapsulation failed.");
}
}
}
Step 7: Run the Code
- After completion of implement the code, you need to run the code.
- For run the code, right click on Java project and then select Run As > Java Application.
- The output will be shown in console window in your Eclipse as shown below.
Output:

Here, the output is indicates the symmetric key encapsulation and decapsulation process was successfully completed and that the decrypted symmetric key matches the original one, it describes the correctness of Key Encapsulation Mechanism implementation.
Similar Reads
Authentication with API Key in Java
Usually, in a web application, we will log in by using a username(email id/login name) with a password. Securely we can do the same by using an APIKey as well. Let us see what is an APIKey. The API key is a unique identifier that authenticates requests and if several users are there, their username
5 min read
Introduction to Java NIO with Examples
Java IO(Input/Output) is used to perform read and write operations. The java.io package contains all the classes required for input and output operation. Whereas, Java NIO (New IO) was introduced from JDK 4 to implement high-speed IO operations. It is an alternative to the standard IO APIâs. In this
5 min read
Encapsulation in Java
Encapsulation is one of the core concepts in Java Object-Oriented Programming (OOP). It is the process of wrapping data (variables) and methods that operate on the data into a single unit, i.e., a class. Encapsulation is used to hide the internal implementation details of a class. This technique ens
10 min read
KeyStore getCreationDate() method in Java with Examples
The getCreationDate() method of java.security.KeyStore class is used to get the date of creation of the specified entry with the help of the specified alias name. Syntax: public final Date getCreationDate(String alias) throws KeyStoreException Parameter: This method accepts the name of the alias as
3 min read
Encapsulation in R Programming
In R programming, OOPs provides classes and objects as its key tools to reduce and manage the complexity of the program. R is a functional language that uses concepts of OOPs. We can think of class like a sketch of a car. It contains all the details about the model_name, model_no, engine, etc. Based
4 min read
Difference Between keySet() and entrySet() Method in Java Map
Map Interface is present in Java.util package, which provides mainly three methods KeySet(),entrySet() and values(). These methods are used to retrieve the keys of the map, key-value pairs of the map, and values of the map respectively. Since these methods are part of Map Interface, so we can use th
4 min read
Introduction to Java
Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is intended to let application developers Write Once and Run Anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the
9 min read
What is Data Encapsulation and de-encapsulation in networking?
This article is all about Data Encapsulation and Decapsulation in Networking. Both encapsulation and decapsulation processes are simultaneously running over a network in order to make effective communication possible. Encapsulation is the process which is executed on the sender's side whereas decaps
3 min read
Foreign Function and Memory API in Java
Foreign Function Interface (FFI) and Memory API in Java provide mechanisms for Java programs to interact with code written in other languages, such as C or C++. This allows developers to leverage existing native libraries or access low-level system functionality. FFI enables Java programs to call na
3 min read
KeyStore isKeyEntry() method in Java with Examples
The isKeyEntry() method of java.security.KeyStore class is used to check if the particular specified key entry is present. It returns a boolean value stating the same. Syntax: public final boolean isKeyEntry(String alias) throws KeyStoreException Parameter: This method accepts the name of the alias
3 min read