Android Apps

Android App Java RSA public Key Encryption and PHP server side Decryption

This is a simple RSA based secured algorithm to transfer valid data from your Android app to server. This works really well with a certain level of security, but still vulnerable to hack since we store the public key inside the app ( Please suggest a better solution if you have one ). You can follow the below steps.

Step 1: Here I use phpseclib library to decrypt the cipher. You can download the library from the below link.

http://phpseclib.sourceforge.net/

Step 2: Download the Bouncy castle library from the below link and import the package to your Android project.

http://www.bouncycastle.org/latest_releases.html

Screen Shot 2013 06 10 at 18.43.41 Android App Java RSA public Key Encryption and PHP server side  Decryption

Step 3: You can use the below code to generate public and private key from PHP Server. Import the phpseclib library. Some examples are provided in the phpseclib website.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
        header("Content-Type: text/html; charset=UTF-8");
 
        $rsa = new Crypt_RSA();
 
        $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);
 
        // Code to Generate the public key and private key
 
        $keys = $rsa->createKey(1024);
        extract($keys);
 
        // Base 64 encode Public and Private key
        $publicKeyBase = base64_encode( $publickey );
        $privateKeyBase = base64_encode( $privatekey );
 
        // Private key
        var_dump( $privateKeyBase );
 
        echo "---------------------------------------------------------</br>";
 
        // Public Key
        var_dump($publicKeyBase);

Step 4: Find the below code to encrypt the data from your android app. It is written as a class to file. Encrypt the data and send to the sever.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
 
import java.io.BufferedReader;
import java.io.StringReader;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.Security;
import javax.crypto.Cipher;
import org.bouncycastle.openssl.PEMReader;
import android.util.Base64;
import android.util.Log;
 
public class rsaEncryption {
 
	private String publicKey;  
 
	public rsaEncryption()
	{
		this.publicKey = this.getPublicKey(); 
 
	}
 
 
	/*
	 * Function to encrypt the data. 
	 * 
	 */
 
	public String encrypt( String data ) throws Exception
	{
 
 
 
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
 
 
		 byte[] keyBytes =   Base64.decode( this.publicKey, 0 );
 
		 PublicKey publickey       = strToPublicKey(new String(keyBytes));
		 cipher.init( Cipher.ENCRYPT_MODE , publickey );
 
	     // Base 64 encode the encrypted data 
	     byte[] encryptedBytes = Base64.encode( cipher.doFinal(data.getBytes()), 0 );
 
             return new String(encryptedBytes);
 
 
	}
 
 
	public static PublicKey strToPublicKey(String s)
    {
 
		PublicKey pbKey = null;
        try {
 
        	BufferedReader br   = new BufferedReader( new StringReader(s) );
            PEMReader pr        = new PEMReader(br);
            Object obj = pr.readObject(); 
 
            if( obj instanceof PublicKey )
            {
            	pbKey = (PublicKey) pr.readObject();
            }
            else if( obj instanceof KeyPair ) 
            {
            	KeyPair kp = (KeyPair) pr.readObject();
            	pbKey = kp.getPublic();
            }
            pr.close();
 
        }
        catch( Exception e )
        {
        	Log.d("CIPHER", e.getMessage() );
        }
 
        return pbKey;
    }
 
 
	private String getPublicKey()
	{
 
		// write a code to fetch it 
		// Base 64 encoded public key
		return "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0NCk1JR2ZNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0R05BRENCaVFLQmdRRE1PZGtaN28yMmJiSTAxZnY5QWtvMXFmTHd6MzRBYlA3ejgrcUMNCi9XZGNHdEFmdGk1QUFvZWUxOTV2NUd1QTZhak9JS3Y1cDkzdEdFNitWamdRdG03d0phS25kMno1UGpvZHIvc2R5bW9hNGdZT2dXcHQNCmVvamRybFZmeHZBbUxUN0JsWEExNGNuQUxDc3prYUtmTktSeEIrWDZlZGIyQkVaVnlKYThQcTBLYndJREFRQUINCi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQ==";
	}
 
}

Step 5: Decrypt the data with the below PHP code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
 
 
header("Content-Type: text/html; charset=UTF-8");
 
        $rsa = new Crypt_RSA();
 
        $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);
 
       $cipher = base64_decode("EKdWTzVOkBcBd9S9TxsvZ/A0Vrj3lOfWddjQNKHCKt8zdJr3WioRC/8tu5xZLTooBh9Mb/c06+FjFNdqlf2F7hpjl+ZpNsxdKich3h/wLcMYYWoDbKoKg80Scw0YNyht0w0iWsLGKZXu7TWqH5wNWIx4KxQJtqJB6XPVJVjigq8=");
       $privateKey = base64_decode("LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQ0KTUlJQ1hRSUJBQUtCZ1FETU9ka1o3bzIyYmJJMDFmdjlBa28xcWZMd3ozNEFiUDd6OCtxQy9XZGNHdEFmdGk1QUFvZWUxOTV2NUd1QQ0KNmFqT0lLdjVwOTN0R0U2K1ZqZ1F0bTd3SmFLbmQyejVQam9kci9zZHltb2E0Z1lPZ1dwdGVvamRybFZmeHZBbUxUN0JsWEExNGNuQQ0KTENzemthS2ZOS1J4QitYNmVkYjJCRVpWeUphOFBxMEtid0lEQVFBQkFvR0FFd2ZVOWppbmxmZFU0dDJKMU1MUTNYMVB1U2JzcStkOA0KUG9sZE1nV2hDeEVva2J2dFJXTzI5Wk5TRkFVcUMySTZxN0tacy9Mem1ETnFxd3ZudjQ3d2VWK3FIZGJSZ1hhUHFFSTdMSTE3SFRPRQ0KdldKSnVNdWlrSFlhbEw5dEpiV24rdktlaEFzN2w4QmEwQUR5MnJDbTJrWnNBUkNZTHhvU01iejBWTUNvdFdrQ1FRRHgwZzlja0lKNw0KMmFLcUlWN1l1VkE5dTUyaDBVRGJSZ25OMkZuY0grcnFGNWg4VVFXUk1SSzAvUFJMcFZvNzBwa1k2bCt2eDMwQkY4Vnd3Q1RJMGtHdA0KQWtFQTJETjEwVnpPOUV3b1IzcE9ITUZucE93TERQNEhOeDV3Rk5menJwODQ3RTlBZHIvcnRDdGxLRVBuZ1RvYjlDK1Q0eVppTngrZg0KMFo3L3Qwa0FUT3dZQ3dKQkFOTzcwTFdFMXF0b29SUUVDZzhMRzJZaUsyQnZYekZmZnVBY3lubUIvT2VoWjJPYWNaeHljbVhFZ29ibA0Kcmo5cEk2SDhQWElrNHFBZFYwUmxDUkJKZ1RVQ1FHVFdnNkkxdmxVVlhFZ1NWSEozQm9kV2pNVHZpcC83czEwVmFCUFBNYmFPTkV2dQ0Kc2Ruano1ZWJMRlFLclZVVUI4OFBiUW0yMTB6bTh2QWl2V0FqVWdjQ1FRQ3hXWmFKam9OU1ovU2ExV1RESUZZdVh0aDk5V1hvK1lsaA0KUUVKUjZSM01WamxmVzEyUERGY0xmeG1YdEtjdGV1Qk14a2U1N2s2clE2RHh3cThUQS81NA0KLS0tLS1FTkQgUlNBIFBSSVZBVEUgS0VZLS0tLS0=");
 
        // Decryption
        $rsa->loadKey($privateKey);
        echo $rsa->decrypt($cipher);

Tagged , ,

Share this to

Related Posts

13 Comments

  1. @touAug 21, 2013 at 8:13 amReply

    From this topic,I want to know how to decryption by private_key.der on android app

    Thank

  2. derdusJan 28, 2014 at 9:12 amReply

    Thanks for the tutorial. however, i downloaded the bouncycastle library but there is an error at line 8 of step 4. kindly help

    • Sarath DRJan 29, 2014 at 12:30 pmReplyAuthor

      Have you imported the jar file and cleared the project ?

  3. derdusFeb 6, 2014 at 9:21 amReply

    I got the right jar file, and i can download the keys from my php server. however, there is an error that org.bouncycastle.jce.provider. class not found. again i ask, the —–BEGIN PUBLIC KEY—– and —–END PUBLIC KEY—– part of the key?
    because wen i remove the encoding function, i see that!

    here is my fool code
    my class:
    package com.cd.crashdata;

    import java.io.BufferedReader;
    import java.io.StringReader;
    import java.security.KeyPair;
    import java.security.PublicKey;
    import java.security.Security;
    import javax.crypto.Cipher;
    //import org.bouncycastle.openssl.PEMReader;
    import android.util.Base64;
    import android.util.Log;

    public class rsaEncryption {

    private String publicKey;

    public rsaEncryption(String key) {

    this.publicKey = key;

    }

    /*
    * Function to encrypt the data.
    */

    public String encrypt(String data, String pKey) throws Exception {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    Cipher cipher = Cipher.getInstance(
    “RSA/None/OAEPWithSHA1AndMGF1Padding”, “BC”);

    byte[] keyBytes = Base64.decode(pKey, 0);

    PublicKey publickey = strToPublicKey(new String(keyBytes));
    cipher.init(Cipher.ENCRYPT_MODE, publickey);

    Base 64 encode the encrypted data
    byte[] encryptedBytes = Base64.encode(cipher.doFinal(data.getBytes()),
    0);

    return new String(encryptedBytes);

    }

    public static PublicKey strToPublicKey(String s) {

    PublicKey pbKey = null;
    try {

    BufferedReader br = new BufferedReader(new StringReader(s));
    PEMReader pr = new PEMReader(br);
    Object obj = pr.readObject();

    if (obj instanceof PublicKey) {
    pbKey = (PublicKey) pr.readObject();
    } else if (obj instanceof KeyPair) {
    KeyPair kp = (KeyPair) pr.readObject();
    pbKey = kp.getPublic();
    }
    pr.close();

    } catch (Exception e) {
    Log.d(“CIPHER”, e.getMessage());
    }

    return pbKey;
    }

    private String getPublicKey() {

    return publicKey;
    // write a code to fetch it
    // Base 64 encoded public key
    // return
    // “LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0NCk1JR2ZNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0R05BRENCaVFLQmdRRE1PZGtaN28yMmJiSTAxZnY5QWtvMXFmTHd6MzRBYlA3ejgrcUMNCi9XZGNHdEFmdGk1QUFvZWUxOTV2NUd1QTZhak9JS3Y1cDkzdEdFNitWamdRdG03d0phS25kMno1UGpvZHIvc2R5bW9hNGdZT2dXcHQNCmVvamRybFZmeHZBbUxUN0JsWEExNGNuQUxDc3prYUtmTktSeEIrWDZlZGIyQkVaVnlKYThQcTBLYndJREFRQUINCi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQ==”;
    }

    }

    my android activity:

    package com.cd.crashdata;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.security.InvalidKeyException;
    import java.security.Key;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.ArrayList;
    import java.util.List;
    import android.util.Base64;

    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.ConnectTimeoutException;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;

    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Bundle;
    import android.os.Looper;
    import android.provider.Settings;
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class Login extends Activity {
    EditText txt_police_no, txt_password;
    Button btn_login;
    String username, password, RSA_PRIVATE_KEY;
    String http_req_result, test_login_feedback;
    Login _this;

    // String key =
    // “MIICWwIBAAKBgQDVIJ8H3Oszc5fWdgpwymWksF1WxkXJHIfdS6Ta1bHeqwEzPIkN f3iVk14LfaoSZpRb9Yvi/jvkXxIzJbHq6aKfnQOC6tKIiixvVvpCfxr1eV4urDdz H9RNy9bqGdXzTQdgQi+KRx0Dcy9RNsl7ZGLAGrUFRnPI4GTdH+7wm4QogQIDAQAB AoGAcUcKX7KC7HDm5h0NRY+94H/AzItLsi3Q5MT81Tc5d+EqHSJysdLrs4yFMtRS 3b7Z4dqrxDVefe4uDTNe0j3lqboKz8oKwAU+paKx3wubHb7aeQnfzwM9mPQJHgEO zBjlvbL4oEa/gklu3VohZAc1daqpPajdWuOQQp4S+jUllrECQQDrITlSjvkxt8ud /vYIcEXHew3iW4nzaAH3z4PRAGZofRpk/OusGZ6cdZoYMTZcdxYTCCbZ5eeyGukW 5QCadie1AkEA6Atx8Z0F7WhLI2lGvCGy+vIOL0vBDZSma0cvLYLAXMx8duoWQ9J2 LwT7SsnRXMeq/8wlNHL7mFEf+YFZBKKlHQJAO78kfrr/zUdjwREBWaGVyZuWKpeS FTyvi1W6rAgK/bAUXeb6x69241DqyAzxQEuuW0WuAZ5u4o39/qhQH++4JQJAAepe RW1TaDNNM3yh/dmVXabz4QYSEOeiPA55YDnNFrcFbAHgryyklxzGakaiOM7ZJYVs 5TLxyr8YsXmU34nsLQJALzC8CaFXJcnU0+6+KoKX7iq1aP3X4LgP4Gianix6pfRo aV8UHnfFLRSgPdn1ZYmKtJfnsJXJYoE+o9xEErb5EQ==”;

    // String str =
    // “MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDWtJ/7+dzfSk3EC04PIpdaF0e T1Xr9fOFQVVcF6FokfJtxugs/NbcuPj86UDvIpdrWI2ztqyX7L7/PSQIdjvkATxs eI1dfdYJ5+aW0J5g80cJqNdL4Rr2APhUv9CJUHApUdT8q27p1xUgbgZ/ERjy5Anc HGaRJwBWBcW3CboomwIDAQAB”;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    _this = this;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    txt_police_no = (EditText) findViewById(R.id.txt_police_no);
    txt_password = (EditText) findViewById(R.id.txt_password);
    btn_login = (Button) findViewById(R.id.btn_login);

    addListenerToLoginButton();

    fetchRsaKey(“pri_key”);

    // Log.d(“res”, “5 ” + RSA_PRIVATE_KEY);
    }

    public String encryptWithPrivateKey(String plaintext) {

    String encoded = null;
    byte[] encrypted = null;

    try {
    Log.e(“track”, “key ” + RSA_PRIVATE_KEY);
    String privKeyPEM = RSA_PRIVATE_KEY;
    byte[] decoded = Base64.decode(privKeyPEM, Base64.DEFAULT);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
    KeyFactory kf = KeyFactory.getInstance(“RSA”);
    PrivateKey privKey = kf.generatePrivate(spec);

    Cipher cipher = Cipher.getInstance(“RSA/ECB/PKCS1Padding”);
    cipher.init(Cipher.ENCRYPT_MODE, privKey);

    encrypted = cipher.doFinal(plaintext.getBytes());

    Log.e(“track”, “encrypted ” + encrypted.toString());
    encoded = Base64.encodeToString(encrypted, Base64.DEFAULT);
    } catch (Exception e) {
    e.printStackTrace();
    }

    return encoded;

    }

    public void saveJobNumber(String job_number) {

    SharedPreferences sp = getSharedPreferences(Utilities.JOB_NO, 1);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString(“job_no”, job_number);
    editor.commit();
    }

    /*
    * private String encryptWithPublicKey(byte[] message, String publicKey)
    * throws Exception { String strippedKey =
    * Crypto.stripPublicKeyHeaders(publicKey); PublicKey apiPublicKey=
    * Crypto.getRSAPublicKeyFromString(strippedKey); Cipher rsaCipher =
    * Cipher.getInstance(“RSA/ECB/OAEPWithSHA1AndMGF1Padding”, “SC”);
    * rsaCipher.init(Cipher.ENCRYPT_MODE, apiPublicKey); return
    * rsaCipher.doFinal(message).toString(); }
    */

    public String encrypt(String key, String original) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    byte[] encodedKey = key.getBytes();

    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
    KeyFactory kf = KeyFactory.getInstance(“RSA”);
    PublicKey pkPublic = kf.generatePublic(publicKeySpec);

    Cipher pkCipher = Cipher.getInstance(“RSA/ECB/PKCS1PADDING”);
    pkCipher.init(Cipher.ENCRYPT_MODE, pkPublic);
    byte[] encryptedInByte = pkCipher.doFinal(original.getBytes());

    //String encryptedInString = new String(Base64.encode(encryptedInByte));
    String encryptedInString = Base64.encodeToString(encryptedInByte, Base64.NO_WRAP);

    return encryptedInString;
    }

    public void addListenerToLoginButton() {
    btn_login.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub

    // Log.d(“res”, “5 ” + RSA_PRIVATE_KEY);

    // rsaEncryption rsaEncryptionObj = new
    // rsaEncryption(RSA_PRIVATE_KEY);
    username = txt_police_no.getText().toString().trim();
    password = txt_password.getText().toString().trim();

    saveJobNumber(username);// save police job number to shared
    // preference.

    Log.i(“test”, “u ” + username);
    Log.i(“test”, “p ” + password);

    Log.e(“track “, “1″);

    String cipherUsername = “”;
    String cipherPassword = “”;
    Log.e(“track “, “2″);

    Log.e(“track “, “3″);
    try{
    cipherUsername = encrypt(RSA_PRIVATE_KEY,username);
    Log.e(“track “, “4″);
    cipherPassword = encrypt(RSA_PRIVATE_KEY,password);
    }catch(Exception e){
    e.getStackTrace();
    }

    Log.e(“track “, “5″);

    Log.i(“test”, “ue ” + cipherUsername);
    Log.i(“test”, “pe ” + cipherPassword);

    sendEncryptedData(cipherUsername, cipherPassword);

    }
    });

    }

    public String encrypt(String pin) {
    String key = RSA_PRIVATE_KEY;
    String encryptedBase64PIN = “”;
    byte[] sigBytes2 = Base64.decode(key, Base64.DEFAULT);
    Log.e(“track”, “new key is: ” + key);
    try {
    PublicKey publicKey = KeyFactory.getInstance(“RSA”).generatePublic(
    new X509EncodedKeySpec(sigBytes2));
    encryptedBase64PIN = encode(publicKey, pin);
    Log.e(“track”, “encoded key is: ” + encryptedBase64PIN);
    // getSecToken();
    } catch (Exception e) {
    Log.e(“track”, “error is: ” + e.getMessage().toString());
    }

    return encryptedBase64PIN;
    }

    public static String encode(Key publicKey, String data)
    throws NoSuchAlgorithmException, NoSuchPaddingException,
    InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    byte[] byteData = data.getBytes(); // convert string to byte array

    Cipher cipher = Cipher.getInstance(“RSA/ECB/NoPadding”);
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] encryptedByteData = cipher.doFinal(byteData);

    String s = Base64.encodeToString(encryptedByteData, Base64.NO_WRAP);
    return s; // convert encrypted byte array to string and return it
    }

    public void sendEncryptedData(final String cipherUsername,
    final String cipherPassword) {

    if (isOnline()) {

    // servercode comes here
    Thread trd = new Thread(new Runnable() {

    @Override
    public void run() {
    // TODO Auto-generated method stub
    Log.e(“Registration”,
    “gone to connectin class with url starting…1″);
    Looper.prepare();

    final String url = Utilities.SEND_ENCRYPTED_DATA;

    Log.e(“Registration”, “gone to connectin class with url ”
    + url);

    HttpResponse response = null;
    // code to do the HTTP request
    InputStream is = null;
    // String result;
    Log.d(“res”, “in addListenerToButton func 5″);
    // Creating HTTP client
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams
    .setConnectionTimeout(httpParams, 13000);
    Log.d(“res”, “in addListenerToButton func 6″);

    HttpClient httpClient = new DefaultHttpClient(httpParams);
    Log.d(“res”, “in addListenerToButton func 7″);

    // Creating HTTP Post
    HttpPost httpPost = new HttpPost(url);

    Log.d(“res”, “in addListenerToButton func 8″);
    List nameValuePair = new ArrayList(
    1);
    Log.d(“res”, “in addListenerToButton func 7″);

    nameValuePair.add(new BasicNameValuePair(“cipherUsername”,
    cipherUsername));
    nameValuePair.add(new BasicNameValuePair(“cipherPassword”,
    cipherPassword));

    Log.d(“res”, “in addListenerToButton func 9″);
    try {
    httpPost.setEntity(new UrlEncodedFormEntity(
    nameValuePair));
    } catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
    }

    try {
    response = httpClient.execute(httpPost);

    HttpEntity entity = response.getEntity();

    is = entity.getContent();

    // writing response to log
    Log.d(“res”, “1 ” + response.toString());

    } catch (ConnectTimeoutException ctEx) {

    Toast.makeText(getApplicationContext(),
    “Server not responding”, Toast.LENGTH_LONG)
    .show();
    } catch (Exception e) {
    // writing exception to log
    Log.d(“res”, “2 ” + e.toString());
    // e.printStackTrace();
    }

    try {

    BufferedReader reader = new BufferedReader(
    new InputStreamReader(is, “iso-8859-1″), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {

    sb.append(line + “\n”);

    }

    is.close();

    test_login_feedback = sb.toString();

    Log.d(“res”, “4 ” + test_login_feedback);

    // changes to gui can be done on the UI thread

    runOnUiThread(new Runnable() {
    @Override
    public void run() {
    // do stuff on main GUI here
    // generated this stuff
    /*
    *
    *
    *
    */

    Toast.makeText(_this, test_login_feedback,
    Toast.LENGTH_LONG).show();

    }
    });

    Log.d(“res”, “in function populate 1″);
    // Log.d(“res”, “Count is ” +
    // String.valueOf(str.length()));

    } catch (Exception e) {
    Log.e(“log_tag”,
    “Error converting result ” + e.toString());
    }
    // Looper.loop();

    }

    });

    trd.start();

    } else {

    String dialogTitle = getResources().getString(
    R.string.no_internet_connection);
    String dialogBody = getResources().getString(
    R.string.enable_data_or_leave_airplane_mode);
    String negativeBtnLabel = getResources().getString(R.string.cancel);
    String positiveBtnLabel = getResources().getString(
    R.string.settings);
    final String settingArea = Settings.ACTION_AIRPLANE_MODE_SETTINGS;
    promptUserToCreateGoogleAccount(dialogTitle, dialogBody,
    negativeBtnLabel, positiveBtnLabel, settingArea);

    }

    }

    public String fetchRsaKey(final String rsaStr) {

    if (isOnline()) {

    // servercode comes here
    Thread trd = new Thread(new Runnable() {

    @Override
    public void run() {
    // TODO Auto-generated method stub
    Log.e(“Registration”,
    “gone to connectin class with url starting…1″);
    Looper.prepare();

    final String url = Utilities.RSA_KEY_REQUEST;

    Log.e(“Registration”, “gone to connectin class with url ”
    + url);

    HttpResponse response = null;
    // code to do the HTTP request
    InputStream is = null;
    // String result;
    Log.d(“res”, “in addListenerToButton func 5″);
    // Creating HTTP client
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams
    .setConnectionTimeout(httpParams, 13000);
    Log.d(“res”, “in addListenerToButton func 6″);

    HttpClient httpClient = new DefaultHttpClient(httpParams);
    Log.d(“res”, “in addListenerToButton func 7″);

    // Creating HTTP Post
    HttpPost httpPost = new HttpPost(url);

    Log.d(“res”, “in addListenerToButton func 8″);
    List nameValuePair = new ArrayList(
    1);
    Log.d(“res”, “in addListenerToButton func 7″);

    nameValuePair.add(new BasicNameValuePair(“vReg”, rsaStr));

    Log.d(“res”, “in addListenerToButton func 9″);
    try {
    httpPost.setEntity(new UrlEncodedFormEntity(
    nameValuePair));
    } catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
    }

    try {
    response = httpClient.execute(httpPost);

    HttpEntity entity = response.getEntity();

    is = entity.getContent();

    // writing response to log
    Log.d(“res”, “1 ” + response.toString());

    } catch (ConnectTimeoutException ctEx) {

    Toast.makeText(getApplicationContext(),
    “Server not responding”, Toast.LENGTH_LONG)
    .show();
    } catch (Exception e) {
    // writing exception to log
    Log.d(“res”, “2 ” + e.toString());
    // e.printStackTrace();
    }

    try {

    BufferedReader reader = new BufferedReader(
    new InputStreamReader(is, “iso-8859-1″), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {

    sb.append(line + “\n”);

    }

    is.close();

    http_req_result = sb.toString();

    Log.d(“res”, “4 ” + http_req_result);
    RSA_PRIVATE_KEY = http_req_result;

    // changes to gui can be done on the UI thread

    runOnUiThread(new Runnable() {
    @Override
    public void run() {
    // do stuff on main GUI here
    // generated this stuff
    /*
    *
    *
    *
    */

    Toast.makeText(_this, http_req_result,
    Toast.LENGTH_LONG).show();

    }
    });

    Log.d(“res”, “in function populate 1″);
    // Log.d(“res”, “Count is ” +
    // String.valueOf(str.length()));

    } catch (Exception e) {
    Log.e(“log_tag”,
    “Error converting result ” + e.toString());
    }
    // Looper.loop();

    }

    });

    trd.start();

    } else {

    String dialogTitle = getResources().getString(
    R.string.no_internet_connection);
    String dialogBody = getResources().getString(
    R.string.enable_data_or_leave_airplane_mode);
    String negativeBtnLabel = getResources().getString(R.string.cancel);
    String positiveBtnLabel = getResources().getString(
    R.string.settings);
    final String settingArea = Settings.ACTION_AIRPLANE_MODE_SETTINGS;
    promptUserToCreateGoogleAccount(dialogTitle, dialogBody,
    negativeBtnLabel, positiveBtnLabel, settingArea);

    }

    return http_req_result;

    }

    public void promptUserToCreateGoogleAccount(String dialogTitle,
    String dialogBody, String negativeBtnLabel,
    String positiveBtnLabel, final String settingArea) {
    // TODO Auto-generated method stub
    // setResult(account);
    AlertDialog.Builder settingsAlert = new AlertDialog.Builder(_this);

    // Setting Dialog Title
    settingsAlert.setTitle(dialogTitle);
    // Setting Dialog Message
    settingsAlert.setMessage(dialogBody);
    // On pressing Settings button
    settingsAlert.setPositiveButton(positiveBtnLabel,
    new DialogInterface.OnClickListener() {
    // On pressing Settings button
    @Override
    public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    Intent intent = new Intent(settingArea);

    _this.startActivity(intent);

    }
    });

    // on pressing cancel button
    settingsAlert.setNegativeButton(negativeBtnLabel,
    new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
    dialog.cancel();
    }
    });
    settingsAlert.show();

    }

    public boolean isOnline() {

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnectedOrConnecting()) {

    return true;
    }
    return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_login, menu);
    return true;
    }

    }

  4. derdusFeb 6, 2014 at 9:22 amReply

    there are many useless functions in the code, don mind them

  5. JonathanFeb 23, 2014 at 8:44 pmReply

    Thank you so much! You helped me so much with this!

  6. nyleaMar 1, 2014 at 5:54 pmReply

    I have tried your code. I am stuck at one point. I cannot get required public key in obj. there is no error and no warning but null is returned in publickey. please can you help?

  7. JoeMar 2, 2014 at 6:17 pmReply

    I get an InvalidKeyException; Unknown key type passed to RSA. Do you have an idea what might have caused this error?

  8. Sarath DRMar 2, 2014 at 6:44 pmReplyAuthor

    Which line did you get the exception ?

  9. JoeMar 2, 2014 at 6:58 pmReply

    Line 46. It is the encryption: cipher.init( Cipher.ENCRYPT_MODE , publickey );
    I used the Base64 encoded public Key.

  10. gouravMar 15, 2015 at 7:26 pmReply

    i get an java.lang.IllegalArgumentException: not an RSA key!
    at org.bouncycastle.jce.provider.JCERSACipher.engineGetKeySize(Unknown Source)
    at javax.crypto.Cipher.passCryptoPermCheck(Cipher.java:1067)

    at cipher.init( Cipher.ENCRYPT_MODE , publickey );
    in step 4

  11. MukundJan 30, 2016 at 6:37 amReply

    How to use above phpseclib to encrypt data in IOS like java/android
    Can anyone please give example to encrypt in IOS and decrypt in PHP using above library

  12. OmidNov 19, 2016 at 7:55 pmReply

    Hi
    How do i load private key in java and decrypt data?

Leave a reply

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

*

About
View Sarath D R's profile on LinkedIn

I am a technology consultant and an entrepreneur focused on the following technologies Java,Spring, Android, Angular, Asterisk, Symfony, Cake , Code-Igniter, Jquery , XAMPP, XHTML, AJAX, MySql, Seo, Web Design, Wordpress, iPhone development.

Today’s Tips
  • Generate Codova.jar file from Phonegap project using ant
  • Google map javascript client  to find the geographic co-ordinates  from  Address or post code
  • Update Android main UI from Webview – Phonegap Plugin
  • Jplayer is not working  with HTC One Android 4.3 version browser
  • Regular expression to validate mobile phone numbers starting with + ( plus ) – php
  • Simple pagination script for PHP
  • Useful adb ( Android Debug Bridge ) commands
  • Change the javascript files url to absolute url – Symfony 1.4
  • Set Http authentication header from Client – PHP / CURL

This site uses cookies from Google to deliver its services, to personalise ads and to analyse traffic. Information about your use of this site is shared with Google. By using this site, you agree to its use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.This site also uses cookies from Google to deliver its services, to personalise ads and to analyse traffic. Information about your use of this site is shared with Google. By using this site, you agree to its use of cookies.

Close