By Alx: December 2019

Encrypt and decrypt data with RSA

Goal

This article explains how to generate a RSA Keypair in order to encrypt and decrypt data.

Big picture

tcpmon GET

Used technologies

JDK 1.8
Maven 3.2


Maven dependencies

There is only one dependency:junit

Helper class

Details:
In order to create a KeyPairGenerator you have to specify a algorithm RSA
We initialize the KeyPairGenerator by passing a keysize, we choose 2048 bit
At (line 10) we generate KeyPair that contains Public and Private Key

The encryptmethod takes two parameter: the Public Key and the message that should be enrcypted
After creating a RSA cipher,we initialize the Cipher with mode=ENCRYPT_MODE and pass the message
The method doFinal()performs Encryption and returns a byte array of the encrypted message

The decryptmethod takes two parameter: the Private Key and the encrypted message
For cipher initialization you specify the DECRYPT_MODE

RSA stands for Rivest, Shamir, and Adelman
Encrypted data with the public key can only decrypted by the private key and encrypted data with the private key can only be decrypted with the public key. Also known as asymmetric encryption

Test class



Run the test

The output should look like:

References


The complete code can be found in GitHub