James Patrick
James Patrick

Reputation: 23

encrypt/decrypt public/private android

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;
}

}

Upvotes: 0

Views: 1403

Answers (2)

Oliv
Oliv

Reputation: 10822

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

Upvotes: 0

Lie Ryan
Lie Ryan

Reputation: 64855

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

Upvotes: 3

Related Questions