Encryption and decryption using RSA in java

You may also like to read:

Introduction

RSA is a cryptosystem, which is known as one of the first practicable public-key cryptosystems and is widely used for secure data transmission. In such a cryptosystem, the encryption key is public and differs from the decryption key which is kept secret. In RSA, this asymmetry is based on the practical difficulty of factoring the product of two large prime numbers – the factoring problem. RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman, who first publicly described the algorithm in 1977.

For more information on RSA, refer to wiki.

Here I am going to give an example for encryption and decryption mechanism in java using RSA algorithm.

Prerequisites

Knowledge of RSA Algorithm, Java 1.8

Example with Source Code

Creating Constants

First create the RSAConstants java class which will be used for holding the various constants used in this coding.

The class defines two constants – algorithm name and algorithm’s key size.

package com.jeejava.rsa;

public final class RSAConstants {

	private RSAConstants() {
	}

	public static final String ALGORITHM = "RSA";
	public static final int ALGORITHM_BITS = 2048;
}

Creating KeyPair Generator

Now create the RSA KeyPair generator class which will be further used for encryption and decryption.

This class will generate private and public keys, which will be used along with password for encryption or decryption.

package com.jeejava.rsa;

import java.security.KeyPair;
import java.security.KeyPairGenerator;

public class RSAKeyPair {

	public static KeyPair keyPairRSA() {
		KeyPairGenerator generator = null;
		try {
			generator = KeyPairGenerator.getInstance(RSAConstants.ALGORITHM);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (generator != null) {
			generator.initialize(RSAConstants.ALGORITHM_BITS);
			KeyPair keyPair = generator.genKeyPair();
			return keyPair;
		}
		return null;
	}

}

Encryption and Decryption

Now create the logic for encryption and decryption. We return byte array after encrypting the value or decrypting the value. We use encryption or decryption mode to indicate whether we are doing encryption or decryption.

package com.jeejava.rsa;

import java.security.Key;

import javax.crypto.Cipher;

public class RSAEncryptDecrypt {

	public static byte[] encrypt(String original, Key privateKey) {
		if (original != null && privateKey != null) {
			byte[] bs = original.getBytes();
			byte[] encData = convert(bs, privateKey, Cipher.ENCRYPT_MODE);
			return encData;
		}
		return null;
	}

	public static byte[] decrypt(byte[] encrypted, Key publicKey) {
		if (encrypted != null && publicKey != null) {
			byte[] decData = convert(encrypted, publicKey, Cipher.DECRYPT_MODE);
			return decData;
		}
		return null;
	}

	private static byte[] convert(byte[] data, Key key, int mode) {
		try {
			Cipher cipher = Cipher.getInstance(RSAConstants.ALGORITHM);
			cipher.init(mode, key);
			byte[] newData = cipher.doFinal(data);
			return newData;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}

Creating Main Class

Now for testing purpose create a main class and test the above encryption and decryption.

We pass the value password to encrypt using RSA algorithm and we again decrypt the encrypted value to get back the original value password.

package com.jeejava.rsa;

import java.security.Key;
import java.security.KeyPair;
import java.util.Arrays;

public class RSATest {

	public static void main(String[] args) {
		String password = "password";
		KeyPair keyPair = RSAKeyPair.keyPairRSA();
		Key publicKey = keyPair.getPublic();
		Key privateKey = keyPair.getPrivate();

		System.out.println("Encrypt Start");
		System.out.println("Original: " + password);
		byte[] encrypted = RSAEncryptDecrypt.encrypt(password, privateKey);
		System.out.println("Encrypted: " + new String(encrypted));
		System.out.println("Encrypt End");

		System.out.println();

		System.out.println("Decrypt Start");
		byte[] decrypted = RSAEncryptDecrypt.decrypt(encrypted, publicKey);
		System.out.println("Decrypted: " + new String(decrypted));
		System.out.println("Decrypted matches Original: " + Arrays.equals(decrypted, password.getBytes()));
		System.out.println("Decrypt End");
	}

}

Testing the Application

Run the above main class, you will get below output in the console:

Encrypt Start
Original: password
Encrypted: 1v
X±ê\‚?Ô?سöLLq}G­òkÓW¸‹åyS›ÙŽÚµ‹O'•$€«è1ݤU¿`«ßì¶ÂÒáwröïÖ]]­	4S=Æ°Þ.¼×PŒóÙI%R?=”;¾DÛfÜÊKg½UœÎ€ôYô9/B—¿2eU?Â"-ü柈ñû„|ï\Ôî'3Šb_ŠËí·z†Ô‘ߤ¬¬oRäêˆ<‰³X"×&Ü©—æYý^
Ë
,N«7G•‡ˆuæJµ~,>³yóý–;¶Ÿ—ÏZ?Ü—³:shßòE+«}鎠÷ëY¯ÍØ CÈy
$PJ2W
Encrypt End

Decrypt Start
Decrypted: password
Decrypted matches Original: true
Decrypt End

Hope you got an idea on encryption and decryption using RSA in Java.

Source Code

You can download source code.

Thanks for reading.

Encryption and decryption using RSA in java

Leave a Reply

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

Scroll to top