0

How to encrypt/decrypt public/private .

I am assuming that means the key is dynamic and never the same for a string.

I would like to know if there is any library for doing so or step by step tutorial to allow a beginner to understand and implement in a an app.

I would like to secure password in http example:

http://www.example.com/username="ENCRYPTED1"+Password="ENCRYPTED2"

Encrypted 1 and 2 is dynamic and never same.

by the method above and the key should always changes hence even if you type the encryption key in the browser it should not allow as the key would have changed .

I am hoping this is the right path .

I looked in to Spongy castle and I did not understand how to implement the same.

Please help me out and guide me.

Thanks in Advance.

Code :

public class CustomizedListView extends Activity {
    // All static variables
    static final String URL = "http://example.com/getmsgs/userno=123";
    // XML node keys
    static final String KEY_SONG = "song"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_ARTIST = "artist";
    static final String KEY_DURATION = "duration";
    static final String KEY_THUMB_URL = "thumb_url";

    ListView list;
    LazyAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

        JSONObject json = JSONfunctions.getJSONfromURL(URL);


        try {
            JSONObject arr2 = json.getJSONObject("feed");
            JSONArray arr = arr2.getJSONArray("entry");

            for (int i = 0; i < arr.length(); i++) {
                JSONObject e1 = arr.getJSONObject(i);

                JSONArray arr3 = e1.getJSONArray("im:image");

                JSONObject arr8 = e1.getJSONObject("im:name");

                JSONObject arr10 = e1.getJSONObject("im:artist");

                    JSONObject e12 = arr3.getJSONObject(0);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            map.put(KEY_THUMB_URL,  e12.getString("label"));

            map.put(KEY_ARTIST, arr8.getString("label"));
            map.put(KEY_TITLE, arr10.getString("label"));
            // adding HashList to ArrayList
            songsList.add(map);
            }

        } catch (JSONException e) {
            // Log.e("log_tag", "Error parsing data "+e.toString());
            Toast.makeText(getBaseContext(),
                    "Network communication error!", 5).show();
        }


        list=(ListView)findViewById(R.id.list);

        // Getting adapter by passing xml data ArrayList
        adapter=new LazyAdapter(this, songsList);        
        list.setAdapter(adapter);

        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {


                HashMap<String, String> o = (HashMap<String, String>) list.getItemAtPosition(position);
                Toast.makeText(CustomizedListView.this, "ID '" + o.get("KEY_TITLE") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

            }
        });     
    }   
}

PHP Code:

<?php

$strno=$_GET['strno'];

if (isset($strno))
{
        $connect=mysql_connect("localhost","test","test") or die ('Connection error!!!');
        mysql_select_db("test") or die ('Database error!!!');

    $query=mysql_query("select sno FROM users  where strno='$strno';");
    while($row = mysql_fetch_assoc($query))

    {
        $jsonoutput='{"json":{
            "msg_sub":"'.$row['msg_sub'].'",
            }}';
    }

}

echo trim($jsonoutput);
mysql_close($connect) or die ('Unable to close connection-error!!!');
}

?>

JSONfunctions.java

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }

      //convert response to string
        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();
            result=sb.toString();
    }catch(Exception e){
            Log.w("log_tag", "Error converting result "+e.toString());
    }

    try{

        jArray = new JSONObject(result);            
    }catch(JSONException e){
            Log.w("log_tag", "Error parsing data "+e.toString());
    }

    return jArray;
}

}

2 Answers2

3

I am hoping this is the right path .

You're way off track.

Instead of creating your own protocol, use SSL/HTTPS, the client can then send their username and password as usual through POST request (except it's done over HTTPS).

Alternatively, you can do "mutual authentication". This means that both the client and the server are authenticated using their public key (with HTTPS, only the server is authenticated with their certificate/public key).

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
  • Thank You Sir for your response.I am using jsonFunctions.java for parsing the data and the code looks something like **JsonObject obj=jsonFunction.getjsonfromurl("http://www.example.com/username="ENCRYPTED1"+Password="ENCRYPTED2");** Currently this is my code in android .I would like to have dynamic encryption to it and also there is no session in my php (I hope that's alright).I would like to know where to proceed or what I need to read to implement what is required.Currently I am stumped and don't know where to start.Any guidance in the right path will help me a great deal.Thanks again. – James Patrick Apr 25 '13 at 05:32
  • @JamesPatrick Hey as you noted here that you are using `JSON`.so try to send your data in `JSON object` vai `HTTP POST` so that will encode your data as well as `POST` will hide your params. so don't worry about that. – Chintan Khetiya Apr 25 '13 at 05:37
  • I have added the code above and here I would like to encrypt userno ie: **123** – James Patrick Apr 25 '13 at 05:42
  • @JamesPatrick: another option other than sending the username/password as JSON in your POST body is to put the username/password as "X-prefix" HTTP Header. It's fine to send them in the header/request body as plain text if you use HTTPS because HTTPS encrypts headers and request body and prevent eavesdropper from getting the username/password. – Lie Ryan Apr 25 '13 at 05:44
  • both android/PHP Code as above .Please suggest me the right path to encrypt/decrypt dynamically – James Patrick Apr 25 '13 at 05:44
  • @LieRyan Hello Sir Can you please add or edit the above code or suggest any link to do so.I have added entire code here do you also want jsonFunctions.java file ?? – James Patrick Apr 25 '13 at 05:47
  • @LieRyan Sorry Sir I did not follow. – James Patrick Apr 25 '13 at 05:54
  • @chintankhetiya How do I change the above code.I have provided everything I am using.Reallyappreciate any help. – James Patrick Apr 25 '13 at 05:54
  • @JamesPatrick see http://stackoverflow.com/questions/13134019/http-post-method-passing-null-values-to-the-server/13134287#13134287 here i have post my answer and change according your needs. – Chintan Khetiya Apr 25 '13 at 06:11
  • @JamesPatrick: use [HttpURLConnection](https://developer.android.com/reference/java/net/HttpURLConnection.html), then use either 1) `setRequestProperty()` to set HTTP Header or 2) [HTTP Basic Auth with Authenticator](https://developer.android.com/reference/java/net/Authenticator.html) or 3) `setDoOutput()`+`getOutputStream()` to send JSON on the POST request body; simply replace "http://" in your URL to "https://" for encryption. You'll also need to set your web server to handle HTTPS, consult your web servers documentation for this. – Lie Ryan Apr 25 '13 at 06:12
  • @LieRyan An example or link will help me a great deal also do I need to save any certificate for that ?? Also is the certificate free ??? Just curious I guess I have seen something similar in mail exchange app but not really sure if thats the same. – James Patrick Apr 25 '13 at 06:22
  • @chintankhetiya can you also give the php(Server side code) I will post my jsonfunction code I have implemented everywhere in the app Hope I make very less changes in the code. – James Patrick Apr 25 '13 at 06:25
  • @LieRyan http://stackoverflow.com/questions/12471999/rsa-encryption-decryption-in-android should I look into this ??? Your opinion will help me a ton. – James Patrick Apr 25 '13 at 06:26
  • @JamesPatrick: since you control both the client and the server, you can use self-signed certificate chain (free); however a couple extra steps will be needed to let HttpURLConnection know to trust the certificate chain. See [HttpsURLConnection](https://developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html) on installing custom X509TrustManager. – Lie Ryan Apr 25 '13 at 06:32
  • I have posted jsonFunctions.java code above .PLease let me know whre to do necessary changes everywhere .The code pasted above has java/php/jsonparser . How to make effective and quick changes to the framework above ?? – James Patrick Apr 25 '13 at 06:37
  • @JamesPatrick: no you don't want to deal with RSA yourself. RSA by itself is not sufficient to ensure secure communication, you also need handshakes and key management which is difficult to implement correctly yourself. Fortunately that's all transparently handled within HTTPS, so just use HTTPS. – Lie Ryan Apr 25 '13 at 06:41
  • @JamesPatrick this is http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php good for you.btw from android side my code is okay so you just need to check PHP code. – Chintan Khetiya Apr 25 '13 at 06:41
  • @LieRyan Also if I paste '(**https: //example.com/getmsgs/userno=123**)' in the browser it is not supposed let me through ?? will that happen ?? – James Patrick Apr 25 '13 at 06:47
  • if it does then its not secure as I can view any users msgs – James Patrick Apr 25 '13 at 06:49
  • @JamesPatrick: then don't put it in the URL. Anyway, consider who you're protecting against; if you use HTTPS eavesdropper will not be able to intercept any communication between the client and the server, while protecting the username/password against your own user is stupid/pointless, they already know their own password anyway. – Lie Ryan Apr 25 '13 at 06:50
  • My question is if I paste the URL above in the browser I still get echo msgs .Will that be secured too ? In the sense that url should not work else any one who knows the link can get the msgs . Sir Did I put across my concern clearly ? Else I need to execute the url only if its sent from android apk and not from browser .Is that possible ??? Sorry for the trouble. – James Patrick Apr 25 '13 at 08:01
  • @JamesPatrick: then fix your server-side code, make it to actually check the username/password and don't put your username and password in the URL. – Lie Ryan Apr 25 '13 at 08:03
  • How do I know if the call is made from android only ?? I have tried many things lie secure id ,app id and stuff but nothing is constant and everything changes and hence I cannot use that .I cannot even use session so only way left is to encrypt the data .Well thats how I have reached at this point I have the app with functionality but now I need to work on securing calls which I never did and its my first app so this would be my first time too. – James Patrick Apr 25 '13 at 08:06
  • oh how I check username and password without putting in the url ?? I never knew thats possible ?? If that working then it solves my problem.What changes should I do in the above code ?? – James Patrick Apr 25 '13 at 08:07
  • @JamesPatrick: read my comments above, I've described three different ways you can send username and password without putting it in the URL. – Lie Ryan Apr 25 '13 at 08:07
  • 1) setRequestProperty() to set HTTP Header or 2) HTTP Basic Auth with Authenticator or 3) setDoOutput()+getOutputStream() to send JSON on the POST request body; ?? Any example code/link or can you modify the code above ?? It would be better if I can have working code to implement the concept . – James Patrick Apr 25 '13 at 08:10
  • @JamesPatrick: You seem to lack basic understanding of how HTTP works. You would want to first learn about that, and the rest would be pretty obvious. And no, nobody would write your code for you. – Lie Ryan Apr 25 '13 at 08:11
  • Right I will look into http working with android .I had so far implemented the same way as I posted the code above.But if you say that I can post code without adding parameters in URL then I will check that out and will let you know how it goes .Thanks for the help and input.Really appreciate your help .Have a nice day . – James Patrick Apr 25 '13 at 08:13
0

Don't invent new security protocols. Use HTTPS and then you don't need to encrypt the password yourself. With HTTP, any way you will encrypt and exchange keys will probably be not very effective, unless you do something basically the same as HTTPS does. It will only be Security through obscurity (google for that).

Edit: And don't send passwords as GET parameters, but always as POST data, even with HTTPS. Even though GET parameters cannot be captured on the wire if https is used, they may be cached by browsers or go to server log unencrypted, for more info see here: http://www.w3schools.com/tags/ref_httpmethods.asp

Oliv
  • 10,221
  • 3
  • 55
  • 76
  • So in the above case static final String URL = "https://example.com/getmsgs/userno=123"; will this work ?? and also if I paste the same in browser it is not supposed let me through ?? will that happen ?? – James Patrick Apr 25 '13 at 06:21