我想比较两个哈希函数和用户输入。如果两者都等于那么Toast me。这样做的目的,我希望将来使用这种方法将我的哈希密码存储到数据库并与用户输入密码进行比较以进行登录。
我制作两种输入类型,其中我通过输入给出字符串值并将其转换为哈希值。当两种输入类型具有相同的值时,它应该是Toast me,如果没有,那么请不要干我或给我错误。
问题是,当我给出相同的值时,它会准确地向我敬酒,但是当我给出两个不同的值时,它也会向我敬酒。这是不正确的结果。
请告诉我如何比较这两个功能并制作登录方案。
代码是:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value1 = (EditText) findViewById(R.id.value1);
value2 = (EditText) findViewById(R.id.value2);
computeSha = (Button) findViewById(R.id.btn1);
result = (TextView) findViewById(R.id.textView2);
//get username and password entered
username = userName.getText().toString();
passwd = passWord.getText().toString();
//check if username or passwd is not null
if ((username != null && username.equals("")) || (passwd != null && passwd.equals(""))) {
computeSha.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//call method to compute SHA hash
computeSHAHash(value1);
computeSHAHash(value2);
if (computeSHAHash(value1).equals(computeSHAHash(value2))) {
Toast.makeText(MainActivity.this, "matched", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private String convertToHex(byte[] data) throws java.io.IOException
{
StringBuffer sb = new StringBuffer();
String hex=null;
hex=Base64.encodeToString(data, 0, data.length, NO_OPTIONS);
sb.append(hex);
return sb.toString();
}
public String computeSHAHash(String password)
{
MessageDigest mdSha1 = null;
try
{
mdSha1 = MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e1) {
Log.e("myapp", "Error initializing SHA1 message digest");
}
try {
mdSha1.update(password.getBytes("ASCII"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = mdSha1.digest();
try {
SHAHash=convertToHex(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.setText("SHA-1 hash generated is: " + " " + SHAHash);
return SHAHash;
}
哈希函数:
private String convertToHex(byte[] data) throws java.io.IOException
{
StringBuffer sb = new StringBuffer();
String hex=null;
hex=Base64.encodeToString(data, 0, data.length, NO_OPTIONS);
sb.append(hex);
return sb.toString();
}
public String computeSHAHash(String password)
{
MessageDigest mdSha1 = null;
try
{
mdSha1 = MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e1) {
Log.e("myapp", "Error initializing SHA1 message digest");
}
try {
mdSha1.update(password.getBytes("ASCII"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = mdSha1.digest();
try {
SHAHash=convertToHex(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.setText("SHA-1 hash generated is: " + " " + SHAHash);
return SHAHash;
}