Possible Duplicate:
Password protecting my android app (the simple way)
Edit:
I founded what i want here: Password protecting my android app (the simple way)
(I have a TextField named password
. If a user enters the correct password 123
, upon clicking a button I want the user to go to another activity. If a wrong password is entered, a message such as "Wrong password!"
should be displayed. The actual password itself is found in a file located at /sdcard/Android/password.txt
.
How can I create such functionality?)
You need to cover a lot of ground here UI, Security etc. so I will give you a brief overview on the steps you need to get done.
You need activities or dialogs for the UI's, getting an initial password and checking the password both should have
TextView that uses the password attribute set (hide characters)
Button(s) that allows the user to cancel or select ok with on click listeners attached
To store/get the password then use something similar to this instead of sdcard and a txt file Getting a password from shared preferences, you can use the shared preferences editor to store it as well. This adds a bit of security but not much
In general what you should store is not the password itself, but you should really store a token for added security, here is one class that can do that for you
import java.security.MessageDigest;
public class PasswordToken {
static public String makeDigest(String password)
{
String hexStr = "";
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
byte[] buffer = password.getBytes();
md.update(buffer);
byte[] digest = md.digest();
for (int i = 0; i < digest.length; i++) {
hexStr += Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );
}
} catch(Exception e) // If the algo is not working for some reason on this device
// we have to use the strings hash code, which
// could allow duplicates but at least allows tokens
{
hexStr = Integer.toHexString(password.hashCode());
}
return hexStr;
}
static public boolean validate(String password, String token)
{
String digestToken = "";
String simpleToken = "";
digestToken = makeDigest(password);
if (0 == digestToken.compareTo(token))
return true;
if (0 == simpleToken.compareTo(token))
return true;
return false;
}
}
So to store a password when you clicked on your ok button
PasswordTextView.getText();
String token = PasswordToken.makeDigest(password);
//... store TOKEN using the shared preferences editor
To check a password when your user wanted to login
PasswordTextView.GetText();
String token = PasswordToken.makeDigest(password);
//... GET token using the shared preferences
if (PasswordToken.validate(token))
Start your new activity
else
tell your user to try again
You can use startActivity or startActivityForResult to start another activity and look at overiding the Dialog class to do the UI bit.