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");
        generator.initialize(1024);
        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");
    cipher.init(Cipher.ENCRYPT_MODE,publicKey);
    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");
    cipher.init(Cipher.DECRYPT_MODE,privateKey);
    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();
    try{
        String encryptedMessage = rsa.encrypt("Hello World");
        String decryptedMessage = rsa.decrypt(encryptedMessage);

        System.err.println("Encrypted:\n"+encryptedMessage);
        System.err.println("Decrypted:\n"+decryptedMessage);

    }catch (Exception ingored){}
}

The result obtained is

Encrypted:
ZwJH0YVcPtE62iyTzqK10mTRRYo+cuIMEJSMuhXa9axI8l9q4Z4W6J0cJBqC0Cw4WXjWMNuNx9CpBryEgx1Z72pZJtqU49EQ8rrravTxDnR+b3m3Fe4ijcBgun6sO021UCbMYrUlw/rupEE5dirn7pKdPi6R3c2rvMW7Z1r6ajQ=
Decrypted:
Hello World

Full code :

Full code can be found on GitHub