1

I have a Android application written in Java which utilises an SQLite database. I want the passwords upon input on the sign up page to generate an MD5 or SHA1 hash which is stored in the database. Which can then be used when logging back into the application.

Can anyone offer any help?

Signup

package com.example.oliver.beckettreg;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class SignUp extends Activity {

DatabaseHelper helper = new DatabaseHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.signup);
}

//if button clicked
public void onSignUpClick(View v) {
    if (v.getId() == R.id.Bsignupbutton) {


        EditText name = (EditText) findViewById(R.id.TFname);
        EditText email = (EditText) findViewById(R.id.TFemail);
        EditText uname = (EditText) findViewById(R.id.TFuname);
        EditText pass1 = (EditText) findViewById(R.id.TFpass1);
        EditText pass2 = (EditText) findViewById(R.id.TFpass2);


        String namestr = name.getText().toString();
        String emailstr = email.getText().toString();
        String unamestr = uname.getText().toString();
        String pass1str = pass1.getText().toString();
        String pass2str = pass2.getText().toString();

        //check passwords match
        if(!pass1str.equals(pass2str))


        {
            //popup msg if fails
            Toast pass = Toast.makeText(SignUp.this , "Passwords don't match!" , Toast.LENGTH_SHORT);
            pass.show();


        }
        else
        {

            //validations for data input
            if (name.getText().toString().length() == 0)
            {name.setError("Name Required");}

            else if (!email.getText().toString().matches("[a-z]{1}\\.[a-z]*[0-9]{4}@student\\.leedsbeckett\\.ac\\.uk"))
            {email.setError("Incorrect Email Format");}

            else if (!uname.getText().toString().matches("[cC][0-9]{7}"))
            {uname.setError("Incorrect ID Format");}

            else if (!pass1.getText().toString().matches("(?=.*[\\d])(?=.*[a-z])(?=.*[A-Z]).{8,}"))
            {pass1.setError("Incorrect Password Format");}

            else{
                //insert the details in database
                Contact c = new Contact();
                c.setName(namestr);
                c.setEmail(emailstr);
                c.setUname(unamestr);
                c.setPass(pass1str);

                helper.insertContact(c);


                //popup if data passes validations
                Toast pass = Toast.makeText(SignUp.this , "User Registered" , Toast.LENGTH_LONG);
                pass.show();

            }

        }

    }


}


public void onButtonClick(View v) {

    if (v.getId() == R.id.Blogin2) {
        Intent i = new Intent(SignUp.this, com.example.oliver.beckettreg.MainActivity.class);
        startActivity(i);

    }




}
}

Login

package com.example.oliver.beckettreg;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

DatabaseHelper helper = new DatabaseHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}


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

public void onButtonClick(View v)
{

    //if button clicked
    if(v.getId() == R.id.Blogin)
    {

        //check if passwords match
        EditText a = (EditText)findViewById(R.id.TFusername);
        String str = a.getText().toString();
        EditText b = (EditText)findViewById(R.id.TFpassword);
        String pass = b.getText().toString();

        String password = helper.searchPass(str);
        if(pass.equals(password))
        {
            Intent i = new Intent(MainActivity.this, NFC.class);
            i.putExtra("Username",str);
            startActivity(i);
        }
        else
        {å
            Toast temp = Toast.makeText(MainActivity.this , "Username and password don't match!" , Toast.LENGTH_SHORT);
            temp.show();
        }



    }
    //sign up button if data passes
    if(v.getId() == R.id.Bsignup)
    {
        Intent i = new Intent(MainActivity.this, com.example.oliver.beckettreg.SignUp.class);
        startActivity(i);

    }

    if(v.getId() == R.id.Bnfc)
    {
        Intent i = new Intent(MainActivity.this, com.example.oliver.beckettreg.AttendanceRegistration.class);
        startActivity(i);

    }


}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Database Helper

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;



 public class
   DatabaseHelper extends SQLiteOpenHelper {

//Database Version
private static final int DATABASE_VERSION = 1;

//Database Name
private static final String DATABASE_NAME = "contacts.db";

//Table Names
private static final String REGISTER_TABLE_NAME = "register";
private static final String CONTACTS_TABLE_NAME = "contacts";

//Contacts Column Names
private static final String CONTACTS_COLUMN_ID = "id";
private static final String CONTACTS_COLUMN_NAME = "name";
private static final String CONTACTS_COLUMN_EMAIL = "email";
private static final String CONTACTS_COLUMN_UNAME = "uname";
private static final String CONTACTS_COLUMN_PASS = "pass";

//Register Column Names
private static final String REGISTER_COLUMN_ID = "id";
private static final String REGISTER_COLUMN_SEMINAR = "seminar";
private static final String REGISTER_COLUMN_LECTURE = "lecture";

SQLiteDatabase db;

//Table Create Statements
private static final String CONTACTS_TABLE_CREATE = "create table contacts (id                                   integer primary key not null , " +
    "name text not null , email text not null , uname text not null , pass text not null);";

private static final String REGISTER_TABLE_CREATE =  "create table register         (id integer primary key not null , " +
    " time DATETIME DEFAULT CURRENT_TIMESTAMP, seminar text not null , lecture text not null,  );";

public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

//Creating Required Tables
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(REGISTER_TABLE_CREATE);
db.execSQL(CONTACTS_TABLE_CREATE);
this.db = db;
}

public void insertContact(Contact c) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();

String query = "select * from contacts";
Cursor cursor = db.rawQuery(query , null);
int count = cursor.getCount();

values.put(CONTACTS_COLUMN_ID, count);
values.put(CONTACTS_COLUMN_NAME, c.getName());
values.put(CONTACTS_COLUMN_EMAIL, c.getEmail());
values.put(CONTACTS_COLUMN_UNAME, c.getUname());
values.put(CONTACTS_COLUMN_PASS, c.getPass());

db.insert(CONTACTS_TABLE_NAME, null, values);
db.close();


}

public void insertRegister(Register r) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();

String query = "select * from register";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();

values.put(REGISTER_COLUMN_ID, count);
values.put(REGISTER_COLUMN_SEMINAR, r.getSeminar());
values.put(REGISTER_COLUMN_LECTURE, r.getLecture());

db.insert(REGISTER_TABLE_NAME, null, values);
db.close();

}


public String searchPass(String uname)
{
db = this.getReadableDatabase();
String query = "select uname, pass from "+CONTACTS_TABLE_NAME;
Cursor cursor = db.rawQuery(query , null);
String a, b;
b = "not found";
if(cursor.moveToFirst())
{
    do{
        a = cursor.getString(0);

        if(a.equals(uname))
        {
            b = cursor.getString(1);
            break;
        }
    }
    while(cursor.moveToNext());
    }

return b;
}


    //On Upgrade Drop Older Tables
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + REGISTER_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + CONTACTS_TABLE_NAME);

//Create New Tables
this.onCreate(db);

}

}
oliver_13
  • 39
  • 10

1 Answers1

0

You can implement this method, which will return the hash as a string.

private String hashMe(String password) {

    try {
        MessageDigest md = MessageDigest.getInstance("SHA-1"); //could also be MD5, SHA-256 etc.
        md.reset();
        md.update(password.getBytes("UTF-8"));
        byte[] resultByte = md.digest();
        password = String.format("%01x", new java.math.BigInteger(1, resultByte));

    } catch (NoSuchAlgorithmException e) {
        //do something.
    } catch (UnsupportedEncodingException ex) {
        //do something
    }
    return password;
}

Since you are dealing with passwords, you should also salt the hash, and save them both in your Db.

  • Thankyou sir, in which class? Both? @Etterfres – oliver_13 Apr 12 '16 at 14:40
  • Im not sure how to implement this into my application, can you offer any further assistance? @etterfres – oliver_13 Apr 12 '16 at 14:48
  • Absolutely! You would need this method both when users sign up and log in, since logging in would compare hashes, and signing up would save the hash. Since I haven't seen your complete project it hard to say where to put it. Maybe DatabaseHelper? (on the grounds that it's used in both your classes.) –  Apr 12 '16 at 23:24
  • I am still struggling so i have posted by database helper if this helps @Etterfres – oliver_13 Apr 13 '16 at 01:51
  • If you were to put it in DatabaseHelper, you could use it like this: values.put(CONTACTS_COLUMN_PASS, hashMe(c.getPass())); –  Apr 13 '16 at 07:20
  • @oliver_13 , how is it going? –  Apr 22 '16 at 09:09
  • I have no problem hashing the passwords and inputting them in my database, I am still struggling to log in to the application once they are hashed. @Etterfres – oliver_13 Apr 22 '16 at 11:28
  • So basically I mean i am struggling to compare the two hashes and loggin in with the username and text password – oliver_13 Apr 22 '16 at 13:10