A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Added HMAC authentication mode in Hash generators (#555)
Abhishek Deore389ba74112b6
diff --git a/src/dev/impl/DevToys/LanguageManager.cs b/src/dev/impl/DevToys/LanguageManager.csindex 6f66a1884..6412d142c 100644--- a/src/dev/impl/DevToys/LanguageManager.cs+++ b/src/dev/impl/DevToys/LanguageManager.cs@@ -977,6 +977,16 @@ namespace DevToys/// Gets the resource SearchKeywords./// </summary>public string SearchKeywords => _resources.GetString("SearchKeywords");++ /// <summary>+ /// Gets the resource HmacMode.+ /// </summary>+ public string HmacMode => _resources.GetString("HmacMode");++ /// <summary>+ /// Gets the resource SecretKey.+ /// </summary>+ public string SecretKey => _resources.GetString("SecretKey");}public class HtmlEncoderDecoderStrings : ObservableObjectdiff --git a/src/dev/impl/DevToys/Strings/en-US/HashGenerator.resw b/src/dev/impl/DevToys/Strings/en-US/HashGenerator.reswindex edb6c9ac9..69cbd9605 100644--- a/src/dev/impl/DevToys/Strings/en-US/HashGenerator.resw+++ b/src/dev/impl/DevToys/Strings/en-US/HashGenerator.resw@@ -162,4 +162,10 @@<data name="SearchKeywords" xml:space="preserve"><value /></data>+ <data name="HmacMode" xml:space="preserve">+ <value>HMAC Mode</value>+ </data>+ <data name="SecretKey" xml:space="preserve">+ <value>Secret Key</value>+ </data></root>\ No newline at end of filediff --git a/src/dev/impl/DevToys/ViewModels/Tools/Generators/HashGenerator/HashGeneratorToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/Generators/HashGenerator/HashGeneratorToolViewModel.csindex e83ca8b7c..178588d3a 100644--- a/src/dev/impl/DevToys/ViewModels/Tools/Generators/HashGenerator/HashGeneratorToolViewModel.cs+++ b/src/dev/impl/DevToys/ViewModels/Tools/Generators/HashGenerator/HashGeneratorToolViewModel.cs@@ -1,6 +1,7 @@#nullable enableusing System;+using System.Collections.Generic;using System.Composition;using System.Threading.Tasks;using DevToys.Api.Core;@@ -17,7 +18,7 @@ using Windows.Storage.Streams;namespace DevToys.ViewModels.Tools.HashGenerator{[Export(typeof(HashGeneratorToolViewModel))]- public sealed class HashGeneratorToolViewModel : QueueWorkerViewModelBase<string>, IToolViewModel+ public sealed class HashGeneratorToolViewModel : QueueWorkerViewModelBase<Tuple<string,string>>, IToolViewModel{/// <summary>/// Whether the generated hash should be uppercase or lowercase.@@ -28,6 +29,15 @@ namespace DevToys.ViewModels.Tools.HashGeneratorisRoaming: true,defaultValue: false);+ /// <summary>+ /// Whether the tool should operate and return HMAC string+ /// </summary>+ private static readonly SettingDefinition<bool> IsHMAC+ = new(+ name: $"{nameof(HashGeneratorToolViewModel)}.{nameof(IsHMAC)}",+ isRoaming: true,+ defaultValue: false);+/// <summary>/// The Output Code to generate./// </summary>@@ -43,6 +53,7 @@ namespace DevToys.ViewModels.Tools.HashGeneratorprivate bool _toolSuccessfullyWorked;private string? _input;+ private string? _secretKey;private string? _md5;private string? _sha1;private string? _sha256;@@ -83,6 +94,20 @@ namespace DevToys.ViewModels.Tools.HashGenerator}}+ internal bool IsHmacMode+ {+ get => SettingsProvider.GetSetting(IsHMAC);+ set+ {+ if(SettingsProvider.GetSetting(IsHMAC) != value)+ {+ SettingsProvider.SetSetting(IsHMAC, value);+ OnPropertyChanged();+ QueueHashCalculation();+ }+ }+ }+internal string? Input{get => _input;@@ -93,6 +118,16 @@ namespace DevToys.ViewModels.Tools.HashGenerator}}+ internal string? SecretKey+ {+ get => _secretKey;+ set+ {+ SetProperty(ref _secretKey, value);+ QueueHashCalculation();+ }+ }+internal string? MD5{get => _md5;@@ -126,15 +161,15 @@ namespace DevToys.ViewModels.Tools.HashGeneratorprivate void QueueHashCalculation(){- EnqueueComputation(Input ?? string.Empty);+ EnqueueComputation(new Tuple<string, string>(Input ?? string.Empty, SecretKey ?? string.Empty));}- protected override async Task TreatComputationQueueAsync(string value)+ protected override async Task TreatComputationQueueAsync(Tuple<string, string> inputSecretKeyPair){- Task<string> md5CalculationTask = CalculateHashAsync(HashAlgorithmNames.Md5, value);- Task<string> sha1CalculationTask = CalculateHashAsync(HashAlgorithmNames.Sha1, value);- Task<string> sha256CalculationTask = CalculateHashAsync(HashAlgorithmNames.Sha256, value);- Task<string> sha512CalculationTask = CalculateHashAsync(HashAlgorithmNames.Sha512, value);+ Task<string> md5CalculationTask = CalculateHashAsync(HashAlgorithmNames.Md5, inputSecretKeyPair.Item1, inputSecretKeyPair.Item2);+ Task<string> sha1CalculationTask = CalculateHashAsync(HashAlgorithmNames.Sha1, inputSecretKeyPair.Item1, inputSecretKeyPair.Item2);+ Task<string> sha256CalculationTask = CalculateHashAsync(HashAlgorithmNames.Sha256, inputSecretKeyPair.Item1, inputSecretKeyPair.Item2);+ Task<string> sha512CalculationTask = CalculateHashAsync(HashAlgorithmNames.Sha512, inputSecretKeyPair.Item1, inputSecretKeyPair.Item2);await Task.WhenAll(md5CalculationTask).ConfigureAwait(false);@@ -153,9 +188,9 @@ namespace DevToys.ViewModels.Tools.HashGenerator});}- private async Task<string> CalculateHashAsync(string alrogithmName, string text)+ private async Task<string> CalculateHashAsync(string algorithmName, string text, string secretKey){- if (string.IsNullOrEmpty(text))+ if (string.IsNullOrEmpty(text) || (IsHmacMode && secretKey.Length == 0)){return string.Empty;}@@ -164,12 +199,23 @@ namespace DevToys.ViewModels.Tools.HashGeneratortry{- var algorithmProvider = HashAlgorithmProvider.OpenAlgorithm(alrogithmName);-- IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(text, BinaryStringEncoding.Utf8);- buffer = algorithmProvider.HashData(buffer);-string? hash = "";+ IBuffer? buffer = null;+ if (IsHmacMode)+ {+ var macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm(GetHmacAlgorithmName(algorithmName));+ IBuffer textBuffer = CryptographicBuffer.ConvertStringToBinary(text, BinaryStringEncoding.Utf8);+ IBuffer secretKeyBuffer = CryptographicBuffer.ConvertStringToBinary(secretKey, BinaryStringEncoding.Utf8);+ CryptographicKey hmacKey = macAlgorithmProvider.CreateKey(secretKeyBuffer);+ buffer = CryptographicEngine.Sign(hmacKey, textBuffer);+ }+ else+ {+ var algorithmProvider = HashAlgorithmProvider.OpenAlgorithm(algorithmName);+ buffer = CryptographicBuffer.ConvertStringToBinary(text, BinaryStringEncoding.Utf8);+ buffer = algorithmProvider.HashData(buffer);+ }+if (string.Equals(OutputType, HexOutput)){hash = IsUppercase@@ -184,9 +230,31 @@ namespace DevToys.ViewModels.Tools.HashGenerator}catch (Exception ex){- Logger.LogFault("Hash Generator", ex, $"Alrogithm name: {alrogithmName}");+ Logger.LogFault("Hash Generator", ex, $"Alrogithm name: {algorithmName}");return ex.Message;}}++ private string GetHmacAlgorithmName(string algorithmName)+ {+ if (algorithmName == HashAlgorithmNames.Md5)+ {+ return MacAlgorithmNames.HmacMd5;+ }+ else if (algorithmName == HashAlgorithmNames.Sha1)+ {+ return MacAlgorithmNames.HmacSha1;+ }+ else if (algorithmName == HashAlgorithmNames.Sha256)+ {+ return MacAlgorithmNames.HmacSha256;+ }+ else if (algorithmName == HashAlgorithmNames.Sha512)+ {+ return MacAlgorithmNames.HmacSha512;+ }++ throw new Exception("Unsupported algorithm: " + algorithmName);+ }}}diff --git a/src/dev/impl/DevToys/Views/Tools/Generators/HashGenerator/HashGeneratorToolPage.xaml b/src/dev/impl/DevToys/Views/Tools/Generators/HashGenerator/HashGeneratorToolPage.xamlindex b88ab14cd..fdd3d78c1 100644--- a/src/dev/impl/DevToys/Views/Tools/Generators/HashGenerator/HashGeneratorToolPage.xaml+++ b/src/dev/impl/DevToys/Views/Tools/Generators/HashGenerator/HashGeneratorToolPage.xaml@@ -42,6 +42,17 @@<ComboBoxItem Tag="Base64" Content="{x:Bind ViewModel.Strings.OutputBase64}"/></ComboBox></controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.Strings.HmacMode}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch+ x:Name="IsUsingHmacToggleSwitch"+ Style="{StaticResource RightAlignedToggleSwitchStyle}"+ Toggled="IsUsingHmacToggleSwitch_Toggled"+ IsOn="{x:Bind ViewModel.IsHmacMode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ </controls:ExpandableSettingControl></StackPanel><controls:CustomTextBox@@ -50,6 +61,13 @@AcceptsReturn="True"Text="{x:Bind ViewModel.Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ <controls:CustomTextBox x:Name="SecretKeyInput"+ Header="{x:Bind ViewModel.Strings.SecretKey}"+ Height="150"+ AcceptsReturn="True"+ Visibility="Collapsed"+ Text="{x:Bind ViewModel.SecretKey, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+<controls:CustomTextBoxHeader="{x:Bind ViewModel.Strings.MD5}"IsReadOnly="True"diff --git a/src/dev/impl/DevToys/Views/Tools/Generators/HashGenerator/HashGeneratorToolPage.xaml.cs b/src/dev/impl/DevToys/Views/Tools/Generators/HashGenerator/HashGeneratorToolPage.xaml.csindex c5a34b5d2..d91a2b082 100644--- a/src/dev/impl/DevToys/Views/Tools/Generators/HashGenerator/HashGeneratorToolPage.xaml.cs+++ b/src/dev/impl/DevToys/Views/Tools/Generators/HashGenerator/HashGeneratorToolPage.xaml.cs@@ -58,5 +58,23 @@ namespace DevToys.Views.Tools.HashGeneratorIsUppercaseToggleSwitch.IsEnabled = true;}}++ private void IsUsingHmacToggleSwitch_Toggled(object sender, RoutedEventArgs e)+ {+ var toggleSwitch = (ToggleSwitch)sender;+ if(toggleSwitch != null)+ {+ ViewModel.IsHmacMode = toggleSwitch.IsOn;+ if (toggleSwitch.IsOn)+ {+ SecretKeyInput.Visibility = Visibility.Visible;+ }+ else+ {+ SecretKeyInput.Visibility = Visibility.Collapsed;+ SecretKeyInput.Text = "";+ }+ }+ }}}diff --git a/src/tests/DevToys.Tests/Providers/Tools/HashGeneratorTests.cs b/src/tests/DevToys.Tests/Providers/Tools/HashGeneratorTests.csindex 52ce31c57..58cb9cf45 100644--- a/src/tests/DevToys.Tests/Providers/Tools/HashGeneratorTests.cs+++ b/src/tests/DevToys.Tests/Providers/Tools/HashGeneratorTests.cs@@ -47,5 +47,49 @@ namespace DevToys.Tests.Providers.ToolsAssert.AreEqual(expectedResult, viewModel.SHA512);}++ [DataTestMethod]+ [DataRow(null, "", "")]+ [DataRow("", "", "")]+ [DataRow(" ", " ", "0b8a72163b925bbb61ffa98e90339e57f0ed5c8956665af83691aebbdebb87e7eb6090a877b62fdcfca2e29768159d0066e7ef875a87d6a8b2ff9d286a98ff56")]+ [DataRow("Hello There", "World", "43bb6d1170cbf1be61ebf85a434ea1acb4caced09b8f0d40125b21804c524a4be66ba0af02617076505973edf819563e4d8eb68a5c2c4dc5d1a0a661bcce5d44")]+ public async Task LowercaseHmacModeHashingAsync(string input, string secretKey, string expectedResult)+ {+ HashGeneratorToolViewModel viewModel = ExportProvider.Import<HashGeneratorToolViewModel>();++ await ThreadHelper.RunOnUIThreadAsync(() =>+ {+ viewModel.IsUppercase = false;+ viewModel.Input = input;+ viewModel.IsHmacMode = true;+ viewModel.SecretKey = secretKey;+ });++ await viewModel.ComputationTask;++ Assert.AreEqual(expectedResult, viewModel.SHA512);+ }++ [DataTestMethod]+ [DataRow(null, "", "")]+ [DataRow("", "", "")]+ [DataRow(" ", " ", "0B8A72163B925BBB61FFA98E90339E57F0ED5C8956665AF83691AEBBDEBB87E7EB6090A877B62FDCFCA2E29768159D0066E7EF875A87D6A8B2FF9D286A98FF56")]+ [DataRow("Hello There", "World", "43BB6D1170CBF1BE61EBF85A434EA1ACB4CACED09B8F0D40125B21804C524A4BE66BA0AF02617076505973EDF819563E4D8EB68A5C2C4DC5D1A0A661BCCE5D44")]+ public async Task UppercaseHmacModeHashingAsync(string input, string secretKey, string expectedResult)+ {+ HashGeneratorToolViewModel viewModel = ExportProvider.Import<HashGeneratorToolViewModel>();++ await ThreadHelper.RunOnUIThreadAsync(() =>+ {+ viewModel.IsUppercase = true;+ viewModel.Input = input;+ viewModel.IsHmacMode = true;+ viewModel.SecretKey = secretKey;+ });++ await viewModel.ComputationTask;++ Assert.AreEqual(expectedResult, viewModel.SHA512);+ }}}