Best practices for encrypting and decrypting passwords? (C#/.NET)

前端 未结 9 1685
醉梦人生
醉梦人生 2021-02-12 12:26

I need to store and encrypt a password in a (preferably text) file, that I later need to be able to decrypt. The password is for another service that I use, and needs to be sent

9条回答
  •  你的背包
    2021-02-12 13:09

    Why you need to decrypt the password? Usually a salted hash of the password is stored and compared. If you encrypt/decrypt the password you have the password as plain text again and this is dangerous. The hash should be salted to avoid duplicated hash if the some users have the same passwords. For the salt you can take the user name.

    HashAlgorithm hash = new SHA256Managed();
    string password = "12345";
    string salt = "UserName";
    
    // compute hash of the password prefixing password with the salt
    byte[] plainTextBytes = Encoding.UTF8.GetBytes(salt + password);
    byte[] hashBytes = hash.ComputeHash(plainTextBytes);
    
    string hashValue = Convert.ToBase64String(hashBytes);
    

    You can calculate the salted hash of the password and store that within your file. During the authentication you calculate the hash from the user entries again and compare this hash with the stored password hash. Since it should be very difficult (its never impossible, always a matter of time) to get the plain text from a hash the password is protected from reading as plain text again.

    Tip: Never store or send a password unencrypted. If you get a new password, encrypt is as soon as possible!

提交回复
热议问题