public void ComputeAndVerifyHash_File() { var testFilePath = Path.GetTempFileName(); GenericHashResult verifyResult = new GenericHashResult(); var errorMessage = ""; File.WriteAllText(testFilePath, _testString); var hashResult = _md5.ComputeFileHash(testFilePath); if (hashResult.Success) { verifyResult = _md5.VerifyFileHash(hashResult.HashString, testFilePath); if (!verifyResult.Success) { errorMessage = verifyResult.Message; } } else { errorMessage = hashResult.Message; } Assert.IsTrue((hashResult.Success && verifyResult.Success), errorMessage); }
public GenericHashResult HashFile(string sourceFilePath, bool verbose = false) { if (!File.Exists(sourceFilePath)) { return(new GenericHashResult() { Success = false, Message = $"File \"{sourceFilePath}\" not found." }); } StringBuilder sb = null; GenericHashResult result = null; try { using (var md5 = System.Security.Cryptography.MD5.Create()) { using (var fs = File.OpenRead(sourceFilePath)) { sb = new StringBuilder(); var hashedBytes = md5.ComputeHash(fs); for (int i = 0; i < hashedBytes.Length; i++) { sb.Append(hashedBytes[i].ToString("X2")); } result = new GenericHashResult() { Success = true, Message = $"File \"{sourceFilePath}\" succesfully hashed.", Hash = sb.ToString() }; } } } catch (Exception ex) { return(new GenericHashResult() { Success = false, Message = ex.ToString() }); } finally { sb.Clear(); sb = null; } return(result); }
public GenericHashResult HashString(string stringToBeHashed) { if (string.IsNullOrWhiteSpace(stringToBeHashed)) { return(new GenericHashResult() { Success = false, Message = "String to be hashed required." }); } StringBuilder sb = null; GenericHashResult result = null; try { using (var md5 = System.Security.Cryptography.MD5.Create()) { byte[] stringToBeHashedBytes = Encoding.UTF8.GetBytes(stringToBeHashed); byte[] hashedBytes = md5.ComputeHash(stringToBeHashedBytes); sb = new StringBuilder(); for (int i = 0; i < hashedBytes.Length; i++) { sb.Append(hashedBytes[i].ToString("X2")); } result = new GenericHashResult() { Success = true, Message = "String succesfully hashed.", Hash = sb.ToString() }; } } catch (Exception ex) { return(new GenericHashResult() { Success = false, Message = ex.ToString() }); } finally { sb.Clear(); sb = null; } return(result); }
internal GenericHashResult ComputeHash(Enums.HashAlgorithm hashAlgorithm, byte[] bytesToComputeHash, int offset = 0, int count = 0) { if (bytesToComputeHash == null || bytesToComputeHash.Length <= 0) { return(new GenericHashResult() { Success = false, Message = MessageDictionary.Instance["Hash.InputRequired"] }); } GenericHashResult result = null; try { using (var hashAlg = (HashAlgorithm)CryptoConfig.CreateFromName(hashAlgorithm.ToString())) { //offset = (offset == 0 ? 0 : offset); count = (count == 0 ? bytesToComputeHash.Length : count); byte[] hash = hashAlg.ComputeHash(bytesToComputeHash, offset, count); result = new GenericHashResult() { Success = true, Message = MessageDictionary.Instance["Hash.ComputeSuccess"], HashBytes = hash, HashString = Encoding.Hexadecimal.ToHexString(hash) }; } } catch (Exception ex) { return(new GenericHashResult() { Success = false, Message = ex.ToString() }); } return(result); }
public void ComputeAndVerifyHash_String() { var verifyResult = new GenericHashResult(); var errorMessage = ""; var hashResult = _sha384.ComputeHash(_testString); if (hashResult.Success) { verifyResult = _sha384.VerifyHash(hashResult.HashString, _testString); if (!verifyResult.Success) { errorMessage = verifyResult.Message; } } else { errorMessage = hashResult.Message; } Assert.IsTrue((hashResult.Success && verifyResult.Success), errorMessage); }
private static ExitCode RunHashOptionsAndReturnExitCode(HashOptions hashOptions) { GenericHashResult hashResult = null; switch (hashOptions.InputType.ToLower()) { case "string": { hashResult = (hashOptions.Algorithm.ToLower()) switch { "md5" => new MD5().ComputeHash(hashOptions.InputToComputeHash), "sha1" => new SHA1().ComputeHash(hashOptions.InputToComputeHash), "sha256" => new SHA256().ComputeHash(hashOptions.InputToComputeHash), "sha384" => new SHA384().ComputeHash(hashOptions.InputToComputeHash), "sha512" => new SHA512().ComputeHash(hashOptions.InputToComputeHash), "pbkdf2" => new PBKDF2_HMAC_SHA_1().ComputeHash(hashOptions.InputToComputeHash), "bcrypt" => new Hash.BCrypt().ComputeHash(hashOptions.InputToComputeHash), _ => new GenericHashResult() { Success = false, Message = $"Unknown algorithm \"{hashOptions.Algorithm}\"." }, }; } break; case "file": { switch (hashOptions.Algorithm.ToLower()) { case "md5": { using (var progressBar = new ProgressBar()) { var md5 = new MD5(); md5.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); }; hashResult = md5.ComputeFileHash(hashOptions.InputToComputeHash); } } break; case "sha1": { using (var progressBar = new ProgressBar()) { var sha1 = new SHA1(); sha1.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); }; hashResult = sha1.ComputeFileHash(hashOptions.InputToComputeHash); } } break; case "sha256": { using (var progressBar = new ProgressBar()) { var sha256 = new SHA256(); sha256.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); }; hashResult = sha256.ComputeFileHash(hashOptions.InputToComputeHash); } } break; case "sha384": { using (var progressBar = new ProgressBar()) { var sha384 = new SHA384(); sha384.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); }; hashResult = sha384.ComputeFileHash(hashOptions.InputToComputeHash); } } break; case "sha512": { using (var progressBar = new ProgressBar()) { var sha512 = new SHA512(); sha512.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); }; hashResult = sha512.ComputeFileHash(hashOptions.InputToComputeHash); } } break; case "pbkdf2": case "bcrypt": hashResult = new GenericHashResult() { Success = false, Message = $"Algorithm \"{hashOptions.Algorithm}\" currently not available for file hashing." }; break; default: hashResult = new GenericHashResult() { Success = false, Message = $"Unknown algorithm \"{hashOptions.Algorithm}\"." }; break; } } break; default: hashResult = new GenericHashResult() { Success = false, Message = $"Unknown input type \"{hashOptions.InputType}\"." }; break; } if (hashResult.Success && !string.IsNullOrWhiteSpace(hashOptions.CompareHash)) { var hashesMatch = ( hashOptions.Algorithm.ToLower() != "bcrypt" && hashOptions.Algorithm.ToLower() != "pbkdf2" ? (hashResult.HashString).Equals(hashOptions.CompareHash, StringComparison.InvariantCultureIgnoreCase) : (hashOptions.Algorithm.ToLower() == "bcrypt" ? new Hash.BCrypt().VerifyHash(hashOptions.InputToComputeHash, hashOptions.CompareHash).Success : new Hash.PBKDF2_HMAC_SHA_1().VerifyHash(hashOptions.InputToComputeHash, hashOptions.CompareHash).Success ) ); var outputMessage = ( hashesMatch ? $"Computed hash MATCH with given hash: {(hashOptions.Algorithm.ToLower() != "bcrypt" ? hashResult.HashString : hashOptions.CompareHash)}" : $"Computed hash DOES NOT MATCH with given hash." + ( hashOptions.Algorithm.ToLower() != "bcrypt" ? $"\nComputed hash: {hashResult.HashString}\nGiven hash: {hashOptions.CompareHash}" : "" ) ); Console.WriteLine(outputMessage); return(hashesMatch ? ExitCode.Sucess : ExitCode.Error); } else if (hashResult.Success && string.IsNullOrWhiteSpace(hashOptions.CompareHash)) { Console.WriteLine(hashResult.HashString); return(ExitCode.Sucess); } else { Console.WriteLine(hashResult.Message); return(ExitCode.Error); } }
internal GenericHashResult ComputeFileHash(Enums.HashAlgorithm hashAlgorithm, string filePathToComputeHash, long offset = 0, long count = 0) { if (!File.Exists(filePathToComputeHash)) { return(new GenericHashResult() { Success = false, Message = $"{MessageDictionary.Instance["Common.FileNotFound"]} \"{filePathToComputeHash}\"." }); } GenericHashResult result = null; try { byte[] hash = null; using (var fStream = new FileStream(filePathToComputeHash, FileMode.Open, FileAccess.Read, FileShare.None)) { //offset = (offset == 0 ? 0 : offset); count = (count == 0 ? fStream.Length : count); fStream.Position = offset; byte[] buffer = new byte[(1024 * 4)]; long amount = (count - offset); using (var hashAlg = (HashAlgorithm)CryptoConfig.CreateFromName(hashAlgorithm.ToString())) { int percentageDone = 0; while (amount > 0) { int bytesRead = fStream.Read(buffer, 0, (int)Math.Min(buffer.Length, amount)); if (bytesRead > 0) { amount -= bytesRead; if (amount > 0) { hashAlg.TransformBlock(buffer, 0, bytesRead, buffer, 0); } else { hashAlg.TransformFinalBlock(buffer, 0, bytesRead); } var tmpPercentageDone = (int)(fStream.Position * 100 / count); if (tmpPercentageDone != percentageDone) { percentageDone = tmpPercentageDone; RaiseOnHashProgress(percentageDone, (percentageDone != 100 ? $"Computing hash ({percentageDone}%)..." : $"Hash computed ({percentageDone}%).")); } } else { throw new InvalidOperationException(); } } hash = hashAlg.Hash; } } result = new GenericHashResult() { Success = true, Message = MessageDictionary.Instance["Hash.ComputeSuccess"], HashString = Encoding.Hexadecimal.ToHexString(hash), HashBytes = hash }; } catch (Exception ex) { result = new GenericHashResult() { Success = false, Message = ex.ToString() }; } return(result); }
private static ExitCode RunHashOptionsAndReturnExitCode(HashOptions hashOptions) { GenericHashResult hashResult = null; switch (hashOptions.InputType.ToLower()) { case "string": { switch (hashOptions.Algorithm.ToLower()) { case "md5": hashResult = new MD5().HashString(hashOptions.InputToBeHashed); break; case "sha1": hashResult = new SHA1().HashString(hashOptions.InputToBeHashed); break; case "sha256": hashResult = new SHA256().HashString(hashOptions.InputToBeHashed); break; case "sha384": hashResult = new SHA384().HashString(hashOptions.InputToBeHashed); break; case "sha512": hashResult = new SHA512().HashString(hashOptions.InputToBeHashed); break; case "bcrypt": hashResult = new Hash.BCrypt().HashString(hashOptions.InputToBeHashed); break; default: hashResult = new GenericHashResult() { Success = false, Message = $"Unknown algorithm \"{hashOptions.Algorithm}\"." }; break; } } break; case "file": { switch (hashOptions.Algorithm.ToLower()) { case "md5": hashResult = new MD5().HashFile(hashOptions.InputToBeHashed, hashOptions.Verbose); break; case "sha1": hashResult = new SHA1().HashFile(hashOptions.InputToBeHashed, hashOptions.Verbose); break; case "sha256": hashResult = new SHA256().HashFile(hashOptions.InputToBeHashed, hashOptions.Verbose); break; case "sha384": hashResult = new SHA384().HashFile(hashOptions.InputToBeHashed, hashOptions.Verbose); break; case "sha512": hashResult = new SHA512().HashFile(hashOptions.InputToBeHashed, hashOptions.Verbose); break; case "bcrypt": hashResult = new GenericHashResult() { Success = false, Message = $"Algorithm \"{hashOptions.Algorithm}\" currently not available for file hashing." }; break; default: hashResult = new GenericHashResult() { Success = false, Message = $"Unknown algorithm \"{hashOptions.Algorithm}\"." }; break; } } break; default: hashResult = new GenericHashResult() { Success = false, Message = $"Unknown input type \"{hashOptions.InputType}\"." }; break; } if (hashResult.Success && !string.IsNullOrWhiteSpace(hashOptions.CompareHash)) { bool hashesMatch = ( hashOptions.Algorithm.ToLower() != "bcrypt" ? (hashResult.Hash).Equals(hashOptions.CompareHash, StringComparison.InvariantCultureIgnoreCase) : new Hash.BCrypt().Verify(hashOptions.InputToBeHashed, hashOptions.CompareHash).Success ); var outputMessage = ( hashesMatch ? $"Computed hash MATCH with given hash: {(hashOptions.Algorithm.ToLower() != "bcrypt" ? hashResult.Hash : hashOptions.CompareHash)}" : $"Computed hash DOES NOT MATCH with given hash." + ( hashOptions.Algorithm.ToLower() != "bcrypt" ? $"\nComputed hash: {hashResult.Hash}\nGiven hash: {hashOptions.CompareHash}" : "" ) ); Console.WriteLine(outputMessage); return(hashesMatch ? ExitCode.Sucess : ExitCode.Error); } else if (hashResult.Success && string.IsNullOrWhiteSpace(hashOptions.CompareHash)) { Console.WriteLine(hashResult.Hash); return(ExitCode.Sucess); } else { Console.WriteLine(hashResult.Message); return(ExitCode.Error); } }
internal GenericHashResult ComputeHash(Enums.HashAlgorithm hashAlgorithm, byte[] bytesToComputeHash, int offset = 0, int count = 0) { if (bytesToComputeHash == null || bytesToComputeHash.Length <= 0) { return(new GenericHashResult() { Success = false, Message = MessageDictionary.Instance["Hash.InputRequired"] }); } GenericHashResult result = null; try { HashAlgorithm hashAlg = null; #if CORERT switch (hashAlgorithm) { case Enums.HashAlgorithm.MD5: hashAlg = MD5.Create(); break; case Enums.HashAlgorithm.SHA1: hashAlg = SHA1.Create(); break; case Enums.HashAlgorithm.SHA256: hashAlg = SHA256.Create(); break; case Enums.HashAlgorithm.SHA384: hashAlg = SHA384.Create(); break; case Enums.HashAlgorithm.SHA512: hashAlg = SHA512.Create(); break; case Enums.HashAlgorithm.BCrypt: default: break; } #else hashAlg = (HashAlgorithm)CryptoConfig.CreateFromName(hashAlgorithm.ToString()); #endif using (hashAlg) { //offset = (offset == 0 ? 0 : offset); count = (count == 0 ? bytesToComputeHash.Length : count); byte[] hash = hashAlg.ComputeHash(bytesToComputeHash, offset, count); result = new GenericHashResult() { Success = true, Message = MessageDictionary.Instance["Hash.ComputeSuccess"], HashBytes = hash, HashString = Encoding.HighPerformanceHexadecimal.ToHexString(hash) }; } } catch (Exception ex) { return(new GenericHashResult() { Success = false, Message = ex.ToString() }); } return(result); }
internal GenericHashResult ComputeFileHash(Enums.HashAlgorithm hashAlgorithm, string filePathToComputeHash, long offset = 0, long count = 0) { if (!File.Exists(filePathToComputeHash)) { return(new GenericHashResult() { Success = false, Message = $"{MessageStrings.Common_FileNotFound} \"{filePathToComputeHash}\"." }); } GenericHashResult result = null; HashAlgorithm hashAlg = null; #if CORERT switch (hashAlgorithm) { case Enums.HashAlgorithm.MD5: hashAlg = MD5.Create(); break; case Enums.HashAlgorithm.SHA1: hashAlg = SHA1.Create(); break; case Enums.HashAlgorithm.SHA256: hashAlg = SHA256.Create(); break; case Enums.HashAlgorithm.SHA384: hashAlg = SHA384.Create(); break; case Enums.HashAlgorithm.SHA512: hashAlg = SHA512.Create(); break; case Enums.HashAlgorithm.BCrypt: default: break; } #else hashAlg = (HashAlgorithm)CryptoConfig.CreateFromName(hashAlgorithm.ToString()); #endif try { byte[] hash = null; using (var fStream = new FileStream(filePathToComputeHash, FileMode.Open, FileAccess.Read, FileShare.None)) { //offset = (offset == 0 ? 0 : offset); count = (count == 0 ? fStream.Length : count); fStream.Position = offset; var buffer = new byte[(1024 * 4)]; var amount = (count - offset); using (hashAlg) { var percentageDone = 0; while (amount > 0) { var bytesRead = fStream.Read(buffer, 0, (int)Math.Min(buffer.Length, amount)); if (bytesRead > 0) { amount -= bytesRead; if (amount > 0) { hashAlg.TransformBlock(buffer, 0, bytesRead, buffer, 0); } else { hashAlg.TransformFinalBlock(buffer, 0, bytesRead); } var tmpPercentageDone = (int)(fStream.Position * 100 / count); if (tmpPercentageDone != percentageDone) { percentageDone = tmpPercentageDone; RaiseOnHashProgress(percentageDone, (percentageDone != 100 ? $"Computing hash ({percentageDone}%)..." : $"Hash computed ({percentageDone}%).")); } } else { throw new InvalidOperationException(); } } hash = hashAlg.Hash; } } result = new GenericHashResult() { Success = true, Message = MessageStrings.Hash_ComputeSuccess, HashString = Encoding.HighPerformanceHexadecimal.ToHexString(hash), HashBytes = hash }; } catch (Exception ex) { result = new GenericHashResult() { Success = false, Message = ex.ToString() }; } return(result); }