internal HMACHashResult ComputeHMAC(Enums.HMACAlgorithm hmacAlgorithm, byte[] bytesToComputeHMAC, byte[] key = null, int offset = 0, int count = 0) { if (bytesToComputeHMAC == null || bytesToComputeHMAC.Length <= 0) { return(new HMACHashResult() { Success = false, Message = MessageDictionary.Instance["HMAC.InputRequired"] }); } if (key == null || key.Length == 0) { key = CommonMethods.GenerateRandomBytes(HMACOutputLengthDictionary.Instance[hmacAlgorithm] / 8); } HMACHashResult result = null; try { using (var hmac = (HMAC)CryptoConfig.CreateFromName(hmacAlgorithm.ToString())) { hmac.Key = key; //offset = (offset == 0 ? 0 : offset); count = (count == 0 ? bytesToComputeHMAC.Length : count); byte[] hash = hmac.ComputeHash(bytesToComputeHMAC, offset, count); result = new HMACHashResult() { Success = true, Message = MessageDictionary.Instance["HMAC.ComputeSuccess"], HashBytes = hash, HashString = Encoding.HighPerformanceHexadecimal.ToHexString(hash), Key = key, PRF = hmacAlgorithm }; } } catch (Exception ex) { return(new HMACHashResult() { Success = false, Message = ex.ToString() }); } return(result); }
public void ComputeAndVerifyHMAC_String() { var verifyResult = new HMACHashResult(); var errorMessage = ""; var hmacResult = _hmacSha1.ComputeHMAC(_testString); if (hmacResult.Success) { verifyResult = _hmacSha1.VerifyHMAC(hmacResult.HashString, _testString, hmacResult.Key); if (!verifyResult.Success) { errorMessage = verifyResult.Message; } } else { errorMessage = hmacResult.Message; } Assert.IsTrue((hmacResult.Success && verifyResult.Success), errorMessage); }
internal HMACHashResult ComputeFileHMAC(Enums.HMACAlgorithm hmacAlgorithm, string filePathToComputeHMAC, byte[] key = null, long offset = 0, long count = 0) { if (!File.Exists(filePathToComputeHMAC)) { return(new HMACHashResult() { Success = false, Message = $"{MessageDictionary.Instance["Common.FileNotFound"]} \"{filePathToComputeHMAC}\"." }); } if (key == null || key.Length == 0) { key = CommonMethods.GenerateRandomBytes(HMACOutputLengthDictionary.Instance[hmacAlgorithm] / 8); } HMACHashResult result = null; try { byte[] hash = null; using (var fStream = new FileStream(filePathToComputeHMAC, 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 hmac = (HMAC)CryptoConfig.CreateFromName(hmacAlgorithm.ToString())) { hmac.Key = key; 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) { hmac.TransformBlock(buffer, 0, bytesRead, buffer, 0); } else { hmac.TransformFinalBlock(buffer, 0, bytesRead); } var tmpPercentageDone = (int)(fStream.Position * 100 / count); if (tmpPercentageDone != percentageDone) { percentageDone = tmpPercentageDone; RaiseOnHashProgress(percentageDone, (percentageDone != 100 ? $"Computing HMAC ({percentageDone}%)..." : $"HMAC computed ({percentageDone}%).")); } } else { throw new InvalidOperationException(); } } hash = hmac.Hash; } } result = new HMACHashResult() { Success = true, Message = MessageDictionary.Instance["HMAC.ComputeSuccess"], HashString = Encoding.HighPerformanceHexadecimal.ToHexString(hash), HashBytes = hash, Key = key }; } catch (Exception ex) { result = new HMACHashResult() { Success = false, Message = ex.ToString() }; } return(result); }
private static ExitCode RunHMACOptionsAndReturnExitCode(HMACOptions hmacOptions) { HMACHashResult hmacResult = null; switch (hmacOptions.InputType.ToLower()) { case "string": { hmacResult = (hmacOptions.Algorithm.ToLower()) switch { "hmacmd5" => new HMAC_MD5().ComputeHMAC(hmacOptions.InputToComputeHMAC, (string.IsNullOrWhiteSpace(hmacOptions.Key) ? null : System.Text.Encoding.UTF8.GetBytes(hmacOptions.Key))), "hmacsha1" => new HMAC_SHA_1().ComputeHMAC(hmacOptions.InputToComputeHMAC, (string.IsNullOrWhiteSpace(hmacOptions.Key) ? null : System.Text.Encoding.UTF8.GetBytes(hmacOptions.Key))), "hmacsha256" => new HMAC_SHA_256().ComputeHMAC(hmacOptions.InputToComputeHMAC, (string.IsNullOrWhiteSpace(hmacOptions.Key) ? null : System.Text.Encoding.UTF8.GetBytes(hmacOptions.Key))), "hmacsha384" => new HMAC_SHA_384().ComputeHMAC(hmacOptions.InputToComputeHMAC, (string.IsNullOrWhiteSpace(hmacOptions.Key) ? null : System.Text.Encoding.UTF8.GetBytes(hmacOptions.Key))), "hmacsha512" => new HMAC_SHA_512().ComputeHMAC(hmacOptions.InputToComputeHMAC, (string.IsNullOrWhiteSpace(hmacOptions.Key) ? null : System.Text.Encoding.UTF8.GetBytes(hmacOptions.Key))), _ => new HMACHashResult() { Success = false, Message = $"Unknown algorithm \"{hmacOptions.Algorithm}\"." }, }; } break; case "file": { switch (hmacOptions.Algorithm.ToLower()) { case "hmacmd5": using (var progressBar = new ProgressBar()) { var hmacMd5 = new HMAC_MD5(); hmacMd5.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); }; hmacResult = hmacMd5.ComputeFileHMAC(hmacOptions.InputToComputeHMAC, (string.IsNullOrWhiteSpace(hmacOptions.Key) ? null : System.Text.Encoding.UTF8.GetBytes(hmacOptions.Key))); } break; case "hmacsha1": using (var progressBar = new ProgressBar()) { var hmacSha1 = new HMAC_SHA_1(); hmacSha1.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); }; hmacResult = hmacSha1.ComputeFileHMAC(hmacOptions.InputToComputeHMAC, (string.IsNullOrWhiteSpace(hmacOptions.Key) ? null : System.Text.Encoding.UTF8.GetBytes(hmacOptions.Key))); } break; case "hmacsha256": using (var progressBar = new ProgressBar()) { var hmacSha256 = new HMAC_SHA_256(); hmacSha256.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); }; hmacResult = hmacSha256.ComputeFileHMAC(hmacOptions.InputToComputeHMAC, (string.IsNullOrWhiteSpace(hmacOptions.Key) ? null : System.Text.Encoding.UTF8.GetBytes(hmacOptions.Key))); } break; case "hmacsha384": using (var progressBar = new ProgressBar()) { var hmacSha384 = new HMAC_SHA_384(); hmacSha384.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); }; hmacResult = hmacSha384.ComputeFileHMAC(hmacOptions.InputToComputeHMAC, (string.IsNullOrWhiteSpace(hmacOptions.Key) ? null : System.Text.Encoding.UTF8.GetBytes(hmacOptions.Key))); } break; case "hmacsha512": using (var progressBar = new ProgressBar()) { var hmacSha512 = new HMAC_SHA_512(); hmacSha512.OnHashProgress += (percentageDone, message) => { progressBar.Report((double)percentageDone / 100); }; hmacResult = hmacSha512.ComputeFileHMAC(hmacOptions.InputToComputeHMAC, (string.IsNullOrWhiteSpace(hmacOptions.Key) ? null : System.Text.Encoding.UTF8.GetBytes(hmacOptions.Key))); } break; default: hmacResult = new HMACHashResult() { Success = false, Message = $"Unknown algorithm \"{hmacOptions.Algorithm}\"." }; break; } } break; default: hmacResult = new HMACHashResult() { Success = false, Message = $"Unknown input type \"{hmacOptions.InputType}\"." }; break; } if (hmacResult.Success && !string.IsNullOrWhiteSpace(hmacOptions.CompareHash)) { if (string.IsNullOrWhiteSpace(hmacOptions.Key)) { Console.WriteLine("The HMAC KEY parameter is required for comparation."); return(ExitCode.Error); } else { var hashesMatch = (hmacResult.HashString.Equals(hmacOptions.CompareHash, StringComparison.InvariantCultureIgnoreCase)); var outputMessage = ( hashesMatch ? $"Computed hash MATCH with given hash: {hmacResult.HashString}" : $"Computed hash DOES NOT MATCH with given hash.\nComputed hash: {hmacResult.HashString}\nGiven hash: {hmacOptions.CompareHash}" ); Console.WriteLine(outputMessage); return(hashesMatch ? ExitCode.Sucess : ExitCode.Error); } } else if (hmacResult.Success && string.IsNullOrWhiteSpace(hmacOptions.CompareHash)) { Console.WriteLine(hmacResult.HashString); return(ExitCode.Sucess); } else { Console.WriteLine(hmacResult.Message); return(ExitCode.Error); } }