Implementing RSA Public Key Decryption in Android Applications

Overview of the RSA Decryption Process

The process for decrypting data with a public key in Android involves three primary stages. The following table outlines these steps:

Step Description
1 Generate an RSA key pair (public and private keys).
2 Encrypt plaintext data using the public key.
3 Decrypt the ciphertext using the corresponding private key.

Implementation Steps and Code Examples

Step 1: Generating the RSA Key Pair

The initial step requires creating a public/private key pair using the RSA algorithm.

// Initialize a KeyPairGenerator for RSA
KeyPairGenerator rsaKeyGen = KeyPairGenerator.getInstance("RSA");
// Specify the key size (e.g., 2048 bits for stronger security)
rsaKeyGen.initialize(2048);
// Generate the key pair
KeyPair rsaKeyPair = rsaKeyGen.generateKeyPair();

// Extract the public and private keys
PublicKey rsaPublicKey = rsaKeyPair.getPublic();
PrivateKey rsaPrivateKey = rsaKeyPair.getPrivate();

This code snippet initializes a KeyPairGenerator with the RSA algorithm, sets the key size to 2048 bits, and generates the key pair. The public and private key are then retrieved from the generated KeyPair object.

Step 2: Encrypting Data with the Public Key

Once the key pair is generated, the public key is used to encrypt data.

// Prepare the data to be encrypted
String originalMessage = "Sensitive data to encrypt";
byte[] plaintextBytes = originalMessage.getBytes(StandardCharsets.UTF_8);

// Initialize the Cipher for encryption
Cipher encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);

// Perform the encryption
byte[] encryptedBytes = encryptCipher.doFinal(plaintextBytes);
// The encryptedBytes array now contains the ciphertext

This code creates a Cipher instance configured for RSA encryption with PKCS#1 padding. It is intiialized in encryption mode with the public key, and then used to encrypt the plaintext bytes.

Step 3: Decrypting Data with the Private Key

The final step involves using the private key to decrypt the data that was encrypted with its corresponding public key.

// Initialize a Cipher for decryption
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);

// Perform the decryption
byte[] decryptedBytes = decryptCipher.doFinal(encryptedBytes);

// Convert the decrypted bytes back to a String
String decryptedMessage = new String(decryptedBytes, StandardCharsets.UTF_8);
// decryptedMessage should now equal originalMessage

Here, a new Cipher instance is created for decryption, initialized with the private key. It processes the encrypted byte array to recover the original plaintext data.

Tags: Android rsa cryptography Public Key Encryption

Posted on Fri, 12 Jun 2026 17:14:39 +0000 by DylanBlitz