I`m trying to make a log in system for my app and want to use sha256 with salt for storing passwords. Problem is it when I hash the same password with the same salt again in order to check it I get different results. here is the code for both of the functions
String[] securePassword(String password)
{
String[] result = new string[2];
byte[] salt = new byte[32];
System.Security.Cryptography.RNGCryptoServiceProvider.Create().GetBytes(salt);
byte[] plainTextBytes = UnicodeEncoding.Unicode.GetBytes(password);
byte[] combinedBytes = new byte[plainTextBytes.Length + salt.Length];
System.Buffer.BlockCopy(plainTextBytes, 0, combinedBytes, 0, plainTextBytes.Length);
System.Buffer.BlockCopy(salt, 0, combinedBytes, plainTextBytes.Length, salt.Length);
System.Security.Cryptography.HashAlgorithm hashAlgo = new System.Security.Cryptography.SHA256Managed();
byte[] hash = hashAlgo.ComputeHash(combinedBytes);
result[0] = Convert.ToBase64String(hash);
result[1] = Convert.ToBase64String(salt);
return result;
}
bool check_password(String password_introduced,String Password,String Salt)
{
byte[] salt = Convert.FromBase64String(Salt);
byte[] plainTextBytes = UnicodeEncoding.Unicode.GetBytes(password_introduced);
byte[] combinedBytes = new byte[plainTextBytes.Length + salt.Length];
System.Buffer.BlockCopy(plainTextBytes, 0, combinedBytes, 0, plainTextBytes.Length);
System.Buffer.BlockCopy(salt, 0, combinedBytes, plainTextBytes.Length, salt.Length);
System.Security.Cryptography.HashAlgorithm hashAlgo = new System.Security.Cryptography.SHA256Managed();
byte[] hash = hashAlgo.ComputeHash(combinedBytes);
String result = Convert.ToBase64String(hash);
return (result == Password);
}
Well, what you have is working for me. I cleaned things up a little, including taking out repeating code (DRY) and standardizing the casing on your methods and parameters.
using System.Text;
using System;
using System.Security.Cryptography;
namespace ConsoleApp1
{
public class Program
{
static void Main()
{
string[] result = SecurePassword("foobar");
bool valid = CheckPassword("foobar", result[0], result[1]);
}
static string[] SecurePassword(string password)
{
string[] result = new string[2];
byte[] salt = new byte[32];
RNGCryptoServiceProvider.Create().GetBytes(salt);
byte[] plainTextBytes = UnicodeEncoding.Unicode.GetBytes(password);
byte[] hash = CreateHash(plainTextBytes, salt);
result[0] = Convert.ToBase64String(hash);
result[1] = Convert.ToBase64String(salt);
return result;
}
static bool CheckPassword(string password_introduced, string password, string originalSalt)
{
byte[] salt = Convert.FromBase64String(originalSalt);
byte[] plainTextBytes = UnicodeEncoding.Unicode.GetBytes(password_introduced);
byte[] hash = CreateHash(plainTextBytes, salt);
string result = Convert.ToBase64String(hash);
return (result == password);
}
static byte[] CreateHash(byte[] plainTextBytes, byte[] salt)
{
byte[] combinedBytes = new byte[plainTextBytes.Length + salt.Length];
Buffer.BlockCopy(plainTextBytes, 0, combinedBytes, 0, plainTextBytes.Length);
Buffer.BlockCopy(salt, 0, combinedBytes, plainTextBytes.Length, salt.Length);
HashAlgorithm hashAlgo = new System.Security.Cryptography.SHA256Managed();
byte[] hash = hashAlgo.ComputeHash(combinedBytes);
return hash;
}
}
}
The call to CheckPassword comes back true.
Please use a dedicated password hash function like BCrypt instead. The SHA* hashes are not appropriate to hash passwords, because they are way too fast and therefore can be brute-forced too easily, even with an off the shelf GPU (about 7 Giga SHA256 per sec nowadays).
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
string passwordHash = BCrypt.HashPassword("my password");
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
bool isCorrect = BCrypt.Verify("my password", passwordHash);
Related
I want to encrypt password using both in CryptoJS and C#. Unfortunately, my C# code fails to generate the proper value. This is my code
internal static byte[] ComputeSha256(this byte[] value)
{
using (SHA256 sha256Hash = SHA256.Create())
return sha256Hash.ComputeHash(value);
}
internal static byte[] ComputeSha256(this string value) => ComputeSha256(Encoding.UTF8.GetBytes(value));
internal static byte[] ComputeMD5(this byte[] value)
{
using (MD5 md5 = MD5.Create())
return md5.ComputeHash(value);
}
internal static byte[] ComputeMD5(this string value) => ComputeMD5(Encoding.UTF8.GetBytes(value));
internal static byte[] CombineByteArray(byte[] first, byte[] second)
{
byte[] bytes = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, bytes, 0, first.Length);
Buffer.BlockCopy(second, 0, bytes, first.Length, second.Length);
return bytes;
}
internal static string EncryptPassword()
{
using (AesManaged aes = new AesManaged())
{
//CLIENT SIDE PASSWORD HASH
/*
var password = '12345';
var passwordMd5 = CryptoJS.MD5(password);
var passwordKey = CryptoJS.SHA256(CryptoJS.SHA256(passwordMd5 + '12345678') + '01234567890123456');
var encryptedPassword = CryptoJS.AES.encrypt(passwordMd5, passwordKey, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.NoPadding });
encryptedPassword = CryptoJS.enc.Base64.parse(encryptedPassword.toString()).toString(CryptoJS.enc.Hex);
//encryptedPassword result is c3de82e9e8a28a4caded8c2ef0d49c80
*/
var y1 = Encoding.UTF8.GetBytes("12345678");
var y2 = Encoding.UTF8.GetBytes("01234567890123456");
var password = "12345";
var passwordMd5 = ComputeMD5(password);
var xkey = CombineByteArray(ComputeSha256(CombineByteArray(passwordMd5, y1)), y2);
var passwordKey = ComputeSha256(xkey);
aes.Key = passwordKey;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.None;
ICryptoTransform crypt = aes.CreateEncryptor();
byte[] cipher = crypt.TransformFinalBlock(passwordMd5, 0, passwordMd5.Length);
var encryptedPassword = BitConverter.ToString(cipher).Replace("-", "").ToLower();
return encryptedPassword; //e969b60e87339625c32f805f17e6f993
}
}
The result of the C# code above is e969b60e87339625c32f805f17e6f993. It should be the same with CryptoJS c3de82e9e8a28a4caded8c2ef0d49c80. What is wrong here?
In the CryptoJS code hashes (in the form of WordArrays) and strings are added in several places. Thereby the WordArray is implicitly encoded with toString() into a hex string with lowercase letters. This is missing in the C# code.
In the C# code the addition is done with CombineByteArray(), where the hash is passed in the parameter first as byte[]. Therefore this parameter must first be converted to a hex encoded string with lowercase letters and then UTF8 encoded, e.g.:
internal static byte[] CombineByteArray(byte[] first, byte[] second)
{
// Hex encode (with lowercase letters) and Utf8 encode
string hex = ByteArrayToString(first).ToLower();
first = Encoding.UTF8.GetBytes(hex);
byte[] bytes = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, bytes, 0, first.Length);
Buffer.BlockCopy(second, 0, bytes, first.Length, second.Length);
return bytes;
}
where ByteArrayToString() is from here.
With this change, the C# code gives the same result as the CryptoJS code.
I am not quite clear about the purpose of the CryptoJS code. Usually plaintext and key are independent, i.e. are not derived from the same password.
Perhaps this is supposed to implement a custom password-based key derivation function. If so, and unless a custom implementation is mandatory for compatibility reasons, it is more secure to use a proven algorithm such as Argon2 or PBKDF2. In particular, the lack of a salt/work factor is insecure.
I need to do 128 bit AES encryption on an application in Windows Phone 8.1. I used the following code for Encrypting and Decrypting the data respectively:
private string GetEncryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Encoding.UTF8.GetBytes(content);
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, null);
return Encoding.UTF8.GetString(cipherText, 0, cipherText.Length);
}
private string GetDecryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Encoding.UTF8.GetBytes(content);
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Decrypt(key, data, null);
return Encoding.UTF8.GetString(cipherText, 0, cipherText.Length);
}
But the encryption and decryption doesn't seem to be working properly. It is getting encrypted to some unicode characters and throwing a crash on decrypting:
Length is not a multiple of block size and no padding is
selected.\r\nParameter name: ciphertext
What am I doing wrong here? Can someone please help?
EDIT
After a lot more time with Google, I found the following methods for encryption and decryption, but they doesn't seem to work either.
public string GetEncryptedContent(string input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
CryptographicHash Hash_AES = HAP.CreateHash();
string encrypted = "";
try
{
byte[] hash = new byte[32];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(pass)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(input));
encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));
return encrypted;
}
catch (Exception ex)
{
return null;
}
}
public string GetDecryptedContent(string input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
CryptographicHash Hash_AES = HAP.CreateHash();
string decrypted = "";
try
{
byte[] hash = new byte[32];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(pass)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
byte[] Decrypted;
CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
decrypted = Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
return decrypted;
}
catch (Exception ex)
{
return null;
}
}
EDIT 2
Finally managed to get the encryption working properly, but the decryption is still not working presumably because the encoding I am passing is not the right one:
private string GetEncryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Encoding.UTF8.GetBytes(content);
byte[] iv = new byte[128 / 8]; // Adding this solved the encryption issue.
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, iv);
return Convert.ToBase64String(cipherText);
}
private string GetDecryptedContent(string content)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(EncryptionKey);
byte[] data = Convert.FromBase64String(content); // Believe this is where the issue is, but not able to figure it out.
byte[] iv = new byte[128 / 8]; // Added this to make the decryption work the same way.
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Decrypt(key, data, iv);
return Convert.ToBase64String(cipherText);
}
I finally solved the problem. The problem was with the text encoding. Using the correct encoding solved the issue. The working code below:
public static string EncryptAES(string content, string password)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(password);
byte[] data = Encoding.UTF8.GetBytes(content);
byte[] iv = new byte[keyMaterial.Length];
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, iv);
return Convert.ToBase64String(cipherText);
}
public static string DecryptAES(string content, string password)
{
byte[] keyMaterial = Encoding.UTF8.GetBytes(password);
byte[] data = Convert.FromBase64String(content);
byte[] iv = new byte[keyMaterial.Length];
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] cipherText = WinRTCrypto.CryptographicEngine.Decrypt(key, data, iv);
return Encoding.UTF8.GetString(cipherText, 0, cipherText.Length);
}
WinRTCrypto is available as part of PCLCrypto.
I have a table with login credentials for a Telerik Sitefinity system. I want to use the same login credentials, but with a different application that doesn't have Sitefinity libraries. I'm struggling with the password encoding, which is set to Hash (Default is SHA1 algorithm).
I tried using the following code to encode passwords, but it doesn't match up with what Sitefinity generated.
public string EncodePassword(string pass, string salt)
{
byte[] bytes = Encoding.Unicode.GetBytes(pass);
byte[] src = Convert.FromBase64String(salt);
byte[] dst = new byte[src.Length + bytes.Length];
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
byte[] inArray = algorithm.ComputeHash(dst);
return Convert.ToBase64String(inArray);
}
EXAMPLE:
PASSWORD: password111
SALT: 94EBE09530D9F5FAE3D002A4BF262D2F (as saved in the SF user table)
Hash with function above: 8IjcFO4ad8BdkD40NJcgD0iGloU=
Hash in table generated by SF:A24GuU8OasJ2bicvT/E4ZiKfAT8=
I have searched online if SF generates the encoded password differently, but can't find any results. How can I use the login credentials created by SF without SF libraries?
You right, Sitefinity is using SHA1 algorithm, but you need to use additional ValidationKey from configuration settings.
Here the working example of code for you:
private static bool CheckValidPassword(string password)
{
//from sf_users column [salt]
var userSalt = "420540B274162AA093FDAC86894F3172";
//from sf_users column [passwd]
var userPassword = "a99j8I0em8DOP1IAJO/O7umQ+H0=";
//from App_Data\Sitefinity\Configuration\SecurityConfig.config attribute "validationKey"
var validationKey = "862391D1B281951D5D92837F4DB9714E0A5630F96483FF39E4307AE733424C557354AE85FF1C00D73AEB48DF3421DD159F6BFA165FF8E812341611BDE60E0D4A";
return userPassword == ComputeHash(password + userSalt, validationKey);
}
internal static string ComputeHash(string data, string key)
{
byte[] hashKey = HexToBytes(key);
HMACSHA1 hmacshA1 = new HMACSHA1();
hmacshA1.Key = hashKey;
var hash = hmacshA1.ComputeHash(Encoding.Unicode.GetBytes(data));
return Convert.ToBase64String(hash);
}
public static byte[] HexToBytes(string hexString)
{
byte[] numArray = new byte[hexString.Length / 2];
for (int index = 0; index < numArray.Length; ++index)
numArray[index] = Convert.ToByte(hexString.Substring(index * 2, 2), 16);
return numArray;
}
I use Login control and membership asp.net 4. and create user with passwrod = "12345678", my password hash in database is "h8A5hga0Cy93JsKxYnJl/U2AluU=" and passwordsalt is "UhVlqavmEX9CiKcUXkSwCw==".
Then I use this code for hash password in other project:
public string HashPassword(string pass, string salt)
{
byte[] bytes = Encoding.Unicode.GetBytes(pass);
byte[] src = Encoding.Unicode.GetBytes(salt);
byte[] dst = new byte[src.Length + bytes.Length];
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
byte[] inArray = algorithm.ComputeHash(dst);
return Convert.ToBase64String(inArray);
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = HashPassword("12345678", "UhVlqavmEX9CiKcUXkSwCw==");
}
textBox2.Text = "YM/JNwFqlL+WA3SINQp48BIxZRI=". But textBox2.Text != my password hashed with login control in database. it is "h8A5hga0Cy93JsKxYnJl/U2AluU=".
Edit:
It is algorithm hash with login control?
public string EncodePassword(string pass, string salt)
{
byte[] bytes = Encoding.Unicode.GetBytes(pass);
byte[] src = Convert.FromBase64String(salt);
byte[] dst = new byte[src.Length + bytes.Length];
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
byte[] inArray = algorithm.ComputeHash(dst);
return Convert.ToBase64String(inArray);
}
MD5 and SHA1 are not encryption algorithms. They are hashing algorithms.
It is a one way formula. Running MD5 or SHA1 on a particular string gives a hash that is always the same. It isn't possible to reverse the function to get back to the original string.
so, you can not decrypt.
if you want encrypt & decrypt, you can use below methods.
public class Encryption
{
private const string _defaultKey = "*3ld+43j";
public static string Encrypt(string toEncrypt, string key)
{
var des = new DESCryptoServiceProvider();
var ms = new MemoryStream();
VerifyKey(ref key);
des.Key = HashKey(key, des.KeySize / 8);
des.IV = HashKey(key, des.KeySize / 8);
byte[] inputBytes = Encoding.UTF8.GetBytes(toEncrypt);
var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputBytes, 0, inputBytes.Length);
cs.FlushFinalBlock();
return HttpServerUtility.UrlTokenEncode(ms.ToArray());
}
public static string Decrypt(string toDecrypt, string key)
{
var des = new DESCryptoServiceProvider();
var ms = new MemoryStream();
VerifyKey(ref key);
des.Key = HashKey(key, des.KeySize / 8);
des.IV = HashKey(key, des.KeySize / 8);
byte[] inputBytes = HttpServerUtility.UrlTokenDecode(toDecrypt);
var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputBytes, 0, inputBytes.Length);
cs.FlushFinalBlock();
var encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
/// <summary>
/// Make sure key is exactly 8 characters
/// </summary>
/// <param name="key"></param>
private static void VerifyKey(ref string key)
{
if (string.IsNullOrEmpty(key))
key = _defaultKey;
key = key.Length > 8 ? key.Substring(0, 8) : key;
if (key.Length < 8)
{
for (int i = key.Length; i < 8; i++)
{
key += _defaultKey[i];
}
}
}
private static byte[] HashKey(string key, int length)
{
var sha = new SHA1CryptoServiceProvider();
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] hash = sha.ComputeHash(keyBytes);
byte[] truncateHash = new byte[length];
Array.Copy(hash, 0, truncateHash, 0, length);
return truncateHash;
}
}
try
private static string CreateSalt()
{
//Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[32];
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");
return hashedPwd;
}
Login control doesn't encode or decode password. Instead, it is MembershipProvider's job.
Here is the Hash Algorithm used by new ASP.Net Universal Provider.
private static string GenerateSalt()
{
byte[] numArray = new byte[16];
(new RNGCryptoServiceProvider()).GetBytes(numArray);
string base64String = Convert.ToBase64String(numArray);
return base64String;
}
private string EncodePassword(string pass, int passwordFormat, string salt)
{
byte[] numArray;
byte[] numArray1;
string base64String;
bool length = passwordFormat != 0;
if (length)
{
byte[] bytes = Encoding.Unicode.GetBytes(pass);
byte[] numArray2 = Convert.FromBase64String(salt);
byte[] numArray3 = null;
HashAlgorithm hashAlgorithm = HashAlgorithm.Create(Membership.HashAlgorithmType);
if (hashAlgorithm as KeyedHashAlgorithm == null)
{
numArray1 = new byte[(int) numArray2.Length + (int) bytes.Length];
Buffer.BlockCopy(numArray2, 0, numArray1, 0, (int) numArray2.Length);
Buffer.BlockCopy(bytes, 0, numArray1, (int) numArray2.Length, (int) bytes.Length);
numArray3 = hashAlgorithm.ComputeHash(numArray1);
}
else
{
KeyedHashAlgorithm keyedHashAlgorithm = (KeyedHashAlgorithm) hashAlgorithm;
if (keyedHashAlgorithm.Key.Length != numArray2.Length)
{
if (keyedHashAlgorithm.Key.Length >= (int) numArray2.Length)
{
numArray = new byte[(int) keyedHashAlgorithm.Key.Length];
int num = 0;
while (true)
{
length = num < (int) numArray.Length;
if (!length)
{
break;
}
int num1 = Math.Min((int) numArray2.Length, (int) numArray.Length - num);
Buffer.BlockCopy(numArray2, 0, numArray, num, num1);
num = num + num1;
}
keyedHashAlgorithm.Key = numArray;
}
else
{
numArray = new byte[(int) keyedHashAlgorithm.Key.Length];
Buffer.BlockCopy(numArray2, 0, numArray, 0, (int) numArray.Length);
keyedHashAlgorithm.Key = numArray;
}
}
else
{
keyedHashAlgorithm.Key = numArray2;
}
numArray3 = keyedHashAlgorithm.ComputeHash(bytes);
}
base64String = Convert.ToBase64String(numArray3);
}
else
{
base64String = pass;
}
return base64String;
}
I have used update function of Sha256 class in my c++ code to include a few string into one hash value, but I can't find this function in .net class Sha256. This function is presented in C++ realizations, Java realizations of Sha, but not in .net?
Sample code in C++:
l_ceSHA2.Init();
for ( l_dwordCnt = 0; l_dwordCnt < l_dwordHashRounds; l_dwordCnt++)
{
l_ceSHA2.Update( mp_strPassword, strlen( mp_strPassword )));
l_ceSHA2.Update( mp_byteSalt, 32 );
}
l_ceSHA2.Final( mp_byteCryptoKey);
So, it's like PBKDF, but easier.
Sha256 code in C for reference
You can use TransformBlock. Here is an example showing how:
using System;
using System.Text;
using System.Security.Cryptography;
// Example code for using TransformBlock to hash data in chunks
namespace HashTest
{
class HashTest
{
static void Main(string[] args)
{
SHA256 hash = SHA256.Create();
ASCIIEncoding encoding = new ASCIIEncoding();
string password = "password";
// Hash a string using ComputeHash
string sourcetext = password;
Console.WriteLine(sourcetext);
byte[] sourcebytes = encoding.GetBytes(sourcetext);
byte[] hashBytes = hash.ComputeHash(sourcebytes);
string hashStr = BitConverter.ToString(hashBytes).Replace("-", "");
Console.WriteLine(hashStr);
// Hash exactly two copies of a string
// (used to cross verify other methods below).
Console.WriteLine();
sourcetext = password + password;
Console.WriteLine(sourcetext);
sourcebytes = encoding.GetBytes(sourcetext);
hashBytes = hash.ComputeHash(sourcebytes);
hashStr = BitConverter.ToString(hashBytes).Replace("-", "");
Console.WriteLine(hashStr);
// Hash a string using TransformFinalBlock
Console.WriteLine();
sourcetext = password;
sourcebytes = encoding.GetBytes(sourcetext);
Console.WriteLine(sourcetext);
hash.TransformFinalBlock(sourcebytes, 0, sourcebytes.Length);
hashBytes = hash.Hash;
hashStr = BitConverter.ToString(hashBytes).Replace("-", "");
Console.WriteLine(hashStr);
// At this point we've finalized the hash. To
// reuse it we must first call Initialize().
// Hash string twice using TransformBlock / TransformFinalBlock
Console.WriteLine();
hash.Initialize();
sourcetext = password;
sourcebytes = encoding.GetBytes(sourcetext);
Console.Write(sourcetext);
hash.TransformBlock(sourcebytes, 0, sourcebytes.Length, null, 0);
Console.WriteLine(sourcetext);
hash.TransformFinalBlock(sourcebytes, 0, sourcebytes.Length);
hashBytes = hash.Hash;
hashStr = BitConverter.ToString(hashBytes).Replace("-", "");
Console.WriteLine(hashStr);
// Hash string twice using TransformBlock in a loop
Console.WriteLine();
hash.Initialize();
sourcetext = password;
sourcebytes = encoding.GetBytes(sourcetext);
for (int i = 0; i < 2; ++i)
{
Console.Write(sourcetext);
hash.TransformBlock(sourcebytes, 0, sourcebytes.Length, null, 0);
}
Console.WriteLine();
hash.TransformFinalBlock(sourcebytes, 0, 0);
hashBytes = hash.Hash;
hashStr = BitConverter.ToString(hashBytes).Replace("-", "");
Console.WriteLine(hashStr);
}
}
}