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 Answers 2

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).

28
  • 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("example.com/…); 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. Commented Apr 25, 2013 at 5: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. Commented Apr 25, 2013 at 5:37
  • I have added the code above and here I would like to encrypt userno ie: 123 Commented Apr 25, 2013 at 5: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
    Commented Apr 25, 2013 at 5:44
  • both android/PHP Code as above .Please suggest me the right path to encrypt/decrypt dynamically Commented Apr 25, 2013 at 5:44
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

1
  • So in the above case static final String URL = "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 ?? Commented Apr 25, 2013 at 6:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.