Good way to replace invalid characters in firebase keys?

前端 未结 4 519
执念已碎
执念已碎 2020-12-05 13:43

My use case is saving a user\'s info. When I try to save data to Firebase using the user\'s email address as a key, Firebase throws the following error:

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 14:12

    I am using the following code for converting email to hash and then using the hash as key in firebase

    public class HashingUtils {
        public HashingUtils() {
        }
    
        //generate 256 bits hash using SHA-256
        public String generateHashkeySHA_256(String email){
            String result = null;
            try {
                MessageDigest digest = MessageDigest.getInstance("SHA-256");
                byte[] hash = digest.digest(email.getBytes("UTF-8"));
                return byteToHex(hash); // make it printable
            }catch(Exception ex) {
                ex.printStackTrace();
            }
            return result;
        }
    
        //generate 160bits hash using SHA-1
        public String generateHashkeySHA_1(String email){
            String result = null;
            try {
                MessageDigest digest = MessageDigest.getInstance("SHA-1");
                byte[] hash = digest.digest(email.getBytes("UTF-8"));
                return byteToHex(hash); // make it printable
            }catch(Exception ex) {
                ex.printStackTrace();
            }
            return result;
        }
    
        public String byteToHex(byte[] bytes) {
            Formatter formatter = new Formatter();
            for (byte b : bytes) {
                formatter.format("%02x", b);
            }
            String hex = formatter.toString();
            return hex;
        }
    }
    

    code for adding the user to firebase

    public void addUser(User user) {
        Log.d(TAG, "addUser: ");
        DatabaseReference userRef= database.getReference("User");
    
        if(!TextUtils.isEmpty(user.getEmailId())){
           String hashEmailId= hashingUtils.generateHashkeySHA_256(user.getEmailId());
            Log.d(TAG, "addUser: hashEmailId"+hashEmailId);
            userRef.child(hashEmailId).setValue(user);
        }
        else {
            Log.d(TAG,"addUser: empty emailId");
        }
    }
    

提交回复
热议问题