Search code examples
androidandroid-asynctaskandroid-thread

Password comparing in Android


So I have stored password as hash in shared preferences, when user puts password I need to make a hash of it and compare with stored one.

Should it be done in AsyncTask or Thread because calculation and comparison could freeze UI? And then do you know a clean way to recieve result (true, false) from asynctask or thread?

public void startGenerateCode(View view) {
    String pinCompare = pin; //pin is class variable obtained from editText
    pinCompare = tools.bin2hex(tools.getHash(pinCompare)); 

    if(pinCompare.compareTo(session.getDetails("Pin"))==0){
        generateCode();
    }
    else
        Toast.makeText(this, "Wrong PIN", Toast.LENGTH_SHORT).show();

}

public void generateCode(){
    Intent i = new Intent(this, GeneratedCode.class);
    startActivity(i);
    overridePendingTransition(R.anim.right_slide_in, R.anim.right_slide_out);
    finish();
}

This is done in activity after button is pressed.


Solution

  • Zolo,

    I guess this process is triggered when someone presses a Button, such as login. I don't think you need any extra Thread to process the Hash calculus.

    If you then have to connect to a server and send/receive data, then you should use it due to the asynchronous flow.

    Response to comments on main post: Yes, you can start an Activity in onPostExecute.

    Code example:

    public void startGenerateCode(View view) {
    
        // Disable button         
        Button button = (Butto) view;
        button.setEnabled(false);
    
        String pinCompare = pin; //pin is class variable obtained from editText
        pinCompare = tools.bin2hex(tools.getHash(pinCompare)); 
    
        if(pinCompare.compareTo(session.getDetails("Pin"))==0){
            generateCode();
        } else {
            // If the login fails, re-enable the button to try again
            button.setEnabled(true);
            Toast.makeText(this, "Wrong PIN", Toast.LENGTH_SHORT).show();
        }
    }
    

    I did it by heart, so there may be mistakes.