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 RSA.java file in Android project. In RSA.java 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”, “prakash@unbounded.in”, “param2”, “password}. Here Uri.Builder helps create URL in android.

package com.pgs.demoapp;

import android.net.Uri;
import android.util.Base64;
import android.util.Log;

import org.bouncycastle.openssl.PEMReader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.security.KeyPair;
import java.security.PublicKey;

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);
        }
        return biulder.build().toString();
    }
    
    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) {
            e.printStackTrace();
        }
        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.

<?php

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

include('/home/unbuonded/public_html/security/phpseclib1.0.13/Net/SSH2.php');
include('/home/unbuonded/public_html/security/phpseclib1.0.13/Math/BigInteger.php');

include('/home/unbuonded/public_html/security/phpseclib1.0.13/Crypt/RSA.php');


set_time_limit(0);
if( file_exists('private.key') )
{
    echo base64_encode(file_get_contents('private.key'));
}
else
{
 
    $rsa = new Crypt_RSA();
    $rsa->setHash('sha1');
    $rsa->setMGFHash('sha1');
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
    $rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
    $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
 
    $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.

<?php
    include('/home/unbounded/public_html/security/phpseclib1.0.13/Math/BigInteger.php');

    include('/home/unbounded/public_html/security/phpseclib1.0.13/Crypt/RSA.php');
    
    set_time_limit(0);
 
    function decrypt($encodedData){
 
    $rsa = new Crypt_RSA();
    $rsa->setHash('sha1');
    $rsa->setMGFHash('sha1');
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
 
    $rsa->loadKey(file_get_contents('/home/unbounded/public_html/security/private.key'));
 
    $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.

<?php

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);
$conn->close();
}

?>

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

(Visited 188 times, 1 visits today)

PrAkAsH

Eyeing investment. Please note that the views given in this website are meant for reference and guidance of the readers to explore further on the topics and take informed decisions. These should not be construed as investment advice or legal opinion.

You may also like...

2 Responses

  1. hamed says:

    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 : *
21 + 22 =