Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- C# Password Encryption
- string UserName = txtUser.Text;
- string password = txtPass.Text;
- string encrKey = "keyvalue";
- byte[] byteKey = { };
- byte[] IV = {25, 47, 60, 88, 99, 106, 125, 139};
- byteKey = Encoding.UTF8.GetBytes(encrKey.Substring(0, 8));
- DESCryptoServiceProvider des = new DESCryptoServiceProvider();
- byte[] inputArray = Encoding.UTF8.GetBytes(password);
- MemoryStream ms = new MemoryStream();
- CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byteKey, IV), CryptoStreamMode.Write);
- cs.Write(inputArray, 0, inputArray.Length);
- cs.FlushFinalBlock();
- password = Convert.ToBase64String(ms.ToArray());
- SqlCommand cmd = new SqlCommand("INSERT INTO USers (UserName, Password) VALUES (@UserName, @Password)", myConnection);
- cmd.CommandType = CommandType.Text;
- cmd.Parameters.AddWithValue("@UserName", UserName);
- cmd.Parameters.AddWithValue("@Password", password);
- SqlDataReader rdr = cmd.ExecuteReader();
- var hash = Encoding.ASCII.GetBytes(password);
- var md5 = new MD5CryptoServiceProvider();
- var md5hash = md5.ComputeHash(hash);
- var hashedPassword = ASCIIEncoding.GetString(md5hash);
- var hash = Encoding.ASCII.GetBytes(password);
- var sha1 = new SHA1CryptoServiceProvider();
- var sha1hash = sha1.ComputeHash(hash);
- var hashedPassword = ASCIIEncoding.GetString(sha1hash);
- public sealed class PasswordHash
- {
- const int SaltSize = 16, HashSize = 20, HashIter = 10000;
- readonly byte[] _salt, _hash;
- public PasswordHash(string password)
- {
- new RNGCryptoServiceProvider().GetBytes(_salt = new byte[SaltSize]);
- _hash = new Rfc2898DeriveBytes(password, _salt, HashIter).GetBytes(HashSize);
- }
- public PasswordHash(byte[] hashBytes)
- {
- Array.Copy(hashBytes, 0, _salt = new byte[SaltSize], 0, SaltSize);
- Array.Copy(hashBytes, SaltSize, _hash = new byte[HashSize], 0, HashSize);
- }
- public PasswordHash(byte[] salt, byte[] hash)
- {
- Array.Copy(salt, 0, _salt = new byte[SaltSize], 0, SaltSize);
- Array.Copy(hash, 0, _hash = new byte[HashSize], 0, HashSize);
- }
- public byte[] ToArray()
- {
- byte[] hashBytes = new byte[SaltSize + HashSize];
- Array.Copy(_salt, 0, hashBytes, 0, SaltSize);
- Array.Copy(_hash, 0, hashBytes, SaltSize, HashSize);
- return hashBytes;
- }
- public byte[] Salt { get { return (byte[])_salt.Clone(); } }
- public byte[] Hash { get { return (byte[])_hash.Clone(); } }
- public bool Verify(string password)
- {
- byte[] test = new Rfc2898DeriveBytes(password, _salt, HashIter).GetBytes(HashSize);
- for (int i = 0; i < HashSize; i++)
- if (test[i] != _hash[i])
- return false;
- return true;
- }
- }
Add Comment
Please, Sign In to add comment