我一直在尝试注册新用户。在注册时,我使用AES在Firebase数据库中加密了密码.Accessal.password加密成功。但是当我尝试使用电子邮件ID和密码登录用户时,我输入的密码 登记表格不匹配。相反,密码与存储在firebase数据库中的加密字符串匹配。
注册活动
public class RegisterActivity extends AppCompatActivity implements
View.OnClickListener {
private static final String TAG = "MAGIC";
Firebase mref= null;
private User user;
private EditText name;
private EditText phoneNumber;
private EditText email;
private EditText password;
private EditText address;
private Button register;
private FirebaseAuth mAuth;
private ProgressDialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Firebase.setAndroidContext(this);
mAuth = FirebaseAuth.getInstance();
}
@Override
protected void onStart() {
super.onStart();
name = (EditText) findViewById(R.id.edit_text_username);
phoneNumber = (EditText) findViewById(R.id.edit_text_phone_number);
email = (EditText) findViewById(R.id.edit_text_new_email);
password = (EditText) findViewById(R.id.edit_text_new_password);
address = (EditText) findViewById(R.id.edit_text_address);
register = (Button) findViewById(R.id.button_register);
register.setOnClickListener(this);
}
@Override
public void onStop() {
super.onStop();
}
//This method sets up a new User by fetching the user entered details.
protected void setUpUser() {
user = new User();
user.setName(name.getText().toString().trim());
user.setPhoneNumber(phoneNumber.getText().toString().trim());
user.setAddress(address.getText().toString().trim());
user.setEmail(email.getText().toString().trim());
user.setPassword(password.getText().toString().trim());
}
@Override
public void onClick(View v) {
encryption(password.toString());
mref = new Firebase("https://encryptlogin.firebaseio.com/");
createNewAccount(email.getText().toString(),password.getText().toString());
}
private void createNewAccount(String email, String password) {
Log.d(TAG, "createNewAccount:" + email);
if (!validateForm()) {
return;
}
//This method sets up a new User by fetching the user entered details.
setUpUser();
//This method method takes in an email address and password, validates them and then creates a new user
// with the createUserWithEmailAndPassword method.
// If the new account was created, the user is also signed in, and the AuthStateListener runs the onAuthStateChanged callback.
// In the callback, you can use the getCurrentUser method to get the user's account data.
showProgressDialog();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "Register Successfully " + task.isSuccessful());
hideProgressDialog();
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "Registration failed.", Toast.LENGTH_SHORT).show();
hideProgressDialog();
} else {
onAuthenticationSuccess(task.getResult().getUser());
Toast.makeText(RegisterActivity.this, "Register Successful.", Toast.LENGTH_SHORT).show();
} hideProgressDialog();
}
});
}
private void onAuthenticationSuccess(FirebaseUser mUser) {
// Write new user
saveNewUser(mUser.getUid(), user.getName(),user.getPhoneNumber(), user.getEmail(), user.getPassword());
signOut();
// Go to LoginActivity
Intent i =new Intent(RegisterActivity.this, MainActivity.class);
startActivity(i);
}
private void saveNewUser(String userId, String name, String phone, String email, String password) {
User user = new User(userId,name,phone,email,password);
mref.child("Users").child(name).setValue(user);
}
private void signOut() {
mAuth.signOut();
}
//This method, validates email address and password
private boolean validateForm() {
boolean valid = true;
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
String userPhoneNumber = phoneNumber.getText().toString();
if (TextUtils.isEmpty(userPhoneNumber)){
phoneNumber.setError("Required");
valid = false;
}else {
phoneNumber.setError(null);
}
String userAddress = address.getText().toString();
if (TextUtils.isEmpty(userAddress)){
address.setError("Required");
valid = false;
}else {
address.setError(null);
}
if(!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()){
Toast.makeText(getApplicationContext(),"please enter valid email",
Toast.LENGTH_LONG).show();
}
if (userEmail.isEmpty() && userPassword.isEmpty()userAddress.isEmpty()
&& userPhoneNumber.isEmpty()){
Toast.makeText(getApplicationContext(),"all fields are mandatory",
Toast.LENGTH_LONG).show();
}
return valid;
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
public void encryption(String pass){
String seedValue = "secKey";
try {
password.setText(AESHelper.encrypt(seedValue,pass));
}catch (Exception e){
e.printStackTrace();
}
}
}
登录活动
public class MainActivity extends AppCompatActivity {
EditText Email, pwd;
Button login;
TextView Register,Forgetpwd;
FirebaseAuth mAuth;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(MainActivity.this, Forget_password.class));
finish();
}
Email = (EditText) findViewById(R.id.myEmail);
pwd = (EditText) findViewById(R.id.editpassword);
login = (Button) findViewById(R.id.buttonlogin);
Register = (TextView) findViewById(R.id.register);
Forgetpwd = (TextView) findViewById(R.id.reset);
mAuth = FirebaseAuth.getInstance();
Register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RegisterActivity.class));
}
});
Forgetpwd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Forget_password.class));
}
});
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = Email.getText().toString();
final String password = pwd.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
Toast.makeText(getApplicationContext(),"please enter valid email",Toast.LENGTH_LONG).show();
}
if (email.isEmpty() && password.isEmpty()){
Toast.makeText(getApplicationContext(),"all fields are mandatory",Toast.LENGTH_LONG).show();
}
showProgressDialog();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
/* progressBar.setVisibility(View.GONE);*/
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "minimum password!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Authentication failed!", Toast.LENGTH_SHORT).show(); }
} else {
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, Forget_password.class);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
});
}
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.loading));
progressDialog.setIndeterminate(true);
}
progressDialog.show();
}
public void hideProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
AESHelper Class
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESHelper {
public static String encrypt(String seed, String cleartext
throwsException{
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted)
throwsException{
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG","Crypto");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception{
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted)throws
Exception{
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).
byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
如何在登录活动中匹配密码。帮帮我...