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

前端 未结 9 2190
时光取名叫无心
时光取名叫无心 2021-02-12 12:29

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:08

    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!

    0 讨论(0)
  • 2021-02-12 13:12

    Encrypted in AES if you must store it in a text file.

    AES is better known as Rijndael in c#

    http://www.obviex.com/samples/Encryption.aspx

    Better place would be the registry, since it would protect other users of the machine getting to it.

    Still not the best storing it anywhere that a user might be able to get to is dangerous a 1/2 way decent developer can load up your app in reflector and find your key.

    Or there is System.Security.Cryptography.ProtectedData that someone else suggested.

    The best you could do on a machine is create a certificate and encrypt/decrypt with it loaded and locked down in the machine's keystore. (Still have to deal with the certificate password being in your code)

    0 讨论(0)
  • 2021-02-12 13:19

    Since you must send the password in unencrypted form over the network, there is nothing you can do to protect it 100%.

    AES is good enough if you need to store locally, and talking about disasms, network sniffers etc is not particulary good contra-argument becuase the same thing can be done with any program (sure, ASM is harder then CIL but its a minior point).

    Such password protecting is good enough to prevent casual pick up, not to prevent decoding by proffesionals.

    0 讨论(0)
提交回复
热议问题