RSA Encryption using Ciphers in JAVA : Android Studio | Spring

Single application RSA Encryption/Decryption

Let’s make a simple Java application to encrypt and decrypt Strings using the RSA algorithm, ECB block mode and PKCS1 padding

This project will only use one single class RSA

public class RSA{

First, we need to create the key pair (private and public keys). We will use a KeyPairGenerator that will create a KeyPair then we can get our private and public keys.

Let’s add two class variables

private PrivateKey privatekey;
private PublicKey publicKey;

They will host the keys generated by the constructor

public RSA(){
    try {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        KeyPair pair = generator.generateKeyPair();
        privateKey = pair.getPrivate();
        publicKey = pair.getPublic();
    } catch (Exception ignored) {}

Before starting the encryption and description process, let’s create two methods to encode and decode Strings using the Base64 encoder and decoder

private String encode(byte[] data){
    return Base64.getEncoder().encodeToString(data);
private byte[] decode(String data){
    return Base64.getDecoder().decode(data);

Let’s make the encrypt method

public String encrypt(String message) throws Exception{
    byte[] messageToBytes = message.getBytes();
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    byte[] encryptedBytes = cipher.doFinal(messageToBytes);
    return encode(encryptedBytes);

Don’t forget that the message you want to encrypt needs to be converted to bytes, the result of the encryption cipher.doFinal(byte[]) is a byte array that can be encoded to get the encrypted message

And the decryption method is similar to the encryption but inverted. Starting from decoding the string then initializing the cipher with the DECRYPT_MODE and returning the decrypted bytes using new String(bytes[])

public String decrypt(String encryptedMessage) throws Exception{
    byte[] encryptedBytes = decode(encryptedMessage);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    byte[] decryptedMessage = cipher.doFinal(encryptedBytes);
    return new String(decryptedMessage,"UTF8");

We can add the main method to test the encryption and the decryption methods:

public static void main(String[] args) {
    RSA rsa = new RSA();
        String encryptedMessage = rsa.encrypt("Hello World");
        String decryptedMessage = rsa.decrypt(encryptedMessage);


    }catch (Exception ingored){}

The result obtained is

Hello World

Full code :

Full code can be found on GitHub