Password encryption/decryption code in .NET

后端 未结 9 1059
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 00:37

I want simple encryption and decryption of password in C#. How to save the password in encrypted format in database and retrieve as original format by decryption?

9条回答
  •  情话喂你
    2020-11-29 01:32

    Here you go. I found it somewhere on the internet. Works well for me.

        /// 
        /// Encrypts a given password and returns the encrypted data
        /// as a base64 string.
        /// 
        /// An unencrypted string that needs
        /// to be secured.
        /// A base64 encoded string that represents the encrypted
        /// binary data.
        /// 
        /// This solution is not really secure as we are
        /// keeping strings in memory. If runtime protection is essential,
        ///  should be used.
        /// If 
        /// is a null reference.
        public string Encrypt(string plainText)
        {
            if (plainText == null) throw new ArgumentNullException("plainText");
    
            //encrypt data
            var data = Encoding.Unicode.GetBytes(plainText);
            byte[] encrypted = ProtectedData.Protect(data, null, Scope);
    
            //return as base64 string
            return Convert.ToBase64String(encrypted);
        }
    
        /// 
        /// Decrypts a given string.
        /// 
        /// A base64 encoded string that was created
        /// through the  or
        ///  extension methods.
        /// The decrypted string.
        /// Keep in mind that the decrypted string remains in memory
        /// and makes your application vulnerable per se. If runtime protection
        /// is essential,  should be used.
        /// If 
        /// is a null reference.
        public string Decrypt(string cipher)
        {
            if (cipher == null) throw new ArgumentNullException("cipher");
    
            //parse base64 string
            byte[] data = Convert.FromBase64String(cipher);
    
            //decrypt data
            byte[] decrypted = ProtectedData.Unprotect(data, null, Scope);
            return Encoding.Unicode.GetString(decrypted);
        }
    

提交回复
热议问题