I'd successfully hash password using AES SHA-1 with salt and stored it in SQL database but I had problem in login because it cannot be verified when trying to login so anyone help me to fix that problem?????
- Salt coding
public partial class Register : System.Web.UI.Page
{
public static string Name;
public static string img="";
private static string CreateSalt(int size)
{
// Generate a cryptographic random number using the cryptographic
// service provider
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
// Return a Base64 string representation of the random number
return Convert.ToBase64String(buff);
}
private static string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = String.Concat(pwd, salt);
string hashedPwd =
FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "SHA1");
hashedPwd = String.Concat(hashedPwd, salt);
return hashedPwd;
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnRegister_Click(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
int saltSize = 5;
string salt = CreateSalt(saltSize);
string passwordHash = CreatePasswordHash(txtPass.Text, salt);
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
namespace Utils.Encryption
{
[Guid("4EE61A1D-142F-4e8b-B0A2-9C5794ADCDF9")]
public interface AESEncryptionInterface
{
string Encrypt(string PlainText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize);
string Decrypt(string CipherText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize);
string ComputeHash(string plainText, string hashAlgorithm, string Salt);
bool VerifyHash(string plainText, string hashAlgorithm, string hashValue);
string ByteArrayToString(byte[] inputArray);
byte[] StringToByteArray(string inputString);
byte[] GenerateSaltBytes();
string GenerateSaltString();
string GenerateRandomString(int length);
int GenerateRandomNumber(int minValue, int maxValue);
byte[] GenerateRandomByteArray(int length);
string GenerateRandomPassword(int length);
}
[Guid("53B906B6-262B-493a-AA93-AFD0D3BFEA81"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface AESEncryptionEvents
{
}
[Guid("CB56A796-EA66-4def-90BB-7DD025BEF028"),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(AESEncryptionEvents))]
public class AESEncryption : AESEncryptionInterface
{
public string lastError = "";
public bool hasError = false;
public string Encrypt(string PlainText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize)
{
try
{
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes);
MemoryStream MemStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] CipherTextBytes = MemStream.ToArray();
MemStream.Close();
cryptoStream.Close();
hasError = false;
return Convert.ToBase64String(CipherTextBytes);
}
catch (Exception ex)
{
hasError = true;
lastError = ex.Message;
return null;
}
}
public string Decrypt(string CipherText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize)
{
try
{
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes);
MemoryStream MemStream = new MemoryStream(CipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read);
byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
int ByteCount = cryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
MemStream.Close();
cryptoStream.Close();
hasError = false;
return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
}
catch (Exception ex)
{
hasError = true;
lastError = ex.Message;
return null;
}
}
public string ByteArrayToString(byte[] inputArray)
{
System.Text.Encoding enc = System.Text.Encoding.ASCII;
return enc.GetString(inputArray);
}
public byte[] StringToByteArray(string inputString)
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
return enc.GetBytes(inputString);
}
public string ComputeHash(string plainText, string hashAlgorithm, string salt)
{
byte[] saltBytes = null;
// If salt is not specified, generate it on the fly.
saltBytes = StringToByteArray(salt);
if (saltBytes == null)
{
// Define min and max salt sizes.
int minSaltSize = 4;
int maxSaltSize = 8;
// Generate a random number for the size of the salt.
Random random = new Random();
int saltSize = random.Next(minSaltSize, maxSaltSize);
// Allocate a byte array, which will hold the salt.
saltBytes = new byte[saltSize];
// Initialize a random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// Fill the salt with cryptographically strong byte values.
rng.GetNonZeroBytes(saltBytes);
}
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// Allocate array, which will hold plain text and salt.
byte[] plainTextWithSaltBytes =
new byte[plainTextBytes.Length + saltBytes.Length];
// Copy plain text bytes into resulting array.
for (int i = 0; i < plainTextBytes.Length; i++)
plainTextWithSaltBytes[i] = plainTextBytes[i];
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
// Because we support multiple hashing algorithms, we must define
// hash object as a common (abstract) base class. We will specify the
// actual hashing algorithm class later during object creation.
HashAlgorithm hash;
// Make sure hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Initialize appropriate hashing algorithm class.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hash = new SHA1Managed();
break;
case "SHA256":
hash = new SHA256Managed();
break;
case "SHA384":
hash = new SHA384Managed();
break;
case "SHA512":
hash = new SHA512Managed();
break;
default:
hash = new MD5CryptoServiceProvider();
break;
}
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
// Create array which will hold hash and original salt bytes.
byte[] hashWithSaltBytes = new byte[hashBytes.Length +
saltBytes.Length];
// Copy hash bytes into resulting array.
for (int i = 0; i < hashBytes.Length; i++)
hashWithSaltBytes[i] = hashBytes[i];
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
// Convert result into a base64-encoded string.
string hashValue = Convert.ToBase64String(hashWithSaltBytes);
// Return the result.
return hashValue;
}
public bool VerifyHash(string plainText, string hashAlgorithm, string hashValue)
{
// Convert base64-encoded hash value into a byte array.
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
// We must know size of hash (without salt).
int hashSizeInBits, hashSizeInBytes;
// Make sure that hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Size of hash is based on the specified algorithm.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hashSizeInBits = 160;
break;
case "SHA256":
hashSizeInBits = 256;
break;
case "SHA384":
hashSizeInBits = 384;
break;
case "SHA512":
hashSizeInBits = 512;
break;
default: // Must be MD5
hashSizeInBits = 128;
break;
}
// Convert size of hash from bits to bytes.
hashSizeInBytes = hashSizeInBits / 8;
// Make sure that the specified hash value is long enough.
if (hashWithSaltBytes.Length < hashSizeInBytes)
return false;
// Allocate array to hold original salt bytes retrieved from hash.
byte[] saltBytes = new byte[hashWithSaltBytes.Length -
hashSizeInBytes];
// Copy salt from the end of the hash to the new array.
for (int i = 0; i < saltBytes.Length; i++)
saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i];
// Compute a new hash string.
string expectedHashString =
ComputeHash(plainText, hashAlgorithm, ByteArrayToString(saltBytes));
// If the computed hash matches the specified hash,
// the plain text value must be correct.
return (hashValue == expectedHashString);
}
public byte[] GenerateSaltBytes()
{
// We don't have the length, yet.
int saltLen = 0;
int minSaltLen = 16;
int maxSaltLen = 32;
// If min and max salt values are the same, it should not be random.
saltLen = GenerateRandomNumber(minSaltLen, maxSaltLen);
// Allocate byte array to hold our salt.
byte[] salt = new byte[saltLen];
// Populate salt with cryptographically strong bytes.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetNonZeroBytes(salt);
// Split salt length (always one byte) into four two-bit pieces and
// store these pieces in the first four bytes of the salt array.
salt[0] = (byte)((salt[0] & 0xfc) | (saltLen & 0x03));
salt[1] = (byte)((salt[1] & 0xf3) | (saltLen & 0x0c));
salt[2] = (byte)((salt[2] & 0xcf) | (saltLen & 0x30));
salt[3] = (byte)((salt[3] & 0x3f) | (saltLen & 0xc0));
return salt;
}
public string GenerateSaltString()
{
// We don't have the length, yet.
int saltLen = 0;
int minSaltLen = 16;
int maxSaltLen = 32;
saltLen = GenerateRandomNumber(minSaltLen, maxSaltLen);
// Allocate byte array to hold our salt.
byte[] salt = new byte[saltLen];
// Populate salt with cryptographically strong bytes.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetNonZeroBytes(salt);
// Split salt length (always one byte) into four two-bit pieces and
// store these pieces in the first four bytes of the salt array.
salt[0] = (byte)((salt[0] & 0xfc) | (saltLen & 0x03));
salt[1] = (byte)((salt[1] & 0xf3) | (saltLen & 0x0c));
salt[2] = (byte)((salt[2] & 0xcf) | (saltLen & 0x30));
salt[3] = (byte)((salt[3] & 0x3f) | (saltLen & 0xc0));
return Convert.ToBase64String(salt);
}
public string GenerateRandomString(int length)
{
//Create and populate random byte array
byte[] randomArray = new byte[length];
string randomString;
//Create random salt and convert to string
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomArray);
randomString = Convert.ToBase64String(randomArray);
return randomString;
}
public byte[] GenerateRandomByteArray(int length)
{
//Create and populate random byte array
byte[] randomArray = new byte[length];
string randomString;
//Create random salt and convert to string
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomArray);
return randomArray;
}
public int GenerateRandomNumber(int minValue, int maxValue)
{
// We will make up an integer seed from 4 bytes of this array.
byte[] randomBytes = new byte[4];
// Generate 4 random bytes.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
// Convert four random bytes into a positive integer value.
int seed = ((randomBytes[0] & 0x7f) << 24) |
(randomBytes[1] << 16) |
(randomBytes[2] << 8) |
(randomBytes[3]);
// Now, this looks more like real randomization.
Random random = new Random(seed);
// Calculate a random number.
return random.Next(minValue, maxValue + 1);
}
public string GenerateRandomPassword(int length)
{
//Create and populate random byte array
byte[] randomArray = new byte[length];
string randomString;
//Create random salt and convert to string
//use only printable ascii characters
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomArray);
randomString = Convert.ToBase64String(randomArray);
return randomString;
}
}
}
Thanks for replay but can you explain what you mean: Did you mean to create a class object name Utils.Encryption, but can you explain with more details how to use it inside login page and the register page, what code that I store in database???
The store hash pass will change every time user input its pass so how to verified it from data base
mkf
Member
7 Points
54 Posts
Hashing pass
Jun 08, 2012 08:13 PM|LINK
I'd successfully hash password using AES SHA-1 with salt and stored it in SQL database but I had problem in login because it cannot be verified when trying to login so anyone help me to fix that problem?????
- Salt coding
public partial class Register : System.Web.UI.Page { public static string Name; public static string img=""; private static string CreateSalt(int size) { // Generate a cryptographic random number using the cryptographic // service provider RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buff = new byte[size]; rng.GetBytes(buff); // Return a Base64 string representation of the random number return Convert.ToBase64String(buff); } private static string CreatePasswordHash(string pwd, string salt) { string saltAndPwd = String.Concat(pwd, salt); string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "SHA1"); hashedPwd = String.Concat(hashedPwd, salt); return hashedPwd; } protected void Page_Load(object sender, EventArgs e) { } protected void btnRegister_Click(object sender, EventArgs e) { ClientScriptManager cs = Page.ClientScript; int saltSize = 5; string salt = CreateSalt(saltSize); string passwordHash = CreatePasswordHash(txtPass.Text, salt);kashifilyaz
Participant
1144 Points
198 Posts
Re: Hashing pass
Jun 08, 2012 08:51 PM|LINK
2- Login page
protected void imgBtnLogin_Click(object sender, ImageClickEventArgs e) { ClientScriptManager cs = Page.ClientScript; string userName = txtName.Text; string pass = txtPass.Text; pass = CreatePasswordHash(pass,CreateSalt(5)); string sqlSel = "select * from userRegister where username=@name and userPass=@pass"; if (operateData.login(sqlSel, userName, pass)) { Session["userName"] = txtName.Text; string sql = "select * from userRegister where userName='" + Session["userName"] + "'"; SqlDataReader sdr = operateData.getRow(sql); sdr.Read(); if (Convert.ToBoolean(sdr["lock"])) { Session["userName"] = null; cs.RegisterStartupScript(this.GetType(), "true", "<script>alert('" + sdr["lockCause"].ToString() + "');location='index.aspx'</script>"); } else cs.RegisterStartupScript(this.GetType(), "true", "<script>alert('Login is successful!Click to return Home');location='user/userIndex.aspx'</script>"); } else { cs.RegisterStartupScript(this.GetType(), "false", "<script>alert('User name or password is incorrect!')</script>"); } }Convert pass to hash and then compare with stored password
mkf
Member
7 Points
54 Posts
Re: Hashing pass
Jun 08, 2012 09:23 PM|LINK
Thanks for replay, but still have login problem.. Pass still not verified
wikkard
Member
204 Points
38 Posts
Re: Hashing pass
Jun 12, 2012 05:56 AM|LINK
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Security.Cryptography; using System.Runtime.InteropServices; namespace Utils.Encryption { [Guid("4EE61A1D-142F-4e8b-B0A2-9C5794ADCDF9")] public interface AESEncryptionInterface { string Encrypt(string PlainText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize); string Decrypt(string CipherText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize); string ComputeHash(string plainText, string hashAlgorithm, string Salt); bool VerifyHash(string plainText, string hashAlgorithm, string hashValue); string ByteArrayToString(byte[] inputArray); byte[] StringToByteArray(string inputString); byte[] GenerateSaltBytes(); string GenerateSaltString(); string GenerateRandomString(int length); int GenerateRandomNumber(int minValue, int maxValue); byte[] GenerateRandomByteArray(int length); string GenerateRandomPassword(int length); } [Guid("53B906B6-262B-493a-AA93-AFD0D3BFEA81"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface AESEncryptionEvents { } [Guid("CB56A796-EA66-4def-90BB-7DD025BEF028"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(AESEncryptionEvents))] public class AESEncryption : AESEncryptionInterface { public string lastError = ""; public bool hasError = false; public string Encrypt(string PlainText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize) { try { byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes); MemoryStream MemStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write); cryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length); cryptoStream.FlushFinalBlock(); byte[] CipherTextBytes = MemStream.ToArray(); MemStream.Close(); cryptoStream.Close(); hasError = false; return Convert.ToBase64String(CipherTextBytes); } catch (Exception ex) { hasError = true; lastError = ex.Message; return null; } } public string Decrypt(string CipherText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize) { try { byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] CipherTextBytes = Convert.FromBase64String(CipherText); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes); MemoryStream MemStream = new MemoryStream(CipherTextBytes); CryptoStream cryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read); byte[] PlainTextBytes = new byte[CipherTextBytes.Length]; int ByteCount = cryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); MemStream.Close(); cryptoStream.Close(); hasError = false; return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount); } catch (Exception ex) { hasError = true; lastError = ex.Message; return null; } } public string ByteArrayToString(byte[] inputArray) { System.Text.Encoding enc = System.Text.Encoding.ASCII; return enc.GetString(inputArray); } public byte[] StringToByteArray(string inputString) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); return enc.GetBytes(inputString); } public string ComputeHash(string plainText, string hashAlgorithm, string salt) { byte[] saltBytes = null; // If salt is not specified, generate it on the fly. saltBytes = StringToByteArray(salt); if (saltBytes == null) { // Define min and max salt sizes. int minSaltSize = 4; int maxSaltSize = 8; // Generate a random number for the size of the salt. Random random = new Random(); int saltSize = random.Next(minSaltSize, maxSaltSize); // Allocate a byte array, which will hold the salt. saltBytes = new byte[saltSize]; // Initialize a random number generator. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); // Fill the salt with cryptographically strong byte values. rng.GetNonZeroBytes(saltBytes); } // Convert plain text into a byte array. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // Allocate array, which will hold plain text and salt. byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; // Copy plain text bytes into resulting array. for (int i = 0; i < plainTextBytes.Length; i++) plainTextWithSaltBytes[i] = plainTextBytes[i]; // Append salt bytes to the resulting array. for (int i = 0; i < saltBytes.Length; i++) plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i]; // Because we support multiple hashing algorithms, we must define // hash object as a common (abstract) base class. We will specify the // actual hashing algorithm class later during object creation. HashAlgorithm hash; // Make sure hashing algorithm name is specified. if (hashAlgorithm == null) hashAlgorithm = ""; // Initialize appropriate hashing algorithm class. switch (hashAlgorithm.ToUpper()) { case "SHA1": hash = new SHA1Managed(); break; case "SHA256": hash = new SHA256Managed(); break; case "SHA384": hash = new SHA384Managed(); break; case "SHA512": hash = new SHA512Managed(); break; default: hash = new MD5CryptoServiceProvider(); break; } // Compute hash value of our plain text with appended salt. byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes); // Create array which will hold hash and original salt bytes. byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length]; // Copy hash bytes into resulting array. for (int i = 0; i < hashBytes.Length; i++) hashWithSaltBytes[i] = hashBytes[i]; // Append salt bytes to the result. for (int i = 0; i < saltBytes.Length; i++) hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i]; // Convert result into a base64-encoded string. string hashValue = Convert.ToBase64String(hashWithSaltBytes); // Return the result. return hashValue; } public bool VerifyHash(string plainText, string hashAlgorithm, string hashValue) { // Convert base64-encoded hash value into a byte array. byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue); // We must know size of hash (without salt). int hashSizeInBits, hashSizeInBytes; // Make sure that hashing algorithm name is specified. if (hashAlgorithm == null) hashAlgorithm = ""; // Size of hash is based on the specified algorithm. switch (hashAlgorithm.ToUpper()) { case "SHA1": hashSizeInBits = 160; break; case "SHA256": hashSizeInBits = 256; break; case "SHA384": hashSizeInBits = 384; break; case "SHA512": hashSizeInBits = 512; break; default: // Must be MD5 hashSizeInBits = 128; break; } // Convert size of hash from bits to bytes. hashSizeInBytes = hashSizeInBits / 8; // Make sure that the specified hash value is long enough. if (hashWithSaltBytes.Length < hashSizeInBytes) return false; // Allocate array to hold original salt bytes retrieved from hash. byte[] saltBytes = new byte[hashWithSaltBytes.Length - hashSizeInBytes]; // Copy salt from the end of the hash to the new array. for (int i = 0; i < saltBytes.Length; i++) saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i]; // Compute a new hash string. string expectedHashString = ComputeHash(plainText, hashAlgorithm, ByteArrayToString(saltBytes)); // If the computed hash matches the specified hash, // the plain text value must be correct. return (hashValue == expectedHashString); } public byte[] GenerateSaltBytes() { // We don't have the length, yet. int saltLen = 0; int minSaltLen = 16; int maxSaltLen = 32; // If min and max salt values are the same, it should not be random. saltLen = GenerateRandomNumber(minSaltLen, maxSaltLen); // Allocate byte array to hold our salt. byte[] salt = new byte[saltLen]; // Populate salt with cryptographically strong bytes. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetNonZeroBytes(salt); // Split salt length (always one byte) into four two-bit pieces and // store these pieces in the first four bytes of the salt array. salt[0] = (byte)((salt[0] & 0xfc) | (saltLen & 0x03)); salt[1] = (byte)((salt[1] & 0xf3) | (saltLen & 0x0c)); salt[2] = (byte)((salt[2] & 0xcf) | (saltLen & 0x30)); salt[3] = (byte)((salt[3] & 0x3f) | (saltLen & 0xc0)); return salt; } public string GenerateSaltString() { // We don't have the length, yet. int saltLen = 0; int minSaltLen = 16; int maxSaltLen = 32; saltLen = GenerateRandomNumber(minSaltLen, maxSaltLen); // Allocate byte array to hold our salt. byte[] salt = new byte[saltLen]; // Populate salt with cryptographically strong bytes. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetNonZeroBytes(salt); // Split salt length (always one byte) into four two-bit pieces and // store these pieces in the first four bytes of the salt array. salt[0] = (byte)((salt[0] & 0xfc) | (saltLen & 0x03)); salt[1] = (byte)((salt[1] & 0xf3) | (saltLen & 0x0c)); salt[2] = (byte)((salt[2] & 0xcf) | (saltLen & 0x30)); salt[3] = (byte)((salt[3] & 0x3f) | (saltLen & 0xc0)); return Convert.ToBase64String(salt); } public string GenerateRandomString(int length) { //Create and populate random byte array byte[] randomArray = new byte[length]; string randomString; //Create random salt and convert to string RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(randomArray); randomString = Convert.ToBase64String(randomArray); return randomString; } public byte[] GenerateRandomByteArray(int length) { //Create and populate random byte array byte[] randomArray = new byte[length]; string randomString; //Create random salt and convert to string RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(randomArray); return randomArray; } public int GenerateRandomNumber(int minValue, int maxValue) { // We will make up an integer seed from 4 bytes of this array. byte[] randomBytes = new byte[4]; // Generate 4 random bytes. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(randomBytes); // Convert four random bytes into a positive integer value. int seed = ((randomBytes[0] & 0x7f) << 24) | (randomBytes[1] << 16) | (randomBytes[2] << 8) | (randomBytes[3]); // Now, this looks more like real randomization. Random random = new Random(seed); // Calculate a random number. return random.Next(minValue, maxValue + 1); } public string GenerateRandomPassword(int length) { //Create and populate random byte array byte[] randomArray = new byte[length]; string randomString; //Create random salt and convert to string //use only printable ascii characters RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(randomArray); randomString = Convert.ToBase64String(randomArray); return randomString; } } }www.icle.com.au
www.wikkard.net
mkf
Member
7 Points
54 Posts
Re: Hashing pass
Jun 12, 2012 04:55 PM|LINK
Thanks for replay but can you explain what you mean: Did you mean to create a class object name Utils.Encryption, but can you explain with more details how to use it inside login page and the register page, what code that I store in database??? The store hash pass will change every time user input its pass so how to verified it from data base
wikkard
Member
204 Points
38 Posts
Re: Hashing pass
Jun 13, 2012 12:32 AM|LINK
Yes the stored pass will change each time, but by using the verify hash function in the class I provided you can validate the the hash is correct.
www.icle.com.au
www.wikkard.net
mkf
Member
7 Points
54 Posts
Re: Hashing pass
Jun 13, 2012 06:11 PM|LINK
Thanks