如何在firebase中哈希密码和存储

时间:2018-03-15 11:58:25

标签: android firebase hash firebase-authentication sha256

我一直在尝试制作注册页面。我正在使用电子邮件身份验证我的注册数据存储在firebase数据库中。

出于安全考虑,我希望隐藏密码字符串。因此,我正在使用SHA-256进行哈希,但它不起作用。

这是我的代码:

 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) {

    String pass = password.getText().toString();

    MessageDigest digest = null;
    try {
        digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    byte[] hash = digest.digest(pass.getBytes(StandardCharsets.UTF_8));

    mref = new Firebase("https://tango-3a561.firebaseio.com/");
    createNewAccount(email.getText().toString(), hash);
}



private void createNewAccount(String email, final byte[] 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, String.valueOf(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();*/

                        if (task.getException() instanceof FirebaseAuthUserCollisionException){

                            Toast.makeText(RegisterActivity.this,"User with this email already exist.",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(RegisterActivity.this, "Register Successful.", Toast.LENGTH_SHORT).show();
                            hideProgressDialog();
                        }

                      /*  if (password.length() < 6) {

                            Toast.makeText(getApplicationContext(), "minimum password!", Toast.LENGTH_SHORT).show();
                            hideProgressDialog();
                        } else {
                            Toast.makeText(getApplicationContext(), "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.getAddress(), user.getEmail(), user.getPassword());
    signOut();
    // Go to LoginActivity
    Intent i =new Intent(RegisterActivity.this, LoginActivity.class);
    startActivity(i);
}


private void saveNewUser(String userId, String name, String phone, String address, String email, String password) {

    User user = new User(userId,name,phone,address,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 userName = name.getText().toString();
    if (TextUtils.isEmpty(userName)) {
        name.setError("Required.");
        valid = false;
    } else {
        name.setError(null);
    }

    String userEmail = email.getText().toString();
    if (TextUtils.isEmpty(userEmail)) {
        email.setError("Required.");
        valid = false;
    } else {
        email.setError(null);
    }

    if (!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()) {
        email.setError("Invalid Mail Address.");
        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);
    }

    if (phoneNumber.length() < 10){
        phoneNumber.setError("Should be 10 Digit");
        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 (Patterns.PHONE.matcher(userPhoneNumber).matches()){
        Toast.makeText(getApplicationContext(),"please enter valid mobile no",Toast.LENGTH_LONG).show();
    }*/

    if (userName.isEmpty() && 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();
    }
}

@Override
public void onPointerCaptureChanged(boolean hasCapture) {

}
}

this is how my database looks

正如您所看到的,我的密码未经过哈希处理。

1 个答案:

答案 0 :(得分:0)

我已用此代码解决了这类问题,请查看

public static String sha256(String base) {
    try{
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(base.getBytes("UTF-8"));
        StringBuffer hexString = new StringBuffer();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
    } catch(Exception ex){
       throw new RuntimeException(ex);
    }
}

然后你只需调用方法并传递密码字段

String newPass =  sha256(pass).toString();

编辑:根据您的问题,这将解决问题

@Override
public void onClick(View v) {

    String pass = password.getText().toString();
    String newPass =  sha256(pass);

    mref = new Firebase("https://tango-3a561.firebaseio.com/");
    createNewAccount(email.getText().toString(), newPass );
}

更改方法参数

private void createNewAccount(String email,String pass)....

希望它有效,快乐编码