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

前端 未结 9 1678
醉梦人生
醉梦人生 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:07

    I just implemented something like this for storing a user supplied password. I converted the encrypted result to a base 64 encoded string, so that I could easily store it in my application's user settings.

    From your question, it seems that your malicious user is actually using your application, so this will only provide obfuscation. Though no key would be revealed through the use of Reflector, the plain text would be visible in a debugger.

    static byte[] entropy = { 65, 34, 87, 33 };
    
    public string Password
    {
        get
        {
            if (this.EncryptedPassword == string.Empty)
            {
                return string.Empty;
            }
    
            var encrypted = Convert.FromBase64String(this.EncryptedPassword);
            var data = ProtectedData.Unprotect(encrypted, entropy, DataProtectionScope.CurrentUser);
            var password = Encoding.UTF8.GetString(data);
            return password;
        }
        set
        {
            if (value == string.Empty)
            {
                this.EncryptedPassword = string.Empty;
                return;
            }
    
            var data = Encoding.UTF8.GetBytes(value);
            var encrypted = ProtectedData.Protect(data, entropy, DataProtectionScope.CurrentUser);
            var stored = Convert.ToBase64String(encrypted);
            this.EncryptedPassword = stored;
        }
    }
    

提交回复
热议问题