password encryption

The sample code gives you a way of encrypting sensitive data like passwords in c#.

There are many ways of encrypting data, many algorithms, the code i am providing here is one of them. There may be many other ways of encryption which are much stronger and secure than this, but yeah this works for me. I am yet to find a way of decrypting back the original string. But then you don’t really need decryption in normal scenarios. Anyway so here’s what i use to encrypt passwords and all.

public class Encryption
        private string _password;
        private int _salt;

        public Encryption()
            _salt = your_secret_number;

        public string EncryptPassword(string password_to_encrypt)
            _password = password_to_encrypt;
                // Create Byte array of password string
                ASCIIEncoding encoder = new ASCIIEncoding();
                Byte[] _secretBytes = encoder.GetBytes(_password);

                // Create a new salt
                Byte[] _saltBytes = new Byte[4];
                _saltBytes[0] = (byte)(_salt >> 24);
                _saltBytes[1] = (byte)(_salt >> 16);
                _saltBytes[2] = (byte)(_salt >> 8);
                _saltBytes[3] = (byte)(_salt);

                // append the two arrays
                Byte[] toHash = new Byte[_secretBytes.Length + _saltBytes.Length];
                Array.Copy(_secretBytes, 0, toHash, 0, _secretBytes.Length);
                Array.Copy(_saltBytes, 0, toHash, _secretBytes.Length, _saltBytes.Length);

                SHA1 sha1 = SHA1.Create();
                Byte[] computedHash = sha1.ComputeHash(toHash);

                return encoder.GetString(computedHash);
            catch (Exception ex)

The code uses .net’s inbuilt cryptography classes to achieve the encrption. You can see that i’ve hardcoded the ‘salt’ value. Thats’ important, there must be one and only one salt value throughout the project, coz once you change it there’s no way of getting the previously encrypted strings’ original value.

Hope you find it useful.

Published by

Chandan Chaudhary

Chandan is a WordPress guy. A programmer at heart. He loves building community sites with WordPress and BuddyPress.

Leave a Reply

Your email address will not be published. Required fields are marked *