RSA Android encryption PHP decryption

Hi, I have recently used used RSA encryption to secure login in Android application which sends email and password of user to PHP server over http protocol. I am listing down code in Android and php for encryption and decryption over http. Feel free to comment in case you find any difficulty using it. So let’s see RSA Android encryption PHP decryption in 4 easy steps.

Step1: Create file in Android project. In we have method encrypt() to encrypt plain text. Download and copy bcprov-jdk16-1.45.jar in to your Android lib folder. Right click on jar and select add as library.

Here input to getUrlParamString() is String[] = { “param1”, “”, “param2”, “password}. Here Uri.Builder helps create URL in android.

package com.pgs.demoapp;

import android.util.Base64;
import android.util.Log;

import org.bouncycastle.openssl.PEMReader;


import javax.crypto.Cipher;

public class RSA {

    /** Method to create URL param **/
    public static String getUrlParamString(Object... param) {
        Uri.Builder biulder = Uri.parse("?").buildUpon();

        for (int i = 0; i < param.length; i = i + 2) {
            String key = String.valueOf(param[i]);
            String value = String.valueOf(param[i + 1]);
                try {
                    value = encrypt(value);
                    value = Uri.encode(value);
                } catch (Exception e) {
                    Log.e("Error", e.getMessage());
            biulder.appendQueryParameter(key, value);
    public static String encrypt(String data) throws Exception {
        byte[] decodedStr = data.getBytes();

        Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, strToPublicKey(PRIVATE));

        byte[] encryptedBytes = Base64.encode(cipher.doFinal(decodedStr), 0);
        return new String(encryptedBytes);

    public static PublicKey strToPublicKey(String s) {
        BufferedReader br = new BufferedReader(new StringReader(s));
        PEMReader pr = new PEMReader(br);
        KeyPair kp;
        try {
            kp = (KeyPair) pr.readObject();
        } catch (IOException e) {
        return kp.getPublic();

    private static String PRIVATE = "-----BEGIN RSA PRIVATE KEY-----\n" +
            "MIICXAIBAAKBgQC6cQBQTJ8scI+FlRqAa15IC6J91XSa4voi13hP0SwZo0iH8IGK\n" +
            "xlziTHUAUVRb6HemBOSXiBKfWKQfuBFsn44Qhcdcz8BWVohIqJyQ6kguZMio9DXJ\n" +
            "TM6U9dDmg6KpMdAK6Z85mfqOYAeNuyJm3e3h459mkXJz3EJh6ahs51Q4pwIDAQAB\n" +
            "AoGAHMxVmxGqyId+c8jLNijfgEtjxwIQp9gFgRo9OD78C92/11eb+t6W/FGJBQqK\n" +
            "+ENZL+izkoBvN/POLiQVdOzUWY9PhRwhSKc/cXUVlO5jJNb92SH6b/nQIFfLIpy9\n" +
            "j7cF0sVvhezxPCC7NTbVvPOE0IfATBQwFkI/45xL82XvpAkCQQDr6/lvLU04g2VB\n" +
            "pYoCundwK0oj9gpJQBSA3DG9poMl5ZPgJ0Zwrnqy1rM7F3hYdHYExjyMxDgwPV3d\n" +
            "hVAqTc8DAkEAyk7/pYCHkub0IVF1uLD2MyMLajgPOV5y521GCUZCTghpjSp7DWY/\n" +
            "yAOP+PnEFH09H0n1BpK1GdiCw/+3J9G8jQJAMUcr5b4HqCtB5jFmn2VFd2eDZ/mH\n" +
            "cn9xCO11clCqiirm9WYev4CiXmKcM1aWq5s/34VstlZyChl3VsL22K9B8wJARbmC\n" +
            "XEz27MdSXmVP2E6NG8S5O2uEu7X0jhRYLfwb//7gOfnpHQ4fb1Ti+uFCFfmv5ie8\n" +
            "Hf7UEctQDjMEseGURQJBAM3DnidBSRqMgdNTsJ46e5aUI/ajNjRANrRWTj0BRumR\n" +
            "n6xdkGacvg3AjH26WU0HBjeRaKo9/n0mDMqwc4lj37U=\n" +
            "-----END RSA PRIVATE KEY-----";

Step 2: GenerateKey.php on php server.. Download phpseclib PHP library in current folder and run following file to generate a pair of Public and Private Keys. This is to be run only once. Private key generated here is used in step 1.


set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');



if( file_exists('private.key') )
    echo base64_encode(file_get_contents('private.key'));
    $rsa = new Crypt_RSA();
    $res = $rsa->createKey(1024);
    $privateKey = $res['privatekey'];
    $publicKey  = $res['publickey'];
    file_put_contents('public.key', $publicKey);
    file_put_contents('private.key', $privateKey);
    echo base64_encode($privateKey);

Step 3: decrypt.php: This has utility method to decrypt given input text.


    function decrypt($encodedData){
    $rsa = new Crypt_RSA();
    $decodedData  = base64_decode($encodedData);
    $ciphertext = $rsa->decrypt($decodedData);

    return $ciphertext;

Step 4: UserLogin.php: This is the API which Android application will use for authentication.


if ( isset($_GET['param1']) &amp;&amp; isset($_GET['param2']) ){

require '/home/unbounded/public_html/security/decrypt.php';

$emailID =  decrypt(urldecode($_GET['param1']));
$pwd = decrypt(urldecode($_GET['param2']));

require '/home/unboudned/public_html/db/conn.php';

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$sql = "select * from tUser where emailID= '$emailID' and password = '$pwd'";

$rows = array();
$result = mysqli_query($conn, $sql);

while ($r = mysqli_fetch_assoc($result))
    $rows[] = $r;

print json_encode($rows);


Don’t forgot to comment if above code saved you few hours for RSA Android encryption PHP decryption.

(Visited 517 times, 1 visits today)

2 thoughts on “RSA Android encryption PHP decryption”

  1. Notice: Decryption error in /home2/hostName/public_html/xengine/magic/phpseclib1.0.13/Crypt/RSA.php on line 2516
    Hello I have problem for Decryption part
    encryption has no problem in client side but when request send with params I have this error at the top and cant decrypt it!

Leave a Reply

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

Solve : *
15 + 25 =