A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Features/jwt decoder encoder tool update (#645)
BenjaminTa8b700b76944
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdindex 8a859dede..c7cc2fd59 100644--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@ -1,25 +1,27 @@-THIRD-PARTY SOFTWARE NOTICES AND INFORMATION+# THIRD-PARTY SOFTWARE NOTICES AND INFORMATIONThis project incorporates components from the projects listed below. The original copyright notices and the licenses under which Etienne Baudoux received such components are set forth below. Etienne Baudoux reserves all rights not expressly granted herein, whether by implication, estoppel or otherwise.-1. Newtonsoft.Json (https://github.com/JamesNK/Newtonsoft.Json)-2. GitInfo (https://github.com/devlooped/GitInfo)-3. Windows Community Toolkit (https://github.com/CommunityToolkit/WindowsCommunityToolkit)-4. YamlDotNet (https://github.com/aaubry/YamlDotNet)-5. Fluent UI System Icons (https://github.com/microsoft/fluentui-system-icons)-6. Monaco Editor (https://github.com/Microsoft/monaco-editor)-7. Monaco Editor UWP (https://github.com/hawkerm/monaco-editor-uwp)-8. Observable Vector (https://github.com/jamesqo/observable-vector)-9. Azure Active Directory IdentityModel Extensions for .NET (https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet)-10. Markdig (https://github.com/xoofx/markdig)-11. github-markdown-css (https://github.com/sindresorhus/github-markdown-css)-12. Efficient Compression Tool (https://github.com/fhanau/Efficient-Compression-Tool)-13. NLipsum (https://github.com/alexcpendleton/NLipsum)-14. SQL Formatter (https://github.com/zeroturnaround/sql-formatter)-15. Cronos (https://github.com/HangfireIO/Cronos)--Newtonsoft.Json NOTICES AND INFORMATION BEGIN HERE+1. [Newtonsoft.Json](#newtonsoftjson) (<https://github.com/JamesNK/Newtonsoft.Json>)+2. [GitInfo](#gitinfo) (<https://github.com/devlooped/GitInfo>)+3. [Windows Community Toolkit](#windows-community-toolkit) (<https://github.com/CommunityToolkit/WindowsCommunityToolkit>)+4. [YamlDotNet](#yamldotnet) (<https://github.com/aaubry/YamlDotNet>)+5. [Fluent UI System Icons](#fluent-ui-system-icons) (<https://github.com/microsoft/fluentui-system-icons>)+6. [Monaco Editor](#monaco-editor) (<https://github.com/Microsoft/monaco-editor>)+7. [Monaco Editor UWP](#monaco-editor-uwp) (<https://github.com/hawkerm/monaco-editor-uwp>)+8. [Observable Vector](#observable-vector) (<https://github.com/jamesqo/observable-vector>)+9. [Azure Active Directory IdentityModel Extensions for .NET](#azure-active-directory-identitymodel-extensions-for-net) (<https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet>)+10. [Markdig](#markdig) (<https://github.com/xoofx/markdig>)+11. [github-markdown-css](#github-markdown-css) (<https://github.com/sindresorhus/github-markdown-css>)+12. [Efficient Compression Tool](#efficient-compression-tool) (<https://github.com/fhanau/Efficient-Compression-Tool>)+13. [NLipsum](#nlipsum) (<https://github.com/alexcpendleton/NLipsum>)+14. [SQL Formatter](#sql-formatter) (<https://github.com/zeroturnaround/sql-formatter>)+15. [Cronos](#cronos) (<https://github.com/HangfireIO/Cronos>)+16. [BouncyCastle](#bouncy-castle) (<https://www.bouncycastle.org/>)++Newtonsoft.Json=========================================+The MIT License (MIT)Copyright (c) 2007 James Newton-King@@ -41,8 +43,9 @@ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHERIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.-GitInfo NOTICES AND INFORMATION BEGIN HERE+GitInfo=========================================+The MIT License (MIT)Copyright (c) Daniel Cazzulino and Contributors@@ -65,15 +68,14 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.-Windows Community Toolkit NOTICES AND INFORMATION BEGIN HERE+Windows Community Toolkit=========================================-# Windows Community ToolkitCopyright © .NET Foundation and ContributorsAll rights reserved.-## MIT License (MIT)+# MIT License (MIT)Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:@@ -81,8 +83,9 @@ The above copyright notice and this permission notice shall be included in all cTHE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.-YamlDotNet NOTICES AND INFORMATION BEGIN HERE+YamlDotNet=========================================+Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Antoine Aubry and contributorsPermission is hereby granted, free of charge, to any person obtaining a copy of@@ -103,8 +106,9 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.-Fluent UI System Icons NOTICES AND INFORMATION BEGIN HERE+Fluent UI System Icons=========================================+MIT LicenseCopyright (c) 2020 Microsoft Corporation@@ -127,8 +131,9 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.-Monaco Editor NOTICES AND INFORMATION BEGIN HERE+Monaco Editor=========================================+The MIT License (MIT)Copyright (c) 2016 - present Microsoft Corporation@@ -139,8 +144,9 @@ The above copyright notice and this permission notice shall be included in all cTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.-Monaco Editor UWP NOTICES AND INFORMATION BEGIN HERE+Monaco Editor UWP=========================================+Copyright 2017 Michael A. HawkerPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:@@ -149,8 +155,9 @@ The above copyright notice and this permission notice shall be included in all cTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.-Observable Vector NOTICES AND INFORMATION BEGIN HERE+Observable Vector=========================================+The MIT License (MIT)Copyright (c) 2016 James Ko@@ -173,8 +180,9 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.-Azure Active Directory IdentityModel Extensions for .NET NOTICES AND INFORMATION BEGIN HERE+Azure Active Directory IdentityModel Extensions for .NET=========================================+The MIT License (MIT)Copyright (c) Microsoft Corporation@@ -197,37 +205,39 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.-Markdig NOTICES AND INFORMATION BEGIN HERE+Markdig=========================================+Copyright (c) 2018-2019, Alexandre MutelAll rights reserved.Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:-1. Redistributions of source code must retain the above copyright notice, this+1. Redistributions of source code must retain the above copyright notice, thislist of conditions and the following disclaimer.-2. Redistributions in binary form must reproduce the above copyright notice,- this list of conditions and the following disclaimer in the documentation+2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentationand/or other materials provided with the distribution.-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.-github-markdown-css NOTICES AND INFORMATION BEGIN HERE+github-markdown-css=========================================+MIT License-Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)+Copyright (c) Sindre Sorhus <[email protected]> (<<https://sindresorhus.com>)Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:@@ -235,8 +245,9 @@ The above copyright notice and this permission notice shall be included in all cTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.-Efficient Compression Tool NOTICES AND INFORMATION BEGIN HERE+Efficient Compression Tool=========================================+Apache LicenseVersion 2.0, January 2004http://www.apache.org/licenses/@@ -439,8 +450,9 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.-NLipsum NOTICES AND INFORMATION BEGIN HERE+NLipsum=========================================+The MIT License (MIT)Copyright (c) 2015 Alex Pendleton@@ -462,8 +474,9 @@ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHERIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.-SQL Formatter NOTICES AND INFORMATION BEGIN HERE+SQL Formatter=========================================+The MIT License (MIT)Copyright (c) 2016-2020 ZeroTurnaround LLC@@ -487,8 +500,9 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.-Cronos NOTICES AND INFORMATION BEGIN HERE+Cronos=========================================+The MIT License (MIT)Copyright (c) 2017 Hangfire OÜ@@ -509,4 +523,20 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE-SOFTWARE.\ No newline at end of file+SOFTWARE.++Bouncy Castle+=========================================++Please note this should be read in the same way as the [MIT license](<<http://opensource.org/licenses/MIT>).++Please also note this licensing model is made possible through funding from [donations](<<https://www.bouncycastle.org/donate>) and the sale of [support contracts](<<https://www.cryptoworkshop.com/support_faq.html>).++LICENSE+Copyright (c) 2000 - 2021 The Legion of the Bouncy Castle Inc. (<<https://www.bouncycastle.org>)++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.diff --git a/src/Directory.Build.props b/src/Directory.Build.propsindex 16c049513..125d3ec8f 100644--- a/src/Directory.Build.props+++ b/src/Directory.Build.props@@ -37,5 +37,6 @@<NuGet_YamlDotNet>11.2.1</NuGet_YamlDotNet><NuGet_IdentityModelTokenJwt>6.13.1</NuGet_IdentityModelTokenJwt><NuGet_NLipsum>1.1.0</NuGet_NLipsum>+ <NuGet_BouncyCastleNetCore>1.9.0</NuGet_BouncyCastleNetCore></PropertyGroup></Project>\ No newline at end of filediff --git a/src/dev/impl/DevToys/Core/QueueWorkerViewModelBase.cs b/src/dev/impl/DevToys/Core/QueueWorkerViewModelBaseAsync.cssimilarity index 100%rename from src/dev/impl/DevToys/Core/QueueWorkerViewModelBase.csrename to src/dev/impl/DevToys/Core/QueueWorkerViewModelBaseAsync.csdiff --git a/src/dev/impl/DevToys/DevToys.csproj b/src/dev/impl/DevToys/DevToys.csprojindex 0c93d4b5d..7513d0ee6 100644--- a/src/dev/impl/DevToys/DevToys.csproj+++ b/src/dev/impl/DevToys/DevToys.csproj@@ -28,8 +28,9 @@<Compile Include="Api\Tools\NotSearchableAttribute.cs" /><Compile Include="Api\Tools\ParentAttribute.cs" /><Compile Include="Core\OOP\AppService.cs" />- <Compile Include="Core\QueueWorkerViewModelBase.cs" />+ <Compile Include="Core\QueueWorkerViewModelBaseAsync.cs" /><Compile Include="Core\Threading\AsyncLazy.cs" />+ <Compile Include="Helpers\Base64Helper.cs" /><Compile Include="Helpers\JsonYaml\Core\BooleanYamlTypeResolver.cs" /><Compile Include="Helpers\StorageFileHelper.cs" /><Compile Include="Helpers\ImageHelper.cs" />@@ -74,12 +75,20 @@<Compile Include="Models\HashingAlgorithmDisplayPair.cs" /><Compile Include="Models\HashingProgress.cs" /><Compile Include="Models\InfoBarData.cs" />+ <Compile Include="Models\JwtAlgorithm.cs" />+ <Compile Include="Models\JwtAlgorithmDisplayPair.cs" />+ <Compile Include="Models\JwtDecoderEncoder\DecoderParameters.cs" />+ <Compile Include="Models\JwtDecoderEncoder\EncoderParameters.cs" />+ <Compile Include="Models\JwtDecoderEncoder\TokenParameters.cs" />+ <Compile Include="Models\JwtDecoderEncoder\TokenResult.cs" />+ <Compile Include="Models\JwtDecoderEncoder\TokenResultErrorEventArgs.cs" /><Compile Include="Models\NumberBaseDictionary.cs" /><Compile Include="Models\SqlLanguageDisplayPair.cs" /><Compile Include="Models\NoResultFoundMockToolProvider.cs" /><Compile Include="Models\Radix.cs" /><Compile Include="Models\NumberBaseFormat.cs" /><Compile Include="Models\TileIconSizeDefinition.cs" />+ <Compile Include="Models\ValidationBase.cs" /><Compile Include="UI\Controls\FileSelector.xaml.cs"><DependentUpon>FileSelector.xaml</DependentUpon></Compile>@@ -114,6 +123,14 @@<Compile Include="Helpers\JsonYaml\Core\DecimalJsonConverter.cs" /><Compile Include="Helpers\JsonYaml\Core\DecimalYamlTypeResolver.cs" /><Compile Include="ViewModels\Tools\EncodersDecoders\EncodersDecodersGroupToolProvider.cs" />+ <Compile Include="ViewModels\Tools\EncodersDecoders\JwtDecoderEncoder\JwtEncoder.cs" />+ <Compile Include="ViewModels\Tools\EncodersDecoders\JwtDecoderEncoder\JwtDecoder.cs" />+ <Compile Include="ViewModels\Tools\EncodersDecoders\JwtDecoderEncoder\JwtDecoderControlViewModel.cs" />+ <Compile Include="ViewModels\Tools\EncodersDecoders\JwtDecoderEncoder\JwtDecoderEncoderSettings.cs" />+ <Compile Include="ViewModels\Tools\EncodersDecoders\JwtDecoderEncoder\JwtDecoderEncoderViewModelBase.cs" />+ <Compile Include="ViewModels\Tools\EncodersDecoders\JwtDecoderEncoder\JwtEncoderControlViewModel.cs" />+ <Compile Include="ViewModels\Tools\EncodersDecoders\JwtDecoderEncoder\JwtJobAddedMessage.cs" />+ <Compile Include="ViewModels\Tools\EncodersDecoders\JwtDecoderEncoder\JwtPayloadConverter.cs" /><Compile Include="ViewModels\Tools\Formatters\XmlFormatter\XmlFormatterToolProvider.cs" /><Compile Include="ViewModels\Tools\Formatters\XmlFormatter\XmlFormatterToolViewModel.cs" /><Compile Include="ViewModels\Tools\Formatters\SqlFormatter\SqlFormatterToolProvider.cs" />@@ -173,6 +190,12 @@<Compile Include="Views\Tools\EncodersDecoders\GZipEncoderDecoder\GZipEncoderDecoderToolPage.xaml.cs"><DependentUpon>GZipEncoderDecoderToolPage.xaml</DependentUpon></Compile>+ <Compile Include="Views\Tools\EncodersDecoders\JwtDecoderEncoder\JwtDecoderControl.xaml.cs">+ <DependentUpon>JwtDecoderControl.xaml</DependentUpon>+ </Compile>+ <Compile Include="Views\Tools\EncodersDecoders\JwtDecoderEncoder\JwtEncoderControl.xaml.cs">+ <DependentUpon>JwtEncoderControl.xaml</DependentUpon>+ </Compile><Compile Include="Views\Tools\Formatters\XmlFormatter\XmlFormatterToolPage.xaml.cs"><DependentUpon>XmlFormatterToolPage.xaml</DependentUpon></Compile>@@ -553,6 +576,14 @@<AppxManifest Include="Package.appxmanifest"><SubType>Designer</SubType></AppxManifest>+ <Page Include="Views\Tools\EncodersDecoders\JwtDecoderEncoder\JwtDecoderControl.xaml">+ <Generator>MSBuild:Compile</Generator>+ <SubType>Designer</SubType>+ </Page>+ <Page Include="Views\Tools\EncodersDecoders\JwtDecoderEncoder\JwtEncoderControl.xaml">+ <Generator>MSBuild:Compile</Generator>+ <SubType>Designer</SubType>+ </Page><Page Include="Views\Tools\Graphic\ColorPicker\ColorPickerToolPage.xaml"><Generator>MSBuild:Compile</Generator><SubType>Designer</SubType>@@ -742,6 +773,7 @@<PackageReference Include="Microsoft.UI.Xaml" Version="$(NuGet_MicrosoftUIXaml)" /><PackageReference Include="Newtonsoft.Json" Version="$(NuGet_NewtonsoftJson)" /><PackageReference Include="NLipsum" Version="$(NuGet_NLipsum)" />+ <PackageReference Include="BouncyCastle.NetCore" Version="$(NuGet_BouncyCastleNetCore)" /><PackageReference Include="System.Composition" Version="$(NuGet_DotNet)" /><PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="$(NuGet_IdentityModelTokenJwt)" /><PackageReference Include="YamlDotNet" Version="$(NuGet_YamlDotNet)" />diff --git a/src/dev/impl/DevToys/Helpers/Base64Helper.cs b/src/dev/impl/DevToys/Helpers/Base64Helper.csnew file mode 100644index 000000000..8d0b4fa26--- /dev/null+++ b/src/dev/impl/DevToys/Helpers/Base64Helper.cs@@ -0,0 +1,76 @@+#nullable enable++using System;+using System.Text;+using System.Text.RegularExpressions;++namespace DevToys.Helpers+{+ internal static class Base64Helper+ {+ internal static bool IsBase64DataStrict(string? data)+ {+ if (string.IsNullOrWhiteSpace(data))+ {+ return false;+ }++ data = data!.Trim();++ if (data.Length % 4 != 0)+ {+ return false;+ }++ if (new Regex(@"[^A-Z0-9+/=]", RegexOptions.IgnoreCase).IsMatch(data))+ {+ return false;+ }++ int equalIndex = data.IndexOf('=');+ int length = data.Length;++ if (!(equalIndex == -1 || equalIndex == length - 1 || (equalIndex == length - 2 && data[length - 1] == '=')))+ {+ return false;+ }++ string? decoded;++ try+ {+ byte[]? decodedData = Convert.FromBase64String(data);+ decoded = Encoding.UTF8.GetString(decodedData);+ }+ catch (Exception)+ {+ return false;+ }++ //check for special chars that you know should not be there+ char current;+ for (int i = 0; i < decoded.Length; i++)+ {+ current = decoded[i];+ if (current == 65533)+ {+ return false;+ }++#pragma warning disable IDE0078 // Use pattern matching+ if (!(current == 0x9+ || current == 0xA+ || current == 0xD+ || (current >= 0x20 && current <= 0xD7FF)+ || (current >= 0xE000 && current <= 0xFFFD)+ || (current >= 0x10000 && current <= 0x10FFFF)))+#pragma warning restore IDE0078 // Use pattern matching+ {+ return false;+ }+ }++ return true;+ }+ }+}diff --git a/src/dev/impl/DevToys/Helpers/JwtHelper.cs b/src/dev/impl/DevToys/Helpers/JwtHelper.csindex 9dd7bddff..f9446ab80 100644--- a/src/dev/impl/DevToys/Helpers/JwtHelper.cs+++ b/src/dev/impl/DevToys/Helpers/JwtHelper.cs@@ -7,6 +7,9 @@ namespace DevToys.Helpers{internal static class JwtHelper{+ private static readonly string AuthorizationHeader = "Authorization:";+ private static readonly string BearerScheme = "Bearer";+/// <summary>/// Detects whether the given string is a JWT Token or not./// </summary>@@ -19,10 +22,20 @@ namespace DevToys.Helpersinput = input!.Trim();+ if (input.StartsWith(AuthorizationHeader))+ {+ input = input.Remove(0, AuthorizationHeader.Length).Trim();+ }++ if (input.StartsWith(BearerScheme))+ {+ input = input.Remove(0, BearerScheme.Length).Trim();+ }+try{var handler = new JwtSecurityTokenHandler();- JwtSecurityToken jwtSecurityToken = handler.ReadJwtToken(input);+ JwtSecurityToken jwtSecurityToken = handler.ReadJwtToken(input.Trim());return jwtSecurityToken is not null;}catch (Exception) //some other exceptiondiff --git a/src/dev/impl/DevToys/LanguageManager.cs b/src/dev/impl/DevToys/LanguageManager.csindex 31ac99e86..34fcb706a 100644--- a/src/dev/impl/DevToys/LanguageManager.cs+++ b/src/dev/impl/DevToys/LanguageManager.cs@@ -1582,9 +1582,9 @@ namespace DevToyspublic string MenuDisplayName => _resources.GetString("MenuDisplayName");/// <summary>- /// Gets the resource HeaderLabel.+ /// Gets the resource JwtHeaderLabel./// </summary>- public string HeaderLabel => _resources.GetString("HeaderLabel");+ public string JwtHeaderLabel => _resources.GetString("JwtHeaderLabel");/// <summary>/// Gets the resource JwtTokenLabel.@@ -1592,24 +1592,219 @@ namespace DevToyspublic string JwtTokenLabel => _resources.GetString("JwtTokenLabel");/// <summary>- /// Gets the resource PayloadLabel.+ /// Gets the resource JwtPayloadLabel./// </summary>- public string PayloadLabel => _resources.GetString("PayloadLabel");+ public string JwtPayloadLabel => _resources.GetString("JwtPayloadLabel");/// <summary>/// Gets the resource Description./// </summary>public string Description => _resources.GetString("Description");+ /// <summary>+ /// Gets the resource SearchKeywords.+ /// </summary>+ public string SearchKeywords => _resources.GetString("SearchKeywords");++ /// <summary>+ /// Gets the resource Algorithm.+ /// </summary>+ public string Algorithm => _resources.GetString("Algorithm");++ /// <summary>+ /// Gets the resource DecodeSwitchModeLabel.+ /// </summary>+ public string DecodeSwitchModeLabel => _resources.GetString("DecodeSwitchModeLabel");++ /// <summary>+ /// Gets the resource DecodeValidateTokenLabel.+ /// </summary>+ public string DecodeValidateTokenLabel => _resources.GetString("DecodeValidateTokenLabel");++ /// <summary>+ /// Gets the resource DecodeValidateTokenNoLabel.+ /// </summary>+ public string DecodeValidateTokenNoLabel => _resources.GetString("DecodeValidateTokenNoLabel");++ /// <summary>+ /// Gets the resource DecodeValidateTokenYesLabel.+ /// </summary>+ public string DecodeValidateTokenYesLabel => _resources.GetString("DecodeValidateTokenYesLabel");++ /// <summary>+ /// Gets the resource EncodeExpirationTitle.+ /// </summary>+ public string EncodeExpirationTitle => _resources.GetString("EncodeExpirationTitle");++ /// <summary>+ /// Gets the resource EncodeExpirationMonthLabel.+ /// </summary>+ public string EncodeExpirationMonthLabel => _resources.GetString("EncodeExpirationMonthLabel");++ /// <summary>+ /// Gets the resource EncodeExpirationYearLabel.+ /// </summary>+ public string EncodeExpirationYearLabel => _resources.GetString("EncodeExpirationYearLabel");++ /// <summary>+ /// Gets the resource EncodeHashingTitle.+ /// </summary>+ public string EncodeHashingTitle => _resources.GetString("EncodeHashingTitle");++ /// <summary>+ /// Gets the resource EncodeSettingsTitle.+ /// </summary>+ public string EncodeSettingsTitle => _resources.GetString("EncodeSettingsTitle");++ /// <summary>+ /// Gets the resource EncodeSwitchModeLabel.+ /// </summary>+ public string EncodeSwitchModeLabel => _resources.GetString("EncodeSwitchModeLabel");++ /// <summary>+ /// Gets the resource SettingsSwitchModeLabel.+ /// </summary>+ public string SettingsSwitchModeLabel => _resources.GetString("SettingsSwitchModeLabel");++ /// <summary>+ /// Gets the resource SettingsTitle.+ /// </summary>+ public string SettingsTitle => _resources.GetString("SettingsTitle");++ /// <summary>+ /// Gets the resource EncodeDefaultTimeTitle.+ /// </summary>+ public string EncodeDefaultTimeTitle => _resources.GetString("EncodeDefaultTimeTitle");++ /// <summary>+ /// Gets the resource EncodeExpirationDaysLabel.+ /// </summary>+ public string EncodeExpirationDaysLabel => _resources.GetString("EncodeExpirationDaysLabel");++ /// <summary>+ /// Gets the resource EncodeExpirationHoursLabel.+ /// </summary>+ public string EncodeExpirationHoursLabel => _resources.GetString("EncodeExpirationHoursLabel");++ /// <summary>+ /// Gets the resource EncodeExpirationMinutesLabel.+ /// </summary>+ public string EncodeExpirationMinutesLabel => _resources.GetString("EncodeExpirationMinutesLabel");++ /// <summary>+ /// Gets the resource PrivateKeyLabel.+ /// </summary>+ public string PrivateKeyLabel => _resources.GetString("PrivateKeyLabel");++ /// <summary>+ /// Gets the resource SignatureLabel.+ /// </summary>+ public string SignatureLabel => _resources.GetString("SignatureLabel");++ /// <summary>+ /// Gets the resource JwtIsValidMessage.+ /// </summary>+ public string JwtIsValidMessage => _resources.GetString("JwtIsValidMessage");++ /// <summary>+ /// Gets the resource InvalidPublicKeyError.+ /// </summary>+ public string InvalidPublicKeyError => _resources.GetString("InvalidPublicKeyError");++ /// <summary>+ /// Gets the resource JwtInValidMessage.+ /// </summary>+ public string JwtInValidMessage => _resources.GetString("JwtInValidMessage");++ /// <summary>+ /// Gets the resource DecodeValidateActorLabel.+ /// </summary>+ public string DecodeValidateActorLabel => _resources.GetString("DecodeValidateActorLabel");++ /// <summary>+ /// Gets the resource DecodeValidateAudienceLabel.+ /// </summary>+ public string DecodeValidateAudienceLabel => _resources.GetString("DecodeValidateAudienceLabel");++ /// <summary>+ /// Gets the resource DecodeValidateIssuerLabel.+ /// </summary>+ public string DecodeValidateIssuerLabel => _resources.GetString("DecodeValidateIssuerLabel");++ /// <summary>+ /// Gets the resource DecodeValidateLifetimeLabel.+ /// </summary>+ public string DecodeValidateLifetimeLabel => _resources.GetString("DecodeValidateLifetimeLabel");++ /// <summary>+ /// Gets the resource ValidAudiencesLabel.+ /// </summary>+ public string ValidAudiencesLabel => _resources.GetString("ValidAudiencesLabel");++ /// <summary>+ /// Gets the resource ValidIssuersLabel.+ /// </summary>+ public string ValidIssuersLabel => _resources.GetString("ValidIssuersLabel");++ /// <summary>+ /// Gets the resource DecodeValidationSettingsDescription.+ /// </summary>+ public string DecodeValidationSettingsDescription => _resources.GetString("DecodeValidationSettingsDescription");++ /// <summary>+ /// Gets the resource DecodeValidationSettingsTitle.+ /// </summary>+ public string DecodeValidationSettingsTitle => _resources.GetString("DecodeValidationSettingsTitle");++ /// <summary>+ /// Gets the resource ValidAudiencesError.+ /// </summary>+ public string ValidAudiencesError => _resources.GetString("ValidAudiencesError");++ /// <summary>+ /// Gets the resource ValidIssuersError.+ /// </summary>+ public string ValidIssuersError => _resources.GetString("ValidIssuersError");++ /// <summary>+ /// Gets the resource PublicKeyIsPrivateKeyError.+ /// </summary>+ public string PublicKeyIsPrivateKeyError => _resources.GetString("PublicKeyIsPrivateKeyError");++ /// <summary>+ /// Gets the resource EncodeAudienceLabel.+ /// </summary>+ public string EncodeAudienceLabel => _resources.GetString("EncodeAudienceLabel");++ /// <summary>+ /// Gets the resource EncodeIssuerLabel.+ /// </summary>+ public string EncodeIssuerLabel => _resources.GetString("EncodeIssuerLabel");++ /// <summary>+ /// Gets the resource EncodeSettingsDescription.+ /// </summary>+ public string EncodeSettingsDescription => _resources.GetString("EncodeSettingsDescription");++ /// <summary>+ /// Gets the resource InvalidPrivateKeyError.+ /// </summary>+ public string InvalidPrivateKeyError => _resources.GetString("InvalidPrivateKeyError");++ /// <summary>+ /// Gets the resource PublicKeyLabel.+ /// </summary>+ public string PublicKeyLabel => _resources.GetString("PublicKeyLabel");+/// <summary>/// Gets the resource SearchDisplayName./// </summary>public string SearchDisplayName => _resources.GetString("SearchDisplayName");/// <summary>- /// Gets the resource SearchKeywords.+ /// Gets the resource InvalidSignatureError./// </summary>- public string SearchKeywords => _resources.GetString("SearchKeywords");+ public string InvalidSignatureError => _resources.GetString("InvalidSignatureError");}public class LoremIpsumGeneratorStrings : ObservableObjectdiff --git a/src/dev/impl/DevToys/Models/JwtAlgorithm.cs b/src/dev/impl/DevToys/Models/JwtAlgorithm.csnew file mode 100644index 000000000..49ad9edf1--- /dev/null+++ b/src/dev/impl/DevToys/Models/JwtAlgorithm.cs@@ -0,0 +1,18 @@+namespace DevToys.Models+{+ public enum JwtAlgorithm+ {+ HS256,+ HS384,+ HS512,+ RS256,+ RS384,+ RS512,+ ES256,+ ES384,+ ES512,+ PS256,+ PS384,+ PS512+ }+}diff --git a/src/dev/impl/DevToys/Models/JwtAlgorithmDisplayPair.cs b/src/dev/impl/DevToys/Models/JwtAlgorithmDisplayPair.csnew file mode 100644index 000000000..7bae9f7df--- /dev/null+++ b/src/dev/impl/DevToys/Models/JwtAlgorithmDisplayPair.cs@@ -0,0 +1,32 @@+using System;++namespace DevToys.Models+{+ public sealed class JwtAlgorithmDisplayPair : IEquatable<JwtAlgorithmDisplayPair>+ {+ public static readonly JwtAlgorithmDisplayPair HS256 = new(nameof(HS256), JwtAlgorithm.HS256);+ public static readonly JwtAlgorithmDisplayPair HS384 = new(nameof(HS384), JwtAlgorithm.HS384);+ public static readonly JwtAlgorithmDisplayPair HS512 = new(nameof(HS512), JwtAlgorithm.HS512);+ public static readonly JwtAlgorithmDisplayPair RS256 = new(nameof(RS256), JwtAlgorithm.RS256);+ public static readonly JwtAlgorithmDisplayPair RS384 = new(nameof(RS384), JwtAlgorithm.RS384);+ public static readonly JwtAlgorithmDisplayPair RS512 = new(nameof(RS512), JwtAlgorithm.RS512);+ public static readonly JwtAlgorithmDisplayPair ES256 = new(nameof(ES256), JwtAlgorithm.ES256);+ public static readonly JwtAlgorithmDisplayPair ES384 = new(nameof(ES384), JwtAlgorithm.ES384);+ public static readonly JwtAlgorithmDisplayPair ES512 = new(nameof(ES512), JwtAlgorithm.ES512);+ public static readonly JwtAlgorithmDisplayPair PS256 = new(nameof(PS256), JwtAlgorithm.PS256);+ public static readonly JwtAlgorithmDisplayPair PS384 = new(nameof(PS384), JwtAlgorithm.PS384);+ public static readonly JwtAlgorithmDisplayPair PS512 = new(nameof(PS512), JwtAlgorithm.PS512);++ public string DisplayName { get; }++ public JwtAlgorithm Value { get; }++ private JwtAlgorithmDisplayPair(string displayName, JwtAlgorithm value)+ {+ DisplayName = displayName;+ Value = value;+ }++ public bool Equals(JwtAlgorithmDisplayPair other) => other.Value == Value;+ }+}diff --git a/src/dev/impl/DevToys/Models/JwtDecoderEncoder/DecoderParameters.cs b/src/dev/impl/DevToys/Models/JwtDecoderEncoder/DecoderParameters.csnew file mode 100644index 000000000..213193b6e--- /dev/null+++ b/src/dev/impl/DevToys/Models/JwtDecoderEncoder/DecoderParameters.cs@@ -0,0 +1,20 @@+#nullable enable++using DevToys;++namespace DevToys.Models.JwtDecoderEncoder+{+ public record DecoderParameters+ {+ public bool ValidateSignature { get; set; }++ public bool ValidateActor { get; set; }++ public bool ValidateLifetime { get; set; }++ public bool ValidateIssuer { get; set; }++ public bool ValidateAudience { get; set; }++ }+}diff --git a/src/dev/impl/DevToys/Models/JwtDecoderEncoder/EncoderParameters.cs b/src/dev/impl/DevToys/Models/JwtDecoderEncoder/EncoderParameters.csnew file mode 100644index 000000000..b1d6946ea--- /dev/null+++ b/src/dev/impl/DevToys/Models/JwtDecoderEncoder/EncoderParameters.cs@@ -0,0 +1,17 @@+#nullable enable++using DevToys;++namespace DevToys.Models.JwtDecoderEncoder+{+ public record EncoderParameters+ {+ public bool HasExpiration { get; set; }++ public bool HasAudience { get; set; }++ public bool HasIssuer { get; set; }++ public bool HasDefaultTime { get; set; }+ }+}diff --git a/src/dev/impl/DevToys/Models/JwtDecoderEncoder/TokenParameters.cs b/src/dev/impl/DevToys/Models/JwtDecoderEncoder/TokenParameters.csnew file mode 100644index 000000000..5699496de--- /dev/null+++ b/src/dev/impl/DevToys/Models/JwtDecoderEncoder/TokenParameters.cs@@ -0,0 +1,37 @@+#nullable enable++using System.Collections.Generic;+using System.Linq;++namespace DevToys.Models.JwtDecoderEncoder+{+ public class TokenParameters+ {+ public string? Token { get; set; }++ public string? Payload { get; set; }++ public string? Signature { get; set; }++ public string? PublicKey { get; set; }++ public string? PrivateKey { get; set; }++ public JwtAlgorithm TokenAlgorithm { get; set; }++ public int ExpirationYear { get; set; }++ public int ExpirationMonth { get; set; }++ public int ExpirationDay { get; set; }++ public int ExpirationHour { get; set; }++ public int ExpirationMinute { get; set; }++ public HashSet<string> ValidIssuers { get; set; } = new HashSet<string>();++ public HashSet<string> ValidAudiences { get; set; } = new HashSet<string>();++ }+}diff --git a/src/dev/impl/DevToys/Models/JwtDecoderEncoder/TokenResult.cs b/src/dev/impl/DevToys/Models/JwtDecoderEncoder/TokenResult.csnew file mode 100644index 000000000..eeba1aa86--- /dev/null+++ b/src/dev/impl/DevToys/Models/JwtDecoderEncoder/TokenResult.cs@@ -0,0 +1,22 @@+#nullable enable+++namespace DevToys.Models.JwtDecoderEncoder+{+ public class TokenResult+ {+ public string? Token { get; set; }++ public string? Header { get; set; }++ public string? Payload { get; set; }++ public string? Signature { get; set; }++ public string? PublicKey { get; set; }++ public string? PrivateKey { get; set; }++ public JwtAlgorithm TokenAlgorithm { get; set; }+ }+}diff --git a/src/dev/impl/DevToys/Models/JwtDecoderEncoder/TokenResultErrorEventArgs.cs b/src/dev/impl/DevToys/Models/JwtDecoderEncoder/TokenResultErrorEventArgs.csnew file mode 100644index 000000000..c8dd6e700--- /dev/null+++ b/src/dev/impl/DevToys/Models/JwtDecoderEncoder/TokenResultErrorEventArgs.cs@@ -0,0 +1,14 @@+#nullable enable++using System;+using Microsoft.UI.Xaml.Controls;++namespace DevToys.Models.JwtDecoderEncoder+{+ public class TokenResultErrorEventArgs : EventArgs+ {+ public string Message { get; set; } = string.Empty;++ public InfoBarSeverity Severity { get; set; }+ }+}diff --git a/src/dev/impl/DevToys/Models/ValidationBase.cs b/src/dev/impl/DevToys/Models/ValidationBase.csnew file mode 100644index 000000000..2546222d1--- /dev/null+++ b/src/dev/impl/DevToys/Models/ValidationBase.cs@@ -0,0 +1,11 @@+#nullable enable++namespace DevToys.Models+{+ public record ValidationBase+ {+ internal bool IsValid { get; set; }++ internal string? ErrorMessage { get; set; }+ }+}diff --git a/src/dev/impl/DevToys/Strings/en-US/JwtDecoderEncoder.resw b/src/dev/impl/DevToys/Strings/en-US/JwtDecoderEncoder.reswindex 678c56cb6..8ac98bf45 100644--- a/src/dev/impl/DevToys/Strings/en-US/JwtDecoderEncoder.resw+++ b/src/dev/impl/DevToys/Strings/en-US/JwtDecoderEncoder.resw@@ -118,27 +118,144 @@<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader><data name="AccessibleName" xml:space="preserve">- <value>JWT Decoder tool</value>+ <value>JWT Encoder / Decoder tool</value></data><data name="MenuDisplayName" xml:space="preserve">- <value>JWT Decoder</value>+ <value>JWT</value></data>- <data name="HeaderLabel" xml:space="preserve">+ <data name="JwtHeaderLabel" xml:space="preserve"><value>Header</value></data><data name="JwtTokenLabel" xml:space="preserve">- <value>Jwt Token</value>+ <value>Token</value></data>- <data name="PayloadLabel" xml:space="preserve">+ <data name="JwtPayloadLabel" xml:space="preserve"><value>Payload</value></data><data name="Description" xml:space="preserve"><value>Decode a JWT header, payload and signature</value></data>- <data name="SearchDisplayName" xml:space="preserve">- <value>JWT Decoder</value>- </data><data name="SearchKeywords" xml:space="preserve"><value /></data>+ <data name="Algorithm" xml:space="preserve">+ <value>Algorithm</value>+ </data>+ <data name="DecodeSwitchModeLabel" xml:space="preserve">+ <value>Decode</value>+ </data>+ <data name="DecodeValidateTokenLabel" xml:space="preserve">+ <value>Validate Token</value>+ </data>+ <data name="DecodeValidateTokenNoLabel" xml:space="preserve">+ <value>No</value>+ </data>+ <data name="DecodeValidateTokenYesLabel" xml:space="preserve">+ <value>Yes</value>+ </data>+ <data name="EncodeExpirationTitle" xml:space="preserve">+ <value>Token has expirations</value>+ </data>+ <data name="EncodeExpirationMonthLabel" xml:space="preserve">+ <value>Expire in month(s)</value>+ </data>+ <data name="EncodeExpirationYearLabel" xml:space="preserve">+ <value>Expire in year(s)</value>+ </data>+ <data name="EncodeHashingTitle" xml:space="preserve">+ <value>Token hashing algorithm</value>+ </data>+ <data name="EncodeSettingsTitle" xml:space="preserve">+ <value>Settings</value>+ </data>+ <data name="EncodeSwitchModeLabel" xml:space="preserve">+ <value>Encode</value>+ </data>+ <data name="SettingsSwitchModeLabel" xml:space="preserve">+ <value>Encode / Decode</value>+ </data>+ <data name="SettingsTitle" xml:space="preserve">+ <value>Configuration</value>+ </data>+ <data name="EncodeDefaultTimeTitle" xml:space="preserve">+ <value>Token has default time</value>+ </data>+ <data name="EncodeExpirationDaysLabel" xml:space="preserve">+ <value>Expire in day(s)</value>+ </data>+ <data name="EncodeExpirationHoursLabel" xml:space="preserve">+ <value>Expire in hour(s)</value>+ </data>+ <data name="EncodeExpirationMinutesLabel" xml:space="preserve">+ <value>Expire in minute(s)</value>+ </data>+ <data name="PrivateKeyLabel" xml:space="preserve">+ <value>Private Key</value>+ </data>+ <data name="SignatureLabel" xml:space="preserve">+ <value>Signature</value>+ </data>+ <data name="JwtIsValidMessage" xml:space="preserve">+ <value>Signature Verified</value>+ </data>+ <data name="InvalidPublicKeyError" xml:space="preserve">+ <value>Invalid Public Key</value>+ </data>+ <data name="JwtInValidMessage" xml:space="preserve">+ <value>Invalid Signature</value>+ </data>+ <data name="DecodeValidateActorLabel" xml:space="preserve">+ <value>Validate actor</value>+ </data>+ <data name="DecodeValidateAudienceLabel" xml:space="preserve">+ <value>Validate audience</value>+ </data>+ <data name="DecodeValidateIssuerLabel" xml:space="preserve">+ <value>Validate issuer</value>+ </data>+ <data name="DecodeValidateLifetimeLabel" xml:space="preserve">+ <value>Validate lifetime</value>+ </data>+ <data name="ValidAudiencesLabel" xml:space="preserve">+ <value>Valid audiences</value>+ </data>+ <data name="ValidIssuersLabel" xml:space="preserve">+ <value>Valid issuers</value>+ </data>+ <data name="DecodeValidationSettingsDescription" xml:space="preserve">+ <value>Select which token paramters to validate</value>+ </data>+ <data name="DecodeValidationSettingsTitle" xml:space="preserve">+ <value>Token validation settings</value>+ </data>+ <data name="ValidAudiencesError" xml:space="preserve">+ <value>Valid audiences are empty</value>+ </data>+ <data name="ValidIssuersError" xml:space="preserve">+ <value>Valid issuers are empty</value>+ </data>+ <data name="PublicKeyIsPrivateKeyError" xml:space="preserve">+ <value>The public key provided is a private key</value>+ </data>+ <data name="EncodeAudienceLabel" xml:space="preserve">+ <value>Token has audience</value>+ </data>+ <data name="EncodeIssuerLabel" xml:space="preserve">+ <value>Token has issuer</value>+ </data>+ <data name="EncodeSettingsDescription" xml:space="preserve">+ <value>Select token parameters</value>+ </data>+ <data name="InvalidPrivateKeyError" xml:space="preserve">+ <value>Invalid Private Key</value>+ </data>+ <data name="PublicKeyLabel" xml:space="preserve">+ <value>Public Key</value>+ </data>+ <data name="SearchDisplayName" xml:space="preserve">+ <value>JWT Encoder / Decoder</value>+ </data>+ <data name="InvalidSignatureError" xml:space="preserve">+ <value>Invalid Signature</value>+ </data></root>\ No newline at end of filediff --git a/src/dev/impl/DevToys/UI/Controls/CustomTextBox.xaml.cs b/src/dev/impl/DevToys/UI/Controls/CustomTextBox.xaml.csindex 4dbcaff78..d87c9cdf1 100644--- a/src/dev/impl/DevToys/UI/Controls/CustomTextBox.xaml.cs+++ b/src/dev/impl/DevToys/UI/Controls/CustomTextBox.xaml.cs@@ -31,7 +31,7 @@ namespace DevToys.UI.Controlsnameof(Header),typeof(object),typeof(CustomTextBox),- new PropertyMetadata(null));+ new PropertyMetadata(null, OnHeaderPropertyChangedCalled));public string? Header{@@ -811,6 +811,11 @@ namespace DevToys.UI.Controls((CustomTextBox)sender).UpdateUI();}+ private static void OnHeaderPropertyChangedCalled(DependencyObject sender, DependencyPropertyChangedEventArgs eventArgs)+ {+ ((CustomTextBox)sender).UpdateUI();+ }+private static void OnTextPropertyChangedCalled(DependencyObject sender, DependencyPropertyChangedEventArgs eventArgs){var customTextBox = (CustomTextBox)sender;diff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/Base64TextEncoderDecoder/Base64EncoderDecoderToolProvider.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/Base64TextEncoderDecoder/Base64EncoderDecoderToolProvider.csindex 8f8d7bc8f..8fc18cab3 100644--- a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/Base64TextEncoderDecoder/Base64EncoderDecoderToolProvider.cs+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/Base64TextEncoderDecoder/Base64EncoderDecoderToolProvider.cs@@ -6,6 +6,7 @@ using System.Text;using System.Text.RegularExpressions;using DevToys.Api.Tools;using DevToys.Core.Threading;+using DevToys.Helpers;using DevToys.Shared.Api.Core;using Windows.UI.Xaml.Controls;@@ -46,7 +47,7 @@ namespace DevToys.ViewModels.Tools.Base64EncoderDecoder}string? trimmedData = data.Trim();- bool isBase64 = IsBase64DataStrict(trimmedData);+ bool isBase64 = Base64Helper.IsBase64DataStrict(trimmedData);return isBase64;}@@ -55,68 +56,5 @@ namespace DevToys.ViewModels.Tools.Base64EncoderDecoder{return _mefProvider.Import<Base64EncoderDecoderToolViewModel>();}-- private bool IsBase64DataStrict(string data)- {- if (string.IsNullOrWhiteSpace(data))- {- return false;- }-- if (data.Length % 4 != 0)- {- return false;- }-- if (new Regex(@"[^A-Z0-9+/=]", RegexOptions.IgnoreCase).IsMatch(data))- {- return false;- }-- int equalIndex = data.IndexOf('=');- int length = data.Length;-- if (!(equalIndex == -1 || equalIndex == length - 1 || (equalIndex == length - 2 && data[length - 1] == '=')))- {- return false;- }-- string? decoded;-- try- {- byte[]? decodedData = Convert.FromBase64String(data);- decoded = Encoding.UTF8.GetString(decodedData);- }- catch (Exception)- {- return false;- }-- //check for special chars that you know should not be there- char current;- for (int i = 0; i < decoded.Length; i++)- {- current = decoded[i];- if (current == 65533)- {- return false;- }--#pragma warning disable IDE0078 // Use pattern matching- if (!(current == 0x9- || current == 0xA- || current == 0xD- || (current >= 0x20 && current <= 0xD7FF)- || (current >= 0xE000 && current <= 0xFFFD)- || (current >= 0x10000 && current <= 0x10FFFF)))-#pragma warning restore IDE0078 // Use pattern matching- {- return false;- }- }-- return true;- }}}diff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoder.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoder.csnew file mode 100644index 000000000..58a2fe33f--- /dev/null+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoder.cs@@ -0,0 +1,301 @@+#nullable enable++using System;+using System.Composition;+using System.IdentityModel.Tokens.Jwt;+using System.IO;+using System.Linq;+using System.Security.Cryptography;+using System.Text;+using DevToys.Helpers;+using DevToys.Helpers.JsonYaml;+using DevToys.Models;+using DevToys.Models.JwtDecoderEncoder;+using DevToys.Shared.Core;+using Microsoft.IdentityModel.Logging;+using Microsoft.IdentityModel.Tokens;+using Microsoft.UI.Xaml.Controls;+using Org.BouncyCastle.Crypto;+using Org.BouncyCastle.Crypto.Parameters;+using Org.BouncyCastle.OpenSsl;++namespace DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder+{+ [Export(typeof(JwtDecoder))]+ [Shared]+ public class JwtDecoder+ {+ private const string PublicKeyStart = "-----BEGIN PUBLIC KEY-----";+ private const string PublicKeyEnd = "-----END PUBLIC KEY-----";+ private Action<TokenResultErrorEventArgs>? _decodingErrorCallBack;+ private JwtDecoderEncoderStrings _localizedStrings => LanguageManager.Instance.JwtDecoderEncoder;++ public TokenResult? DecodeToken(+ DecoderParameters decodeParameters,+ TokenParameters tokenParameters,+ Action<TokenResultErrorEventArgs> decodingErrorCallBack)+ {+ Arguments.NotNull(decodeParameters, nameof(decodeParameters));+ Arguments.NotNull(tokenParameters, nameof(tokenParameters));+ _decodingErrorCallBack = Arguments.NotNull(decodingErrorCallBack, nameof(decodingErrorCallBack));+ Arguments.NotNullOrWhiteSpace(tokenParameters.Token, nameof(tokenParameters.Token));++ var tokenResult = new TokenResult();++ try+ {+ IdentityModelEventSource.ShowPII = true;+ var handler = new JwtSecurityTokenHandler();+ JwtSecurityToken jwtSecurityToken = handler.ReadJwtToken(tokenParameters.Token);+ tokenResult.Header = JsonHelper.Format(jwtSecurityToken.Header.SerializeToJson(), Indentation.TwoSpaces, false);+ tokenResult.Payload = JsonHelper.Format(jwtSecurityToken.Payload.SerializeToJson(), Indentation.TwoSpaces, false);+ tokenResult.TokenAlgorithm = tokenParameters.TokenAlgorithm;++ if (decodeParameters.ValidateSignature)+ {+ bool signatureValid = ValidateTokenSignature(handler, decodeParameters, tokenParameters, tokenResult);+ if (!signatureValid)+ {+ return null;+ }+ }+ }+ catch (Exception exception)+ {+ RaiseError(exception.Message);+ return null;+ }++ return tokenResult;+ }++ /// <summary>+ /// Validate the token using the Signing Credentials+ /// </summary>+ private bool ValidateTokenSignature(+ JwtSecurityTokenHandler handler,+ DecoderParameters decodeParameters,+ TokenParameters tokenParameters,+ TokenResult tokenResult)+ {+ SigningCredentials? signingCredentials = GetValidationCredentials(tokenParameters);+ var validationParameters = new TokenValidationParameters+ {+ ValidateIssuerSigningKey = true,+ IssuerSigningKey = signingCredentials.Key,+ TryAllIssuerSigningKeys = true,+ ValidateActor = decodeParameters.ValidateActor,+ ValidateLifetime = decodeParameters.ValidateLifetime,+ ValidateIssuer = decodeParameters.ValidateIssuer,+ ValidateAudience = decodeParameters.ValidateAudience+ };++ /// check if the token issuers are part of the user provided issuers+ if (decodeParameters.ValidateIssuer)+ {+ if (tokenParameters.ValidIssuers.Count == 0)+ {+ RaiseError(_localizedStrings.ValidIssuersError);+ return false;+ }+ validationParameters.ValidIssuers = tokenParameters.ValidIssuers;+ }++ /// check if the token audience are part of the user provided audiences+ if (decodeParameters.ValidateAudience)+ {+ if (tokenParameters.ValidAudiences.Count == 0)+ {+ RaiseError(_localizedStrings.ValidAudiencesError);+ return false;+ }+ validationParameters.ValidAudiences = tokenParameters.ValidAudiences;+ }++ try+ {+ handler.ValidateToken(tokenParameters.Token, validationParameters, out _);+ tokenResult.Signature = tokenParameters.Signature;+ tokenResult.PublicKey = tokenParameters.PublicKey;+ return true;+ }+ catch (Exception exception)+ {+ RaiseError(exception.Message);+ }+ return false;+ }++ /// <summary>+ /// Get the Signing Credentials depending on the token Algorithm+ /// </summary>+ private SigningCredentials GetValidationCredentials(+ TokenParameters tokenParameters)+ {+ SigningCredentials? signingCredentials = tokenParameters.TokenAlgorithm switch+ {+ JwtAlgorithm.ES512 => new SigningCredentials(GetECDsaValidationKey(tokenParameters), SecurityAlgorithms.EcdsaSha512Signature),+ JwtAlgorithm.ES384 => new SigningCredentials(GetECDsaValidationKey(tokenParameters), SecurityAlgorithms.EcdsaSha384Signature),+ JwtAlgorithm.ES256 => new SigningCredentials(GetECDsaValidationKey(tokenParameters), SecurityAlgorithms.EcdsaSha256Signature),+ JwtAlgorithm.PS512 => new SigningCredentials(GetRsaShaValidationKey(tokenParameters), SecurityAlgorithms.RsaSsaPssSha512),+ JwtAlgorithm.PS384 => new SigningCredentials(GetRsaShaValidationKey(tokenParameters), SecurityAlgorithms.RsaSsaPssSha384),+ JwtAlgorithm.PS256 => new SigningCredentials(GetRsaShaValidationKey(tokenParameters), SecurityAlgorithms.RsaSsaPssSha256),+ JwtAlgorithm.RS512 => new SigningCredentials(GetRsaShaValidationKey(tokenParameters), SecurityAlgorithms.RsaSha512Signature),+ JwtAlgorithm.RS384 => new SigningCredentials(GetRsaShaValidationKey(tokenParameters), SecurityAlgorithms.RsaSha384Signature),+ JwtAlgorithm.RS256 => new SigningCredentials(GetRsaShaValidationKey(tokenParameters), SecurityAlgorithms.RsaSha256Signature),+ JwtAlgorithm.HS512 => new SigningCredentials(GetHmacShaValidationKey(tokenParameters), SecurityAlgorithms.HmacSha512Signature),+ JwtAlgorithm.HS384 => new SigningCredentials(GetHmacShaValidationKey(tokenParameters), SecurityAlgorithms.HmacSha384Signature),+ _ => new SigningCredentials(GetHmacShaValidationKey(tokenParameters), SecurityAlgorithms.HmacSha256Signature),// HS256+ };+ return signingCredentials;+ }++ /// <summary>+ /// Generate a Symetric Security Key using the token signature (base 64 or not)+ /// </summary>+ /// <param name="tokenParameters">Token parameters with the token signature</param>+ private SymmetricSecurityKey? GetHmacShaValidationKey(TokenParameters tokenParameters)+ {+ if (string.IsNullOrWhiteSpace(tokenParameters.Signature))+ {+ return null;+ }++ byte[]? signatureByte;+ if (Base64Helper.IsBase64DataStrict(tokenParameters.Signature))+ {+ signatureByte = Convert.FromBase64String(tokenParameters.Signature);+ }+ else+ {+ signatureByte = Encoding.UTF8.GetBytes(tokenParameters.Signature);+ }+ byte[] byteKey = tokenParameters.TokenAlgorithm switch+ {+ JwtAlgorithm.HS512 => new HMACSHA512(signatureByte).Key,+ JwtAlgorithm.HS384 => new HMACSHA384(signatureByte).Key,+ _ => new HMACSHA256(signatureByte).Key,// HS256+ };+ return new SymmetricSecurityKey(byteKey);+ }++ /// <summary>+ /// Generate a RSA Security Key using the token signing public key+ /// </summary>+ /// <param name="tokenParameters">Token parameters with the token signing public key</param>+ private RsaSecurityKey? GetRsaShaValidationKey(TokenParameters tokenParameters)+ {+ try+ {+ AsymmetricKeyParameter? asymmetricKeyParameter = GetPublicAsymmetricKeyParameter(tokenParameters);+ if (asymmetricKeyParameter is null)+ {+ RaiseError(_localizedStrings.InvalidPublicKeyError);+ return null;+ }++ var publicKey = (RsaKeyParameters)asymmetricKeyParameter;+ if (publicKey.IsPrivate)+ {+ RaiseError(_localizedStrings.PublicKeyIsPrivateKeyError);+ return null;+ }++ RSAParameters rsaParameters = new()+ {+ Modulus = publicKey.Modulus.ToByteArrayUnsigned(),+ Exponent = publicKey.Exponent.ToByteArrayUnsigned()+ };+ return new RsaSecurityKey(rsaParameters);+ }+ catch (Exception exception)+ {+ RaiseError($"{_localizedStrings.InvalidPublicKeyError}: '{exception.Message}'");+ return null;+ }+ }++ /// <summary>+ /// Generate a ECDsa Security Key using the token signing public key+ /// </summary>+ /// <param name="tokenParameters">Token parameters with the token signing public key</param>+ private ECDsaSecurityKey? GetECDsaValidationKey(TokenParameters tokenParameters)+ {+ try+ {+ AsymmetricKeyParameter? asymmetricKeyParameter = GetPublicAsymmetricKeyParameter(tokenParameters);+ if (asymmetricKeyParameter is null)+ {+ RaiseError(_localizedStrings.InvalidPublicKeyError);+ return null;+ }++ var publicKey = (ECPublicKeyParameters)asymmetricKeyParameter;+ if (publicKey.IsPrivate)+ {+ RaiseError(_localizedStrings.PublicKeyIsPrivateKeyError);+ return null;+ }++ ECParameters ecParameters = new()+ {+ Curve = ECCurve.NamedCurves.nistP256,+ Q = new()+ {+ X = publicKey.Q.AffineXCoord.GetEncoded(),+ Y = publicKey.Q.AffineYCoord.GetEncoded()+ }+ };+ var ecdSa = ECDsa.Create(ecParameters);+ return new ECDsaSecurityKey(ecdSa);+ }+ catch (Exception exception)+ {+ RaiseError($"{_localizedStrings.InvalidPublicKeyError}: '{exception.Message}'");+ return null;+ }+ }++ /// <summary>+ /// Generate the Asymetric Security Key using the token signing public key+ /// </summary>+ /// <param name="tokenParameters">Token parameters with the token signing public key</param>+ private AsymmetricKeyParameter? GetPublicAsymmetricKeyParameter(TokenParameters tokenParameters)+ {+ if (string.IsNullOrWhiteSpace(tokenParameters.PublicKey))+ {+ RaiseError(_localizedStrings.InvalidPublicKeyError);+ return null;+ }+ var publicKeyStringBuilder = new StringBuilder(tokenParameters.PublicKey!.Trim());+ if (!tokenParameters.PublicKey!.StartsWith(PublicKeyStart, StringComparison.OrdinalIgnoreCase))+ {+ publicKeyStringBuilder.Insert(0, PublicKeyStart);+ }+ if (!tokenParameters.PublicKey.EndsWith(PublicKeyEnd, StringComparison.OrdinalIgnoreCase))+ {+ publicKeyStringBuilder.Append(PublicKeyEnd);+ }++ var pemReader = new PemReader(new StringReader(publicKeyStringBuilder.ToString()));+ var asymetricPublicKey = (AsymmetricKeyParameter)pemReader.ReadObject();+ if (asymetricPublicKey is null)+ {+ RaiseError(_localizedStrings.InvalidPublicKeyError);+ return null;+ }++ return asymetricPublicKey;+ }++ private void RaiseError(string message)+ {+ var eventArg = new TokenResultErrorEventArgs+ {+ Message = message,+ Severity = InfoBarSeverity.Error+ };+ _decodingErrorCallBack!.Invoke(eventArg);+ }+ }+}diff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderControlViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderControlViewModel.csnew file mode 100644index 000000000..5f751d7f9--- /dev/null+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderControlViewModel.cs@@ -0,0 +1,119 @@+#nullable enable++using System;+using System.Composition;+using System.Linq;+using DevToys.Api.Core;+using DevToys.Api.Core.Settings;+using DevToys.Api.Tools;+using DevToys.Core.Threading;+using DevToys.Models;+using DevToys.Models.JwtDecoderEncoder;+using DevToys.Shared.Core.Threading;+using DevToys.Views.Tools.EncodersDecoders.JwtDecoderEncoder;+using Microsoft.Toolkit.Mvvm.Messaging;++namespace DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder+{+ [Export(typeof(JwtDecoderControlViewModel))]+ public sealed class JwtDecoderControlViewModel : JwtDecoderEncoderViewModelBase, IToolViewModel, IRecipient<JwtJobAddedMessage>+ {+ private readonly JwtDecoder _decoder;++ public Type View { get; } = typeof(JwtDecoderControl);++ [ImportingConstructor]+ public JwtDecoderControlViewModel(+ ISettingsProvider settingsProvider,+ IMarketingService marketingService,+ JwtDecoder decoder)+ : base(settingsProvider, marketingService)+ {+ IsActive = true;+ _decoder = decoder;+ ShowValidation = ValidateSignature;+ }++ public void Receive(JwtJobAddedMessage message)+ {+ if (string.IsNullOrWhiteSpace(Token))+ {+ return;+ }++ DecoderParameters decoderParamters = new();+ if (ValidateSignature)+ {+ decoderParamters.ValidateSignature = ValidateSignature;+ decoderParamters.ValidateAudience = ValidateAudience;+ decoderParamters.ValidateLifetime = ValidateLifetime;+ decoderParamters.ValidateIssuer = ValidateIssuer;+ decoderParamters.ValidateActor = ValidateActor;+ }++ TokenParameters tokenParameters = new()+ {+ Token = Token,+ Signature = Signature,+ PublicKey = PublicKey,+ };++ if (!string.IsNullOrEmpty(ValidIssuers))+ {+ tokenParameters.ValidIssuers = ValidIssuers!.Split(',').ToHashSet();+ }++ if (!string.IsNullOrEmpty(ValidAudiences))+ {+ tokenParameters.ValidAudiences = ValidAudiences!.Split(',').ToHashSet();+ }++ TokenResult? result = _decoder.DecodeToken(decoderParamters, tokenParameters, TokenErrorCallBack);++ ThreadHelper.RunOnUIThreadAsync(ThreadPriority.Low, () =>+ {+ if (result is null)+ {+ return;+ }++ Header = result.Header;+ Payload = result.Payload;++ if (ValidateSignature)+ {+ RequireSignature = true;+ if (result.TokenAlgorithm is+ not JwtAlgorithm.HS256 and+ not JwtAlgorithm.HS384 and+ not JwtAlgorithm.HS512)+ {+ RequireSignature = false;+ }++ }++ DisplayValidationInfoBar();+++ if (ToolSuccessfullyWorked)+ {+ ToolSuccessfullyWorked = true;+ MarketingService.NotifyToolSuccessfullyWorked();+ }+ }).ForgetSafely();+ }++ private void TokenErrorCallBack(TokenResultErrorEventArgs e)+ {+ JwtValidation.IsValid = false;+ JwtValidation.ErrorMessage = e.Message;+ ThreadHelper.RunOnUIThreadAsync(ThreadPriority.Low, () =>+ {+ Header = string.Empty;+ Payload = string.Empty;+ DisplayValidationInfoBar();+ }).ForgetSafely();+ }+ }+}diff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderSettings.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderSettings.csnew file mode 100644index 000000000..62cb74d76--- /dev/null+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderSettings.cs@@ -0,0 +1,208 @@+#nullable enable++using DevToys.Api.Core.Settings;+using DevToys.Models;++namespace DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder+{+ internal static class JwtDecoderEncoderSettings+ {+ /// <summary>+ /// Define if we need to show the validation parameters / inputs+ /// </summary>+ public static readonly SettingDefinition<bool> ShowValidation+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ShowValidation)}",+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Define if we need to validate the token signature+ /// </summary>+ public static readonly SettingDefinition<bool> ValidateSignature+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ValidateSignature)}",+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Define if we need to validate the token issuer+ /// </summary>+ public static readonly SettingDefinition<bool> ValidateIssuer+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ValidateIssuer)}",+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Define if we need to validate the token actor+ /// </summary>+ public static readonly SettingDefinition<bool> ValidateActor+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ValidateActor)}",+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Define if we need to validate the token audience+ /// </summary>+ public static readonly SettingDefinition<bool> ValidateAudience+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ValidateAudience)}",+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Define if we need to validate the token lifetime+ /// </summary>+ public static readonly SettingDefinition<bool> ValidateLifetime+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ValidateLifetime)}",+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Define if we need to validate the token lifetime+ /// </summary>+ public static readonly SettingDefinition<bool> JWtToolMode+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(JWtToolMode)}",+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Define if the token has an expiration+ /// </summary>+ public static readonly SettingDefinition<bool> HasExpiration+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(HasExpiration)}",+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Define if the token has a default time+ /// </summary>+ public static readonly SettingDefinition<bool> HasDefaultTime+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(HasDefaultTime)}",+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Define if the token has a default time+ /// </summary>+ public static readonly SettingDefinition<bool> HasAudience+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(HasAudience)}",+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Define if the token has a default time+ /// </summary>+ public static readonly SettingDefinition<string?> ValidAudiences+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ValidAudiences)}",+ isRoaming: true,+ defaultValue: string.Empty);++ /// <summary>+ /// Define if the token has a default time+ /// </summary>+ public static readonly SettingDefinition<bool> HasIssuer+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(HasIssuer)}",+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Define if the token has a default time+ /// </summary>+ public static readonly SettingDefinition<string?> ValidIssuers+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ValidIssuers)}",+ isRoaming: true,+ defaultValue: string.Empty);++ /// <summary>+ /// Define if the token expiration year+ /// </summary>+ public static readonly SettingDefinition<int> ExpireYear+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ExpireYear)}",+ isRoaming: true,+ defaultValue: 0);++ /// <summary>+ /// Define if the token expiration month+ /// </summary>+ public static readonly SettingDefinition<int> ExpireMonth+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ExpireMonth)}",+ isRoaming: true,+ defaultValue: 0);++ /// <summary>+ /// Define if the token expiration day+ /// </summary>+ public static readonly SettingDefinition<int> ExpireDay+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ExpireDay)}",+ isRoaming: true,+ defaultValue: 0);++ /// <summary>+ /// Define if the token expiration hours+ /// </summary>+ public static readonly SettingDefinition<int> ExpireHour+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ExpireHour)}",+ isRoaming: true,+ defaultValue: 0);++ /// <summary>+ /// Define if the token expiration minutes+ /// </summary>+ public static readonly SettingDefinition<int> ExpireMinute+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(ExpireMinute)}",+ isRoaming: true,+ defaultValue: 0);++ /// <summary>+ /// Define if the token expiration minutes+ /// </summary>+ public static readonly SettingDefinition<JwtAlgorithm> JwtAlgorithm+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(JwtAlgorithm)}",+ isRoaming: true,+ defaultValue: Models.JwtAlgorithm.HS256);++ /// <summary>+ /// Define if the token expiration minutes+ /// </summary>+ public static readonly SettingDefinition<string?> PublicKey+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(PublicKey)}",+ isRoaming: true,+ defaultValue: string.Empty);++ /// <summary>+ /// Define if the token expiration minutes+ /// </summary>+ public static readonly SettingDefinition<string?> PrivateKey+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(PrivateKey)}",+ isRoaming: true,+ defaultValue: string.Empty);++ /// <summary>+ /// Define if the token expiration minutes+ /// </summary>+ public static readonly SettingDefinition<string?> Signature+ = new(+ name: $"{nameof(JwtDecoderEncoderViewModelBase)}.{nameof(Signature)}",+ isRoaming: true,+ defaultValue: string.Empty);+ }+}diff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.csindex 63eb8980b..0d87d7aa8 100644--- a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.cs+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolViewModel.cs@@ -1,131 +1,48 @@#nullable enableusing System;-using System.Collections.Generic;using System.Composition;-using System.IdentityModel.Tokens.Jwt;-using System.Threading.Tasks;-using DevToys.Api.Core;+using DevToys.Api.Core.Settings;using DevToys.Api.Tools;-using DevToys.Core.Threading;-using DevToys.Shared.Core.Threading;-using DevToys.Models;+using DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder;using DevToys.Views.Tools.JwtDecoderEncoder;using Microsoft.Toolkit.Mvvm.ComponentModel;-using DevToys.Helpers.JsonYaml;namespace DevToys.ViewModels.Tools.JwtDecoderEncoder{[Export(typeof(JwtDecoderEncoderToolViewModel))]public sealed class JwtDecoderEncoderToolViewModel : ObservableRecipient, IToolViewModel{- private readonly IMarketingService _marketingService;- private readonly Queue<string> _decodingQueue = new();+ private readonly ISettingsProvider _settingsProvider;- private bool _toolSuccessfullyWorked;- private bool _decodingInProgress;- private string? _jwtToken;- private string? _jwtHeader;- private string? _jwtPayload;-- public Type View { get; } = typeof(JwtDecoderEncoderToolPage);-- internal JwtDecoderEncoderStrings Strings => LanguageManager.Instance.JwtDecoderEncoder;-- /// <summary>- /// Gets or sets the jwt token.- /// </summary>- internal string? JwtToken+ internal bool JwtToolMode{- get => _jwtToken;+ get => _settingsProvider.GetSetting(JwtDecoderEncoderSettings.JWtToolMode);set{- SetProperty(ref _jwtToken, value?.Trim());- QueueConversion();+ _settingsProvider.SetSetting(JwtDecoderEncoderSettings.JWtToolMode, value);+ OnPropertyChanged();}}- /// <summary>- /// Gets or sets the jwt header.- /// </summary>- internal string? JwtHeader- {- get => _jwtHeader;- set => SetProperty(ref _jwtHeader, value);- }-- /// <summary>- /// Gets or sets the jwt payload.- /// </summary>- internal string? JwtPayload- {- get => _jwtPayload;- set => SetProperty(ref _jwtPayload, value);- }-- [ImportingConstructor]- public JwtDecoderEncoderToolViewModel(IMarketingService marketingService)- {- _marketingService = marketingService;- }-- private void QueueConversion()- {- _decodingQueue.Enqueue(JwtToken ?? string.Empty);- TreatQueueAsync().Forget();- }-- private async Task TreatQueueAsync()- {- if (_decodingInProgress)- {- return;- }-- _decodingInProgress = true;-- await TaskScheduler.Default;+ internal JwtDecoderEncoderStrings Strings => LanguageManager.Instance.JwtDecoderEncoder;- while (_decodingQueue.TryDequeue(out string? text))- {- JwtDecode(text, out string? header, out string? payload);- ThreadHelper.RunOnUIThreadAsync(ThreadPriority.Low, () =>- {- JwtHeader = header;- JwtPayload = payload;+ public Type View { get; } = typeof(JwtDecoderEncoderToolPage);- if (!_toolSuccessfullyWorked)- {- _toolSuccessfullyWorked = true;- _marketingService.NotifyToolSuccessfullyWorked();- }- }).ForgetSafely();- }+ public JwtDecoderControlViewModel DecoderViewModel { get; private set; }- _decodingInProgress = false;- }+ public JwtEncoderControlViewModel EncoderViewModel { get; private set; }- private void JwtDecode(string input, out string header, out string payload)+ [ImportingConstructor]+ public JwtDecoderEncoderToolViewModel(+ JwtDecoderControlViewModel decoderControlViewModel,+ JwtEncoderControlViewModel encoderControlViewModel,+ ISettingsProvider settingsProvider){- if (string.IsNullOrWhiteSpace(input))- {- header = string.Empty;- payload = string.Empty;- return;- }-- try- {- var handler = new JwtSecurityTokenHandler();- JwtSecurityToken jwtSecurityToken = handler.ReadJwtToken(input);- header = JsonHelper.Format(jwtSecurityToken.Header.SerializeToJson(), Indentation.TwoSpaces, sortProperties: false);- payload = JsonHelper.Format(jwtSecurityToken.Payload.SerializeToJson(), Indentation.TwoSpaces, sortProperties: false);- }- catch (Exception ex)- {- header = ex.Message;- payload = ex.Message;- }+ DecoderViewModel = decoderControlViewModel;+ EncoderViewModel = encoderControlViewModel;+ _settingsProvider = settingsProvider;+ IsActive = true;}}}diff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderViewModelBase.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderViewModelBase.csnew file mode 100644index 000000000..106c513d3--- /dev/null+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderViewModelBase.cs@@ -0,0 +1,312 @@+#nullable enable++using System.Collections.Generic;+using System.Collections.ObjectModel;+using System.Linq;+using DevToys.Api.Core;+using DevToys.Api.Core.Settings;+using DevToys.Helpers.JsonYaml;+using DevToys.Models;+using DevToys.UI.Controls;+using Microsoft.Toolkit.Mvvm.ComponentModel;+using Microsoft.Toolkit.Mvvm.Messaging;+using Microsoft.UI.Xaml.Controls;+using Windows.UI.Xaml;++namespace DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder+{+ public abstract class JwtDecoderEncoderViewModelBase : ObservableRecipient+ {+ private string? _token;+ private string? _header;+ private string? _payload;+ private bool _requireSignature;+ private JwtAlgorithmDisplayPair? _algorithmSelected;+ private InfoBarData? _validationResult;++ protected bool WorkInProgress;+ protected bool ToolSuccessfullyWorked;+ protected readonly Queue<bool> JobQueue = new();+ protected readonly ISettingsProvider SettingsProvider;+ protected readonly IMarketingService MarketingService;++ internal ValidationBase JwtValidation = new();++ internal JwtDecoderEncoderStrings LocalizedStrings => LanguageManager.Instance.JwtDecoderEncoder;++ internal RoutedEventHandler InputFocusChanged { get; }++ internal virtual string? Token+ {+ get => _token;+ set+ {+ if (_token != value)+ {+ SetProperty(ref _token, value?.Trim());+ QueueNewTokenJob();+ }+ }+ }++ internal string? Header+ {+ get => _header;+ set+ {+ if (_header != value)+ {+ SetProperty(ref _header, value);+ QueueNewTokenJob();+ }+ }+ }++ internal string? Payload+ {+ get => _payload;+ set+ {+ if (_payload != value)+ {+ SetProperty(ref _payload, value);+ QueueNewTokenJob();+ }+ }+ }++ internal bool ValidateSignature+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ValidateSignature);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ValidateSignature, value);+ OnPropertyChanged();+ ShowValidation = value;+ QueueNewTokenJob();+ }+ }++ internal bool ValidateIssuer+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ValidateIssuer);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ValidateIssuer, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal bool ValidateActor+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ValidateActor);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ValidateActor, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal bool ValidateAudience+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ValidateAudience);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ValidateAudience, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal bool ValidateLifetime+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ValidateLifetime);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ValidateLifetime, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal string? ValidIssuers+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ValidIssuers);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ValidIssuers, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal string? ValidAudiences+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ValidAudiences);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ValidAudiences, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal string? PublicKey+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.PublicKey);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.PublicKey, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal string? PrivateKey+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.PrivateKey);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.PrivateKey, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal string? Signature+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.Signature);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.Signature, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal bool ShowValidation+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ShowValidation);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ShowValidation, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal bool RequireSignature+ {+ get => _requireSignature;+ set+ {+ if (_requireSignature != value)+ {+ SetProperty(ref _requireSignature, value);+ OnPropertyChanged();+ }+ }+ }++ internal InfoBarData? ValidationResult+ {+ get => _validationResult;+ private set => SetProperty(ref _validationResult, value);+ }++ internal JwtAlgorithmDisplayPair AlgorithmMode+ {+ get+ {+ JwtAlgorithm settingsValue = SettingsProvider.GetSetting(JwtDecoderEncoderSettings.JwtAlgorithm);+ JwtAlgorithmDisplayPair? algorithm = Algorithms.FirstOrDefault(x => x.Value == settingsValue);+ Header = JsonHelper.Format(@"{""alg"": """ + algorithm.DisplayName + @""", ""typ"": ""JWT""}", Indentation.TwoSpaces, false);+ IsSignatureRequired(algorithm);+ return _algorithmSelected ?? JwtAlgorithmDisplayPair.HS256;+ }+ set+ {+ if (_algorithmSelected != value)+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.JwtAlgorithm, value.Value);+ IsSignatureRequired(value);+ SetProperty(ref _algorithmSelected, value);+ OnPropertyChanged();+ }+ }+ }++ internal IReadOnlyList<JwtAlgorithmDisplayPair> Algorithms = new ObservableCollection<JwtAlgorithmDisplayPair> {+ JwtAlgorithmDisplayPair.HS256, JwtAlgorithmDisplayPair.HS384, JwtAlgorithmDisplayPair.HS512,+ JwtAlgorithmDisplayPair.RS256, JwtAlgorithmDisplayPair.RS384, JwtAlgorithmDisplayPair.RS512,+ JwtAlgorithmDisplayPair.ES256, JwtAlgorithmDisplayPair.ES384, JwtAlgorithmDisplayPair.ES512,+ JwtAlgorithmDisplayPair.PS256, JwtAlgorithmDisplayPair.PS384, JwtAlgorithmDisplayPair.PS512,+ };++ public JwtDecoderEncoderViewModelBase(+ ISettingsProvider settingsProvider,+ IMarketingService marketingService)+ {+ SettingsProvider = settingsProvider;+ MarketingService = marketingService;+ InputFocusChanged = ControlFocusChanged;+ IsSignatureRequired(AlgorithmMode);+ }++ internal void QueueNewTokenJob()+ {+ JwtValidation = new ValidationBase+ {+ IsValid = true+ };+ var newJob = new JwtJobAddedMessage();+ Messenger.Send(newJob);+ }++ protected void DisplayValidationInfoBar()+ {+ InfoBarSeverity infoBarSeverity;+ string message;+ if (!JwtValidation.IsValid)+ {+ infoBarSeverity = InfoBarSeverity.Error;+ message = JwtValidation.ErrorMessage ?? LocalizedStrings.JwtInValidMessage;+ }+ else+ {+ infoBarSeverity = InfoBarSeverity.Success;+ message = LocalizedStrings.JwtIsValidMessage;+ }++ ValidationResult = new InfoBarData(infoBarSeverity, message);+ }++ protected void ControlFocusChanged(object source, RoutedEventArgs args)+ {+ var input = (CustomTextBox)source;++ if (input.Text.Length == 0)+ {+ return;+ }++ QueueNewTokenJob();+ }++ private void IsSignatureRequired(JwtAlgorithmDisplayPair value)+ {+ if (value.Value is JwtAlgorithm.HS256 ||+ value.Value is JwtAlgorithm.HS384 ||+ value.Value is JwtAlgorithm.HS512)+ {+ RequireSignature = true;+ }+ else+ {+ RequireSignature = false;+ }+ }+ }+}diff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoder.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoder.csnew file mode 100644index 000000000..e225a6a2d--- /dev/null+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoder.cs@@ -0,0 +1,269 @@+#nullable enable++using System;+using System.Collections.Generic;+using System.Composition;+using System.IdentityModel.Tokens.Jwt;+using System.IO;+using System.Security.Cryptography;+using System.Text;+using System.Text.Json;+using DevToys.Helpers;+using DevToys.Models;+using DevToys.Models.JwtDecoderEncoder;+using DevToys.Shared.Core;+using Microsoft.IdentityModel.Tokens;+using Microsoft.UI.Xaml.Controls;+using Org.BouncyCastle.Crypto;+using Org.BouncyCastle.Crypto.Parameters;+using Org.BouncyCastle.Math;+using Org.BouncyCastle.OpenSsl;++namespace DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder+{+ [Export(typeof(JwtEncoder))]+ [Shared]+ public class JwtEncoder+ {+ private const string PrivateKeyStart = "-----BEGIN PRIVATE KEY-----";+ private const string PrivateKeyEnd = "-----END PRIVATE KEY-----";+ private Action<TokenResultErrorEventArgs>? _encodingErrorCallBack;+ private JwtDecoderEncoderStrings _localizedStrings => LanguageManager.Instance.JwtDecoderEncoder;++ public TokenResult? GenerateToken(+ EncoderParameters encodeParameters,+ TokenParameters tokenParameters,+ Action<TokenResultErrorEventArgs> encodingErrorCallBack)+ {+ Arguments.NotNull(encodeParameters, nameof(encodeParameters));+ Arguments.NotNull(tokenParameters, nameof(tokenParameters));+ _encodingErrorCallBack = Arguments.NotNull(encodingErrorCallBack, nameof(encodingErrorCallBack));+ Arguments.NotNullOrWhiteSpace(tokenParameters.Payload, nameof(tokenParameters.Payload));++ var tokenResult = new TokenResult();++ try+ {+ var serializeOptions = new JsonSerializerOptions();+ serializeOptions.Converters.Add(new JwtPayloadConverter());+ Dictionary<string, object>? payload = JsonSerializer.Deserialize<Dictionary<string, object>>(tokenParameters.Payload!, serializeOptions);+ SigningCredentials? signingCredentials = GetSigningCredentials(tokenParameters);++ if (signingCredentials is null)+ {+ return null;+ }++ var tokenDescriptor = new SecurityTokenDescriptor+ {+ Claims = payload,+ SigningCredentials = signingCredentials,+ Expires = null+ };++ if (encodeParameters.HasExpiration)+ {+ DateTime expirationDate = DateTime.UtcNow+ .AddYears(tokenParameters.ExpirationYear)+ .AddMonths(tokenParameters.ExpirationMonth)+ .AddDays(tokenParameters.ExpirationDay)+ .AddHours(tokenParameters.ExpirationHour)+ .AddMinutes(tokenParameters.ExpirationMinute);+ tokenDescriptor.Expires = expirationDate;+ }++ if (encodeParameters.HasAudience)+ {+ tokenDescriptor.Audience = string.Join(',', tokenParameters.ValidAudiences);+ }++ if (encodeParameters.HasIssuer)+ {+ tokenDescriptor.Issuer = string.Join(',', tokenParameters.ValidIssuers);+ tokenDescriptor.IssuedAt = DateTime.UtcNow;+ }++ var handler = new JwtSecurityTokenHandler+ {+ SetDefaultTimesOnTokenCreation = false+ };++ if (encodeParameters.HasDefaultTime)+ {+ handler.SetDefaultTimesOnTokenCreation = true;+ tokenDescriptor.Expires = DateTime.UtcNow.AddHours(1);+ }++ SecurityToken? token = handler.CreateToken(tokenDescriptor);+ tokenResult.Token = handler.WriteToken(token);+ tokenResult.Payload = tokenParameters.Payload;+ }+ catch (Exception exception)+ {+ RaiseError(exception.Message);+ return null;+ }++ return tokenResult;+ }++ private SigningCredentials GetSigningCredentials(TokenParameters tokenParameters)+ {+ SigningCredentials? signingCredentials = tokenParameters.TokenAlgorithm switch+ {+ JwtAlgorithm.ES512 => new SigningCredentials(GetECDsaSigningKey(tokenParameters), SecurityAlgorithms.EcdsaSha512Signature),+ JwtAlgorithm.ES384 => new SigningCredentials(GetECDsaSigningKey(tokenParameters), SecurityAlgorithms.EcdsaSha384Signature),+ JwtAlgorithm.ES256 => new SigningCredentials(GetECDsaSigningKey(tokenParameters), SecurityAlgorithms.EcdsaSha256Signature),+ JwtAlgorithm.PS512 => new SigningCredentials(GetRsaShaSigningKey(tokenParameters), SecurityAlgorithms.RsaSsaPssSha512),+ JwtAlgorithm.PS384 => new SigningCredentials(GetRsaShaSigningKey(tokenParameters), SecurityAlgorithms.RsaSsaPssSha384),+ JwtAlgorithm.PS256 => new SigningCredentials(GetRsaShaSigningKey(tokenParameters), SecurityAlgorithms.RsaSsaPssSha256),+ JwtAlgorithm.RS512 => new SigningCredentials(GetRsaShaSigningKey(tokenParameters), SecurityAlgorithms.RsaSha512Signature),+ JwtAlgorithm.RS384 => new SigningCredentials(GetRsaShaSigningKey(tokenParameters), SecurityAlgorithms.RsaSha384Signature),+ JwtAlgorithm.RS256 => new SigningCredentials(GetRsaShaSigningKey(tokenParameters), SecurityAlgorithms.RsaSha256Signature),+ JwtAlgorithm.HS512 => new SigningCredentials(GetHmacShaSigningKey(tokenParameters), SecurityAlgorithms.HmacSha512Signature),+ JwtAlgorithm.HS384 => new SigningCredentials(GetHmacShaSigningKey(tokenParameters), SecurityAlgorithms.HmacSha384Signature),+ _ => new SigningCredentials(GetHmacShaSigningKey(tokenParameters), SecurityAlgorithms.HmacSha256Signature),// HS256+ };++ return signingCredentials;+ }++ private SymmetricSecurityKey? GetHmacShaSigningKey(TokenParameters tokenParameters)+ {+ if (string.IsNullOrWhiteSpace(tokenParameters.Signature))+ {+ throw new InvalidOperationException(_localizedStrings.InvalidSignatureError);+ }++ byte[]? signatureByte;+ if (Base64Helper.IsBase64DataStrict(tokenParameters.Signature))+ {+ signatureByte = Convert.FromBase64String(tokenParameters.Signature);+ }+ else+ {+ signatureByte = Encoding.UTF8.GetBytes(tokenParameters.Signature);+ }+ byte[] byteKey = tokenParameters.TokenAlgorithm switch+ {+ JwtAlgorithm.HS512 => new HMACSHA512(signatureByte).Key,+ JwtAlgorithm.HS384 => new HMACSHA384(signatureByte).Key,+ _ => new HMACSHA256(signatureByte).Key,// HS256+ };+ return new SymmetricSecurityKey(byteKey);+ }++ private RsaSecurityKey? GetRsaShaSigningKey(TokenParameters tokenParameters)+ {+ AsymmetricKeyParameter asymmetricKeyParameter = GetPrivateAsymmetricKeyParameter(tokenParameters);++ var rsaPrivateKeyParameters = (RsaPrivateCrtKeyParameters)asymmetricKeyParameter;+ if (!rsaPrivateKeyParameters.IsPrivate)+ {+ throw new InvalidOperationException(_localizedStrings.InvalidPrivateKeyError);+ }++ RSAParameters rsaParameters = new();+ rsaParameters.Modulus = rsaPrivateKeyParameters.Modulus.ToByteArrayUnsigned();+ rsaParameters.Exponent = rsaPrivateKeyParameters.PublicExponent.ToByteArrayUnsigned();+ rsaParameters.P = rsaPrivateKeyParameters.P.ToByteArrayUnsigned();+ rsaParameters.Q = rsaPrivateKeyParameters.Q.ToByteArrayUnsigned();+ rsaParameters.D = ConvertRSAParametersField(rsaPrivateKeyParameters.Exponent, rsaParameters.Modulus.Length);+ rsaParameters.DP = ConvertRSAParametersField(rsaPrivateKeyParameters.DP, rsaParameters.P.Length);+ rsaParameters.DQ = ConvertRSAParametersField(rsaPrivateKeyParameters.DQ, rsaParameters.Q.Length);+ rsaParameters.InverseQ = ConvertRSAParametersField(rsaPrivateKeyParameters.QInv, rsaParameters.Q.Length);++ return new RsaSecurityKey(rsaParameters);+ }++ private ECDsaSecurityKey? GetECDsaSigningKey(TokenParameters tokenParameters)+ {+ AsymmetricKeyParameter? asymmetricKeyParameter = GetPrivateAsymmetricKeyParameter(tokenParameters);+ var ecPrivateKeyParameters = (ECPrivateKeyParameters)asymmetricKeyParameter!;+ if (!ecPrivateKeyParameters.IsPrivate)+ {+ throw new InvalidOperationException(_localizedStrings.InvalidPrivateKeyError);+ }++ ECPoint ecPoint = new()+ {+ X = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded(),+ Y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded()+ };+ ECParameters ecParameters = new()+ {+ Curve = ECCurve.NamedCurves.nistP256,+ Q = ecPoint,+ D = ecPrivateKeyParameters.D.ToByteArrayUnsigned()+ };++ var ecdSa = ECDsa.Create(ecParameters);+ return new ECDsaSecurityKey(ecdSa);+ }++ private AsymmetricKeyParameter GetPrivateAsymmetricKeyParameter(TokenParameters tokenParameters)+ {+ if (string.IsNullOrWhiteSpace(tokenParameters.PrivateKey))+ {+ throw new InvalidOperationException(_localizedStrings.InvalidPrivateKeyError);+ }+ var privateKeyStringBuilder = new StringBuilder(tokenParameters.PrivateKey!.Trim());+ if (!tokenParameters.PrivateKey!.StartsWith(PrivateKeyStart, StringComparison.OrdinalIgnoreCase))+ {+ privateKeyStringBuilder.Insert(0, PrivateKeyStart);+ }+ if (!tokenParameters.PrivateKey.EndsWith(PrivateKeyEnd, StringComparison.OrdinalIgnoreCase))+ {+ privateKeyStringBuilder.Append(PrivateKeyEnd);+ }++ var pemReader = new PemReader(new StringReader(privateKeyStringBuilder.ToString()));+ object? pemObject = pemReader.ReadObject();+ if (pemObject is null)+ {+ throw new InvalidOperationException(_localizedStrings.InvalidPrivateKeyError);+ }++ if (pemObject is AsymmetricKeyParameter parameter)+ {+ return parameter;+ }+ else if (pemObject is AsymmetricCipherKeyPair)+ {+ var pair = pemObject as AsymmetricCipherKeyPair;+ return pair!.Private;+ }++ throw new InvalidOperationException(_localizedStrings.InvalidPrivateKeyError);+ }++ /// <summary>+ /// Source (https://stackoverflow.com/questions/28370414/import-rsa-key-from-bouncycastle-sometimes-throws-bad-data)+ /// </summary>+ private static byte[] ConvertRSAParametersField(BigInteger n, int size)+ {+ byte[] bs = n.ToByteArrayUnsigned();+ if (bs.Length == size)+ {+ return bs;+ }+ if (bs.Length > size)+ {+ throw new ArgumentException("Specified size too small", "size");+ }+ byte[] padded = new byte[size];+ Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);+ return padded;+ }++ private void RaiseError(string message)+ {+ var eventArg = new TokenResultErrorEventArgs+ {+ Message = message,+ Severity = InfoBarSeverity.Error+ };+ _encodingErrorCallBack!.Invoke(eventArg);+ }+ }+}diff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoderControlViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoderControlViewModel.csnew file mode 100644index 000000000..5343a1b3b--- /dev/null+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoderControlViewModel.cs@@ -0,0 +1,236 @@+#nullable enable++using System;+using System.Collections.Generic;+using System.Composition;+using System.Linq;+using DevToys.Api.Core;+using DevToys.Api.Core.Settings;+using DevToys.Api.Tools;+using DevToys.Core.Threading;+using DevToys.Models;+using DevToys.Models.JwtDecoderEncoder;+using DevToys.Shared.Core.Threading;+using DevToys.Views.Tools.EncodersDecoders.JwtDecoderEncoder;+using Microsoft.Toolkit.Mvvm.Messaging;++namespace DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder+{+ [Export(typeof(JwtEncoderControlViewModel))]+ public sealed class JwtEncoderControlViewModel : JwtDecoderEncoderViewModelBase, IToolViewModel, IRecipient<JwtJobAddedMessage>+ {+ private string? _token;+ private bool _hasError;++ private readonly JwtEncoder _encoder;++ internal override string? Token+ {+ get => _token;+ set+ {+ if (_token != value)+ {+ SetProperty(ref _token, value?.Trim());+ }+ }+ }++ internal bool HasExpiration+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.HasExpiration);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.HasExpiration, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal bool HasAudience+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.HasAudience);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.HasAudience, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal bool HasIssuer+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.HasIssuer);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.HasIssuer, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal bool HasDefaultTime+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.HasDefaultTime);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.HasDefaultTime, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal bool HasError+ {+ get => _hasError;+ set+ {+ SetProperty(ref _hasError, value);+ }+ }++ internal int ExpireYear+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ExpireYear);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ExpireYear, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal int ExpireMonth+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ExpireMonth);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ExpireMonth, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal int ExpireDay+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ExpireDay);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ExpireDay, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }++ }++ internal int ExpireHour+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ExpireHour);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ExpireHour, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ internal int ExpireMinute+ {+ get => SettingsProvider.GetSetting(JwtDecoderEncoderSettings.ExpireMinute);+ set+ {+ SettingsProvider.SetSetting(JwtDecoderEncoderSettings.ExpireMinute, value);+ OnPropertyChanged();+ QueueNewTokenJob();+ }+ }++ public Type View { get; } = typeof(JwtEncoderControl);++ [ImportingConstructor]+ public JwtEncoderControlViewModel(+ ISettingsProvider settingsProvider,+ IMarketingService marketingService,+ JwtEncoder encoder)+ : base(settingsProvider, marketingService)+ {+ IsActive = true;+ _encoder = encoder;+ }++ public void Receive(JwtJobAddedMessage message)+ {+ if (string.IsNullOrWhiteSpace(Payload))+ {+ return;+ }++ EncoderParameters encoderParameters = new()+ {+ HasAudience = HasAudience,+ HasExpiration = HasExpiration,+ HasIssuer = HasIssuer,+ HasDefaultTime = HasDefaultTime+ };++ TokenParameters tokenParameters = new()+ {+ TokenAlgorithm = AlgorithmMode.Value,+ Payload = Payload,+ ExpirationYear = ExpireYear,+ ExpirationMonth = ExpireMonth,+ ExpirationDay = ExpireDay,+ ExpirationHour = ExpireHour,+ ExpirationMinute = ExpireMinute+ };++ if (!string.IsNullOrEmpty(ValidIssuers))+ {+ tokenParameters.ValidIssuers = ValidIssuers!.Split(',').ToHashSet();+ }++ if (!string.IsNullOrEmpty(ValidAudiences))+ {+ tokenParameters.ValidAudiences = ValidAudiences!.Split(',').ToHashSet();+ }++ if (AlgorithmMode.Value is JwtAlgorithm.HS256 ||+ AlgorithmMode.Value is JwtAlgorithm.HS384 ||+ AlgorithmMode.Value is JwtAlgorithm.HS512)+ {+ tokenParameters.Signature = Signature;+ }+ else+ {+ tokenParameters.PrivateKey = PrivateKey;+ }++ TokenResult? result = _encoder.GenerateToken(encoderParameters, tokenParameters, TokenErrorCallBack);++ ThreadHelper.RunOnUIThreadAsync(ThreadPriority.Low, () =>+ {+ if (result is not null)+ {+ Token = result.Token;+ }+ HasError = JwtValidation.IsValid!;+ if (ToolSuccessfullyWorked)+ {+ ToolSuccessfullyWorked = true;+ MarketingService.NotifyToolSuccessfullyWorked();+ }+ }).ForgetSafely();+ }++ private void TokenErrorCallBack(TokenResultErrorEventArgs e)+ {+ JwtValidation.IsValid = false;+ JwtValidation.ErrorMessage = e.Message;+ ThreadHelper.RunOnUIThreadAsync(ThreadPriority.Low, () =>+ {+ Token = string.Empty;+ DisplayValidationInfoBar();+ }).ForgetSafely();+ }+ }+}diff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtJobAddedMessage.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtJobAddedMessage.csnew file mode 100644index 000000000..9b593cef7--- /dev/null+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtJobAddedMessage.cs@@ -0,0 +1,8 @@+#nullable enable++namespace DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder+{+ public sealed class JwtJobAddedMessage+ {+ }+}diff --git a/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtPayloadConverter.cs b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtPayloadConverter.csnew file mode 100644index 000000000..ac8670bcb--- /dev/null+++ b/src/dev/impl/DevToys/ViewModels/Tools/EncodersDecoders/JwtDecoderEncoder/JwtPayloadConverter.cs@@ -0,0 +1,103 @@+#nullable enable++using System;+using System.Collections.Generic;+using System.Dynamic;+using System.Text.Json;+using System.Text.Json.Serialization;++namespace DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder+{+ internal class JwtPayloadConverter : JsonConverter<Dictionary<string, object>>+ {+ public override Dictionary<string, object>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)+ {+ if (reader.TokenType != JsonTokenType.StartObject)+ {+ throw new JsonException();+ }++ var dictionary = new Dictionary<string, object>();++ while (reader.Read())+ {+ if (reader.TokenType == JsonTokenType.EndObject)+ {+ return dictionary;+ }++ if (reader.TokenType != JsonTokenType.PropertyName)+ {+ throw new JsonException();+ }++ string? propertyName = reader.GetString();+ reader.Read();+ object? value = GetValue(ref reader);++ if (!string.IsNullOrWhiteSpace(propertyName) && value is not null)+ {+ dictionary.Add(propertyName!, value);+ }+ }++ throw new JsonException();+ }++ public override void Write(Utf8JsonWriter writer, Dictionary<string, object> value, JsonSerializerOptions options)+ {+ throw new NotImplementedException();+ }++ private object? GetValue(ref Utf8JsonReader reader)+ {+ switch (reader.TokenType)+ {+ case JsonTokenType.String:+ return reader.GetString();+ case JsonTokenType.False:+ return false;+ case JsonTokenType.True:+ return true;+ case JsonTokenType.Null:+ return null;+ case JsonTokenType.Number:+ if (reader.TryGetInt64(out long _long))+ {+ return _long;+ }+ else if (reader.TryGetDecimal(out decimal _dec))+ {+ return _dec;+ }+ throw new JsonException($"Unhandled Number value");+ case JsonTokenType.StartArray:+ List<object?> array = new();+ while (reader.Read() &&+ reader.TokenType != JsonTokenType.EndArray)+ {+ array.Add(GetValue(ref reader));+ }+ return array.ToArray();+ case JsonTokenType.StartObject:+ var result = new ExpandoObject();+ while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)+ {+ string? propertyName = null;+ if (reader.TokenType is JsonTokenType.PropertyName)+ {+ propertyName = reader.GetString();+ }+ reader.Read();+ if (!string.IsNullOrEmpty(propertyName))+ {+ result.TryAdd(propertyName, GetValue(ref reader));+ }+ }+ return result;+ default:+ return JsonDocument.ParseValue(ref reader).RootElement.Clone();+ }+ }+ }+}diff --git a/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderControl.xaml b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderControl.xamlnew file mode 100644index 000000000..8c8a1a7e5--- /dev/null+++ b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderControl.xaml@@ -0,0 +1,202 @@+<UserControl+ x:Class="DevToys.Views.Tools.EncodersDecoders.JwtDecoderEncoder.JwtDecoderControl"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:DevToys.Views.Tools.EncodersDecoders.JwtDecoderEncoder"+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"+ xmlns:muxc="using:Microsoft.UI.Xaml.Controls"+ xmlns:toolkit="using:Microsoft.Toolkit.Uwp.UI.Controls"+ xmlns:DevToys="using:DevToys"+ xmlns:controls="using:DevToys.UI.Controls"+ xmlns:converters="using:DevToys.UI.Converters">++ <UserControl.Resources>+ <converters:NullToBooleanConverter x:Name="NullToVisible" IsInverted="True"/>+ <converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>+ <converters:BooleanToVisibilityConverter x:Key="InvertedBooleanToVisibilityConverter" IsInverted="True"/>+ <DevToys:LanguageManager x:Key="LanguageManager"/>+ <Style x:Key="GridSettingBlockStyle" TargetType="Grid">+ <Setter Property="BorderBrush" Value="{ThemeResource ExpanderHeaderBorderBrush}" />+ <Setter Property="BorderThickness" Value="{ThemeResource ExpanderHeaderBorderThickness}" />+ <Setter Property="HorizontalAlignment" Value="Stretch" />+ <Setter Property="MinHeight" Value="{StaticResource ExpanderMinHeight}" />+ <Setter Property="Padding" Value="{StaticResource ExpanderContentPadding}" />+ </Style>+ </UserControl.Resources>++ <Grid x:Name="JwtDecoderGrid" Margin="0,0,0,16" RowSpacing="12">+ <Grid.ChildrenTransitions>+ <TransitionCollection>+ <EntranceThemeTransition IsStaggeringEnabled="True" FromVerticalOffset="50"/>+ </TransitionCollection>+ </Grid.ChildrenTransitions>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" MinWidth="100"/>+ <ColumnDefinition Width="16"/>+ <ColumnDefinition Width="*"/>+ </Grid.ColumnDefinitions>+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto"/>+ <RowDefinition Height="Auto"/>+ <RowDefinition Height="Auto" MinHeight="100"/>+ <RowDefinition Height="Auto" MinHeight="300"/>+ <RowDefinition Height="Auto"/>+ </Grid.RowDefinitions>+ <StackPanel+ x:Name="SettingsStackPanel"+ Grid.Row="0"+ Grid.Column="0"+ Grid.ColumnSpan="3"+ Spacing="4">+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.DecodeValidateTokenLabel}"+ VerticalAlignment="Stretch"+ VerticalContentAlignment="Stretch">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch+ Style="{StaticResource RightAlignedToggleSwitchStyle}"+ OffContent="{x:Bind ViewModel.LocalizedStrings.DecodeValidateTokenNoLabel}" OnContent="{x:Bind ViewModel.LocalizedStrings.DecodeValidateTokenYesLabel}"+ IsOn="{x:Bind ViewModel.ValidateSignature, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ </controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.DecodeValidationSettingsTitle}"+ Description="{x:Bind ViewModel.LocalizedStrings.DecodeValidationSettingsDescription}"+ VerticalAlignment="Stretch"+ VerticalContentAlignment="Stretch"+ Visibility="{x:Bind ViewModel.ShowValidation, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}" >+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="Š" />+ </controls:ExpandableSettingControl.Icon>+ <controls:ExpandableSettingControl.ExpandableContent>+ <StackPanel Padding="6" Spacing="4" HorizontalAlignment="Stretch">+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.DecodeValidateIssuerLabel}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch+ Style="{StaticResource RightAlignedToggleSwitchStyle}"+ IsOn="{x:Bind ViewModel.ValidateIssuer, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ <controls:ExpandableSettingControl.ExpandableContent>+ <StackPanel Padding="12" Spacing="4" HorizontalAlignment="Stretch">+ <controls:CustomTextBox+ Header="{x:Bind ViewModel.LocalizedStrings.ValidIssuersLabel}"+ Text="{x:Bind ViewModel.ValidIssuers, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ LostFocus="{x:Bind ViewModel.InputFocusChanged}" />+ </StackPanel>+ </controls:ExpandableSettingControl.ExpandableContent>+ </controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.DecodeValidateAudienceLabel}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch+ Style="{StaticResource RightAlignedToggleSwitchStyle}"+ IsOn="{x:Bind ViewModel.ValidateAudience, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ <controls:ExpandableSettingControl.ExpandableContent>+ <StackPanel Padding="12" Spacing="4" HorizontalAlignment="Stretch">+ <controls:CustomTextBox+ Header="{x:Bind ViewModel.LocalizedStrings.ValidAudiencesLabel}"+ Text="{x:Bind ViewModel.ValidAudiences, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ LostFocus="{x:Bind ViewModel.InputFocusChanged}" />+ </StackPanel>+ </controls:ExpandableSettingControl.ExpandableContent>+ </controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.DecodeValidateLifetimeLabel}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch+ Style="{StaticResource RightAlignedToggleSwitchStyle}"+ IsOn="{x:Bind ViewModel.ValidateLifetime, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ </controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.DecodeValidateActorLabel}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch+ Style="{StaticResource RightAlignedToggleSwitchStyle}"+ IsOn="{x:Bind ViewModel.ValidateActor, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ </controls:ExpandableSettingControl>+ </StackPanel>+ </controls:ExpandableSettingControl.ExpandableContent>+ </controls:ExpandableSettingControl>+ </StackPanel>+ <muxc:InfoBar+ Grid.Row="1"+ Grid.Column="0"+ Grid.ColumnSpan="3"+ Severity="{Binding Severity}"+ Message="{Binding Message, Mode=OneWay}"+ IsOpen="{Binding Mode=OneWay, Converter={StaticResource NullToVisible}}"+ DataContext="{x:Bind ViewModel.ValidationResult, Mode=OneWay}"+ Visibility="{x:Bind ViewModel.ShowValidation, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}"+ IsClosable="False"/>+ <controls:CodeEditor+ x:Name="TokenCodeEditor"+ Grid.Row="2"+ Grid.Column="0"+ Grid.ColumnSpan="3"+ Header="{x:Bind ViewModel.LocalizedStrings.JwtTokenLabel}"+ Text="{x:Bind ViewModel.Token, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ CodeLanguage="text"+ IsReadOnly="False" />+ <controls:CodeEditor+ x:Name="HeaderCodeEditor"+ Grid.Row="3"+ Grid.Column="0"+ Header="{x:Bind ViewModel.LocalizedStrings.JwtHeaderLabel}"+ Text="{x:Bind ViewModel.Header, Mode=OneWay}"+ CodeLanguage="json"+ IsReadOnly="True"/>+ <toolkit:GridSplitter+ x:Name="verticalGridSplitter"+ Grid.Row="3"+ Grid.Column="1"+ ResizeBehavior="BasedOnAlignment"+ ResizeDirection="Columns">+ <toolkit:GridSplitter.Element>+ <FontIcon+ Glyph="ﵕ"+ FontSize="13"/>+ </toolkit:GridSplitter.Element>+ </toolkit:GridSplitter>+ <controls:CodeEditor+ x:Name="PayloadCodeEditor"+ Grid.Row="3"+ Grid.Column="2"+ MinHeight="150"+ Header="{x:Bind ViewModel.LocalizedStrings.JwtPayloadLabel}"+ Text="{x:Bind ViewModel.Payload, Mode=OneWay}"+ CodeLanguage="json"+ IsReadOnly="True"/>+ <Grid+ x:Name="SignatureGrid"+ Grid.Row="4"+ Grid.Column="0"+ Grid.ColumnSpan="3"+ RowSpacing="0"+ Visibility="{x:Bind ViewModel.ShowValidation, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}">+ <controls:CustomTextBox+ Header="{x:Bind ViewModel.LocalizedStrings.SignatureLabel}"+ Grid.Row="0"+ MinHeight="150"+ AcceptsReturn="True"+ Text="{x:Bind ViewModel.Signature, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ Visibility="{x:Bind ViewModel.RequireSignature, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}" />+ <controls:CustomTextBox+ Header="{x:Bind ViewModel.LocalizedStrings.PublicKeyLabel}"+ Grid.Row="0"+ MinHeight="150"+ AcceptsReturn="True"+ Text="{x:Bind ViewModel.PublicKey, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ Visibility="{x:Bind ViewModel.RequireSignature, Mode=OneWay, Converter={StaticResource InvertedBooleanToVisibilityConverter}}" />+ </Grid>+ </Grid>+</UserControl>diff --git a/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderControl.xaml.cs b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderControl.xaml.csnew file mode 100644index 000000000..120862703--- /dev/null+++ b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderControl.xaml.cs@@ -0,0 +1,33 @@+#nullable enable++using System.Composition;+using DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder;+using Windows.UI.Xaml;+using Windows.UI.Xaml.Controls;++namespace DevToys.Views.Tools.EncodersDecoders.JwtDecoderEncoder+{+ public sealed partial class JwtDecoderControl : UserControl+ {+ public static readonly DependencyProperty ViewModelProperty+ = DependencyProperty.Register(+ nameof(ViewModel),+ typeof(JwtDecoderControlViewModel),+ typeof(JwtDecoderControl),+ new PropertyMetadata(default(JwtDecoderControlViewModel)));++ /// <summary>+ /// Gets the page's view model.+ /// </summary>+ public JwtDecoderControlViewModel ViewModel+ {+ get => (JwtDecoderControlViewModel)GetValue(ViewModelProperty);+ set => SetValue(ViewModelProperty, value);+ }++ public JwtDecoderControl()+ {+ InitializeComponent();+ }+ }+}diff --git a/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolPage.xaml b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolPage.xamlindex 37b76b403..7d7e3671a 100644--- a/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolPage.xaml+++ b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolPage.xaml@@ -5,10 +5,16 @@xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:controls="using:DevToys.UI.Controls"- xmlns:toolkit="using:Microsoft.Toolkit.Uwp.UI.Controls"+ xmlns:converters="using:DevToys.UI.Converters"+ xmlns:jwt="using:DevToys.Views.Tools.EncodersDecoders.JwtDecoderEncoder"mc:Ignorable="d"NavigationCacheMode="Required">+ <Page.Resources>+ <converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>+ <converters:BooleanToVisibilityConverter x:Key="InvertedBooleanToVisibilityConverter" IsInverted="True"/>+ </Page.Resources>+<Grid Margin="0,0,0,16" RowSpacing="12"><Grid.ChildrenTransitions><TransitionCollection>@@ -18,46 +24,23 @@<Grid.RowDefinitions><RowDefinition Height="Auto"/>- <RowDefinition MinHeight="200"/>- <RowDefinition Height="16" />- <RowDefinition MinHeight="200"/>+ <RowDefinition Height="Auto"/></Grid.RowDefinitions>- <controls:CustomTextBox- Margin="0,12,0,0"- Header="{x:Bind ViewModel.Strings.JwtTokenLabel}"- Height="150"- AcceptsReturn="True"- Text="{x:Bind ViewModel.JwtToken, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>-- <controls:CodeEditor- x:Name="HeaderCodeEditor"- Grid.Row="1"- Header="{x:Bind ViewModel.Strings.HeaderLabel}"- Text="{x:Bind ViewModel.JwtHeader, Mode=OneWay}"- CodeLanguage="json"- IsReadOnly="True"/>-- <toolkit:GridSplitter- x:Name="PayloadGridSplitter"- Grid.Row="2"- Height="16"- ResizeBehavior="BasedOnAlignment"- ResizeDirection="Auto">- <toolkit:GridSplitter.Element>- <FontIcon- Glyph="ﵒ"- FontSize="13"/>- </toolkit:GridSplitter.Element>- </toolkit:GridSplitter>-- <controls:CodeEditor- x:Name="PayloadCodeEditor"- Grid.Row="3"- Header="{x:Bind ViewModel.Strings.PayloadLabel}"- Text="{x:Bind ViewModel.JwtPayload, Mode=OneWay}"- CodeLanguage="json"- IsReadOnly="True"/>-+ <StackPanel Spacing="0" Grid.Row="0" Margin="0,0,0,-8" >+ <TextBlock Style="{StaticResource SubTitleTextBlock}" Text="{x:Bind ViewModel.Strings.SettingsTitle}" />+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.Strings.SettingsSwitchModeLabel}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch+ Style="{StaticResource RightAlignedToggleSwitchStyle}"+ OffContent="{x:Bind ViewModel.Strings.DecodeSwitchModeLabel}" OnContent="{x:Bind ViewModel.Strings.EncodeSwitchModeLabel}"+ IsOn="{x:Bind ViewModel.JwtToolMode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ </controls:ExpandableSettingControl>+ </StackPanel>+ <jwt:JwtDecoderControl Grid.Row="1" ViewModel="{x:Bind ViewModel.DecoderViewModel, Mode=OneWay}" Visibility="{x:Bind ViewModel.JwtToolMode, Mode=OneWay, Converter={StaticResource InvertedBooleanToVisibilityConverter}}"/>+ <jwt:JwtEncoderControl Grid.Row="1" ViewModel="{x:Bind ViewModel.EncoderViewModel, Mode=OneWay}" Visibility="{x:Bind ViewModel.JwtToolMode, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}"/></Grid></Page>diff --git a/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolPage.xaml.cs b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolPage.xaml.csindex c3b04f6bd..9cd0de199 100644--- a/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolPage.xaml.cs+++ b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtDecoderEncoderToolPage.xaml.cs@@ -46,7 +46,8 @@ namespace DevToys.Views.Tools.JwtDecoderEncoderif (!string.IsNullOrWhiteSpace(parameters.ClipBoardContent)){- ViewModel.JwtToken = parameters.ClipBoardContent;+ ViewModel.DecoderViewModel.Token = parameters.ClipBoardContent;+ ViewModel.JwtToolMode = false;}base.OnNavigatedTo(e);diff --git a/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoderControl.xaml b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoderControl.xamlnew file mode 100644index 000000000..5cb5f7a71--- /dev/null+++ b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoderControl.xaml@@ -0,0 +1,298 @@+<UserControl+ x:Class="DevToys.Views.Tools.EncodersDecoders.JwtDecoderEncoder.JwtEncoderControl"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="using:DevToys.Views.Tools.EncodersDecoders.JwtDecoderEncoder"+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"+ xmlns:muxc="using:Microsoft.UI.Xaml.Controls"+ xmlns:toolkit="using:Microsoft.Toolkit.Uwp.UI.Controls"+ xmlns:DevToys="using:DevToys"+ xmlns:controls="using:DevToys.UI.Controls"+ xmlns:converters="using:DevToys.UI.Converters"+ >++ <UserControl.Resources>+ <converters:NullToBooleanConverter x:Name="NullToVisible" IsInverted="True"/>+ <converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>+ <converters:BooleanToVisibilityConverter x:Key="InvertedBooleanToVisibilityConverter" IsInverted="True"/>+ <DevToys:LanguageManager x:Key="LanguageManager"/>+ <Style x:Key="GridSettingBlockStyle" TargetType="Grid">+ <Setter Property="BorderBrush" Value="{ThemeResource ExpanderHeaderBorderBrush}" />+ <Setter Property="BorderThickness" Value="{ThemeResource ExpanderHeaderBorderThickness}" />+ <Setter Property="HorizontalAlignment" Value="Stretch" />+ <Setter Property="MinHeight" Value="{StaticResource ExpanderMinHeight}" />+ <Setter Property="Padding" Value="{StaticResource ExpanderContentPadding}" />+ </Style>+ </UserControl.Resources>++ <Grid x:Name="JwtEncoderGrid" Margin="0,0,0,16" RowSpacing="12">+ <Grid.ChildrenTransitions>+ <TransitionCollection>+ <EntranceThemeTransition IsStaggeringEnabled="True" FromVerticalOffset="50"/>+ </TransitionCollection>+ </Grid.ChildrenTransitions>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" MinWidth="100"/>+ <ColumnDefinition Width="16"/>+ <ColumnDefinition Width="*"/>+ </Grid.ColumnDefinitions>+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto"/>+ <RowDefinition Height="Auto" MinHeight="5"/>+ <RowDefinition Height="Auto" MinHeight="100"/>+ <RowDefinition Height="Auto" MinHeight="250"/>+ <RowDefinition Height="Auto" MinHeight="250"/>+ </Grid.RowDefinitions>+ <StackPanel+ x:Name="SettingsStackPanel"+ Grid.Row="0"+ Grid.Column="0"+ Grid.ColumnSpan="3"+ Spacing="4">+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.EncodeSettingsTitle}"+ Description="{x:Bind ViewModel.LocalizedStrings.EncodeSettingsDescription}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="Š" />+ </controls:ExpandableSettingControl.Icon>+ <controls:ExpandableSettingControl.ExpandableContent>+ <StackPanel Padding="6" Spacing="4" HorizontalAlignment="Stretch">+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.EncodeHashingTitle}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="刺" />+ </controls:ExpandableSettingControl.Icon>+ <ComboBox+ ItemsSource="{x:Bind ViewModel.Algorithms}"+ DisplayMemberPath="DisplayName"+ SelectedValue="{x:Bind ViewModel.AlgorithmMode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">+ </ComboBox>+ </controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.EncodeIssuerLabel}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch Style="{StaticResource RightAlignedToggleSwitchStyle}" IsOn="{x:Bind ViewModel.HasIssuer, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ <controls:ExpandableSettingControl.ExpandableContent>+ <StackPanel Padding="12" Spacing="4" HorizontalAlignment="Stretch">+ <controls:CustomTextBox+ Header="{x:Bind ViewModel.LocalizedStrings.ValidIssuersLabel}"+ Text="{x:Bind ViewModel.ValidIssuers, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ LostFocus="{x:Bind ViewModel.InputFocusChanged}" />+ </StackPanel>+ </controls:ExpandableSettingControl.ExpandableContent>+ </controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.EncodeAudienceLabel}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch+ Style="{StaticResource RightAlignedToggleSwitchStyle}"+ IsOn="{x:Bind ViewModel.HasAudience, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ <controls:ExpandableSettingControl.ExpandableContent>+ <StackPanel Padding="12" Spacing="4" HorizontalAlignment="Stretch">+ <controls:CustomTextBox+ Header="{x:Bind ViewModel.LocalizedStrings.ValidAudiencesLabel}"+ Text="{x:Bind ViewModel.ValidAudiences, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ LostFocus="{x:Bind ViewModel.InputFocusChanged}" />+ </StackPanel>+ </controls:ExpandableSettingControl.ExpandableContent>+ </controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.EncodeExpirationTitle}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch+ Style="{StaticResource RightAlignedToggleSwitchStyle}"+ IsOn="{x:Bind ViewModel.HasExpiration, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ <controls:ExpandableSettingControl.ExpandableContent>+ <Grid+ Padding="12"+ ColumnSpacing="8"+ AutomationProperties.LabeledBy="{Binding ElementName=ExpireDateTime}"+ CornerRadius="{x:Bind CornerRadius}" >+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*"/>+ <ColumnDefinition Width="*"/>+ <ColumnDefinition Width="*"/>+ <ColumnDefinition Width="*"/>+ <ColumnDefinition Width="*"/>+ </Grid.ColumnDefinitions>+ <StackPanel Grid.Column="0">+ <TextBlock+ x:Name="ExpireYearHeaderTextBlock"+ Text="{x:Bind ViewModel.LocalizedStrings.EncodeExpirationYearLabel}"+ Margin="{ThemeResource TextBoxTopHeaderMargin}"+ Style="{StaticResource SubTitleTextBlock}"+ TextWrapping="NoWrap"+ TextTrimming="CharacterEllipsis"+ VerticalAlignment="Bottom"/>+ <muxc:NumberBox+ Value="{x:Bind ViewModel.ExpireYear, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ SpinButtonPlacementMode="Compact"+ SmallChange="1"+ LargeChange="10"+ Minimum="1"+ Maximum="9999"+ AutomationProperties.LabeledBy="{Binding ElementName=ExpireYearHeaderTextBlock}"/>+ </StackPanel>+ <StackPanel Grid.Column="1">+ <TextBlock+ x:Name="ExpireMonthHeaderTextBlock"+ Text="{x:Bind ViewModel.LocalizedStrings.EncodeExpirationMonthLabel}"+ Margin="{ThemeResource TextBoxTopHeaderMargin}"+ Style="{StaticResource SubTitleTextBlock}"+ TextWrapping="NoWrap"+ TextTrimming="CharacterEllipsis"+ VerticalAlignment="Bottom"/>+ <muxc:NumberBox+ Value="{x:Bind ViewModel.ExpireMonth, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ SpinButtonPlacementMode="Compact"+ SmallChange="1"+ Minimum="1"+ Maximum="12"+ AutomationProperties.LabeledBy="{Binding ElementName=ExpireMonthHeaderTextBlock}"/>+ </StackPanel>+ <StackPanel Grid.Column="2">+ <TextBlock+ x:Name="ExpireDayHeaderTextBlock"+ Text="{x:Bind ViewModel.LocalizedStrings.EncodeExpirationDaysLabel}"+ Margin="{ThemeResource TextBoxTopHeaderMargin}"+ Style="{StaticResource SubTitleTextBlock}"+ TextWrapping="NoWrap"+ TextTrimming="CharacterEllipsis"+ VerticalAlignment="Bottom"/>+ <muxc:NumberBox+ Value="{x:Bind ViewModel.ExpireDay, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ SpinButtonPlacementMode="Compact"+ SmallChange="1"+ Minimum="1"+ Maximum="31"+ AutomationProperties.LabeledBy="{Binding ElementName=ExpireDayHeaderTextBlock}"/>+ </StackPanel>+ <StackPanel Grid.Column="3">+ <TextBlock+ x:Name="ExpireHourHeaderTextBlock"+ Text="{x:Bind ViewModel.LocalizedStrings.EncodeExpirationHoursLabel}"+ Margin="{ThemeResource TextBoxTopHeaderMargin}"+ Style="{StaticResource SubTitleTextBlock}"+ TextWrapping="NoWrap"+ TextTrimming="CharacterEllipsis"+ VerticalAlignment="Bottom"/>+ <muxc:NumberBox+ Value="{x:Bind ViewModel.ExpireHour, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ SpinButtonPlacementMode="Compact"+ SmallChange="1"+ Minimum="0"+ Maximum="23"+ AutomationProperties.LabeledBy="{Binding ElementName=ExpireHourHeaderTextBlock}"/>+ </StackPanel>+ <StackPanel Grid.Column="4">+ <TextBlock+ x:Name="ExpireMinuteHeaderTextBlock"+ Text="{x:Bind ViewModel.LocalizedStrings.EncodeExpirationMinutesLabel}"+ Margin="{ThemeResource TextBoxTopHeaderMargin}"+ Style="{StaticResource SubTitleTextBlock}"+ TextWrapping="NoWrap"+ TextTrimming="CharacterEllipsis"+ VerticalAlignment="Bottom"/>+ <muxc:NumberBox+ Value="{x:Bind ViewModel.ExpireMinute, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ SpinButtonPlacementMode="Compact"+ SmallChange="1"+ Minimum="0"+ Maximum="59"+ AutomationProperties.LabeledBy="{Binding ElementName=ExpireMinuteHeaderTextBlock}"/>+ </StackPanel>+ </Grid>+ </controls:ExpandableSettingControl.ExpandableContent>+ </controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.LocalizedStrings.EncodeDefaultTimeTitle}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch+ Style="{StaticResource RightAlignedToggleSwitchStyle}"+ IsOn="{x:Bind ViewModel.HasDefaultTime, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ </controls:ExpandableSettingControl>+ </StackPanel>+ </controls:ExpandableSettingControl.ExpandableContent>+ </controls:ExpandableSettingControl>+ </StackPanel>+ <muxc:InfoBar+ Grid.Row="1"+ Margin="0,6,0,0"+ Grid.Column="0"+ Grid.ColumnSpan="3"+ Severity="{Binding Severity}"+ Message="{Binding Message, Mode=OneWay}"+ IsOpen="{Binding Mode=OneWay, Converter={StaticResource NullToVisible}}"+ DataContext="{x:Bind ViewModel.ValidationResult, Mode=OneWay}"+ Visibility="{x:Bind ViewModel.HasError, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}"+ IsClosable="False"/>+ <controls:CustomTextBox+ Grid.Row="2"+ Grid.Column="0"+ Grid.ColumnSpan="3"+ Margin="0,6,0,9"+ Header="{x:Bind ViewModel.LocalizedStrings.JwtTokenLabel}"+ Height="150"+ AcceptsReturn="True"+ IsReadOnly="True"+ Text="{x:Bind ViewModel.Token, Mode=OneWay}"/>+ <controls:CodeEditor+ x:Name="HeaderCodeEditor"+ Grid.Row="3"+ Grid.Column="0"+ Header="{x:Bind ViewModel.LocalizedStrings.JwtHeaderLabel}"+ Text="{x:Bind ViewModel.Header, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ CodeLanguage="json"/>+ <toolkit:GridSplitter+ x:Name="PayloadGridSplitter"+ Grid.Row="3"+ Grid.Column="1"+ ResizeBehavior="BasedOnAlignment"+ ResizeDirection="Columns">+ <toolkit:GridSplitter.Element>+ <FontIcon+ Glyph="ﵕ"+ FontSize="13"/>+ </toolkit:GridSplitter.Element>+ </toolkit:GridSplitter>+ <controls:CodeEditor+ x:Name="PayloadCodeEditor"+ Grid.Row="3"+ Grid.Column="2"+ Header="{x:Bind ViewModel.LocalizedStrings.JwtPayloadLabel}"+ Text="{x:Bind ViewModel.Payload, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ CodeLanguage="json"/>+ <Grid+ x:Name="SignatureGrid"+ Grid.Row="4"+ Grid.Column="0"+ Grid.ColumnSpan="3"+ RowSpacing="0">+ <controls:CustomTextBox+ Margin="0,6,0,9"+ Header="{x:Bind ViewModel.LocalizedStrings.SignatureLabel}"+ Grid.Row="0"+ MinHeight="150"+ AcceptsReturn="True"+ Text="{x:Bind ViewModel.Signature, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ Visibility="{x:Bind ViewModel.RequireSignature, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}" />+ <controls:CustomTextBox+ Margin="0,6,0,9"+ Header="{x:Bind ViewModel.LocalizedStrings.PrivateKeyLabel}"+ Grid.Row="0"+ MinHeight="150"+ AcceptsReturn="True"+ Text="{x:Bind ViewModel.PrivateKey, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ Visibility="{x:Bind ViewModel.RequireSignature, Mode=OneWay, Converter={StaticResource InvertedBooleanToVisibilityConverter}}" />+ </Grid>+ </Grid>+</UserControl>diff --git a/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoderControl.xaml.cs b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoderControl.xaml.csnew file mode 100644index 000000000..9509392eb--- /dev/null+++ b/src/dev/impl/DevToys/Views/Tools/EncodersDecoders/JwtDecoderEncoder/JwtEncoderControl.xaml.cs@@ -0,0 +1,33 @@+#nullable enable++using System.Composition;+using DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder;+using Windows.UI.Xaml;+using Windows.UI.Xaml.Controls;++namespace DevToys.Views.Tools.EncodersDecoders.JwtDecoderEncoder+{+ public sealed partial class JwtEncoderControl : UserControl+ {+ public static readonly DependencyProperty ViewModelProperty+ = DependencyProperty.Register(+ nameof(ViewModel),+ typeof(JwtEncoderControlViewModel),+ typeof(JwtEncoderControl),+ new PropertyMetadata(default(JwtEncoderControlViewModel)));++ /// <summary>+ /// Gets the page's view model.+ /// </summary>+ public JwtEncoderControlViewModel ViewModel+ {+ get => (JwtEncoderControlViewModel)GetValue(ViewModelProperty);+ set => SetValue(ViewModelProperty, value);+ }++ public JwtEncoderControl()+ {+ InitializeComponent();+ }+ }+}diff --git a/src/tests/DevToys.Tests/DevToys.Tests.csproj b/src/tests/DevToys.Tests/DevToys.Tests.csprojindex 6fe459e51..77deb8c53 100644--- a/src/tests/DevToys.Tests/DevToys.Tests.csproj+++ b/src/tests/DevToys.Tests/DevToys.Tests.csproj@@ -44,6 +44,8 @@<SDKReference Include="TestPlatform.Universal, Version=$(UnitTestPlatformVersion)" /></ItemGroup><ItemGroup>+ <Compile Include="Helpers\JwtHelperTests.cs" />+ <Compile Include="Helpers\Base64HelperTests.cs" /><Compile Include="Helpers\XmlHelperTests.cs" /><Compile Include="Providers\Tools\BaseNumberFormatterTests.cs" /><Compile Include="Core\Threading\AsyncLazyTests.cs" />@@ -55,9 +57,12 @@<Compile Include="Properties\AssemblyInfo.cs" /><Compile Include="Providers\Tools\HashGeneratorTests.cs" /><Compile Include="Providers\Tools\Base64EncoderDecoderTests.cs" />+ <Compile Include="Providers\Tools\JwtDecoderEncoderTests.cs" />+ <Compile Include="Providers\Tools\JwtEncoderTests.cs" /><Compile Include="Providers\Tools\SqlFormatterTests.cs" /><Compile Include="Providers\Tools\StringUtilitiesTests.cs" /><Compile Include="Providers\Tools\TestDataProvider.cs" />+ <Compile Include="Providers\Tools\JwtDecoderTests.cs" /><Compile Include="Providers\Tools\XmlValidatorTests.cs" /><Compile Include="UI\ConvertersTests.cs" /><Compile Include="UnitTestApp.xaml.cs">@@ -85,6 +90,21 @@<Content Include="Assets\Square44x44Logo.targetsize-24_altform-unplated.png" /><Content Include="Assets\StoreLogo.png" /><Content Include="Assets\Wide310x150Logo.scale-200.png" />+ <EmbeddedResource Include="Providers\TestData\Jwt\ES\BasicToken.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\ES\ComplexToken.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\ES\PrivateKey.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\ES\PublicKey.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\HS\BasicToken.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\HS\ComplexToken.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\HS\Signature.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\PS\BasicToken.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\PS\ComplexToken.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\PS\PrivateKey.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\PS\PublicKey.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\RS\BasicToken.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\RS\ComplexToken.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\RS\PrivateKey.txt" />+ <EmbeddedResource Include="Providers\TestData\Jwt\RS\PublicKey.txt" /><EmbeddedResource Include="Providers\TestData\InvalidXml.xml" /><EmbeddedResource Include="Providers\TestData\InvalidXsd.xml" /><EmbeddedResource Include="Providers\TestData\ValidXml.xml" />@@ -108,6 +128,15 @@<Name>DevToys.Shared</Name></ProjectReference></ItemGroup>+ <ItemGroup />+ <ItemGroup>+ <EmbeddedResource Include="Providers\TestData\Jwt\BasicPayload.json" />+ <EmbeddedResource Include="Providers\TestData\Jwt\ComplexPayload.json" />+ <EmbeddedResource Include="Providers\TestData\Jwt\ES\Header.json" />+ <EmbeddedResource Include="Providers\TestData\Jwt\HS\Header.json" />+ <EmbeddedResource Include="Providers\TestData\Jwt\PS\Header.json" />+ <EmbeddedResource Include="Providers\TestData\Jwt\RS\Header.json" />+ </ItemGroup><Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" /><!-- To modify your build process, add your task inside one of the targets below and uncomment it.Other similar extension points exist, see Microsoft.Common.targets.diff --git a/src/tests/DevToys.Tests/Helpers/Base64HelperTests.cs b/src/tests/DevToys.Tests/Helpers/Base64HelperTests.csnew file mode 100644index 000000000..2212bd10f--- /dev/null+++ b/src/tests/DevToys.Tests/Helpers/Base64HelperTests.cs@@ -0,0 +1,22 @@+using DevToys.Helpers;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace DevToys.Tests.Helpers+{+ [TestClass]+ public class Base64HelperTests+ {+ [DataTestMethod]+ [DataRow(null, false)]+ [DataRow("", false)]+ [DataRow(" ", false)]+ [DataRow("aGVsbG8gd29ybGQ=", true)]+ [DataRow("aGVsbG8gd2f9ybGQ=", false)]+ [DataRow("SGVsbG8gV29y", true)]+ [DataRow("SGVsbG8gVa29y", false)]+ public void IsValid(string input, bool expectedResult)+ {+ Assert.AreEqual(expectedResult, Base64Helper.IsBase64DataStrict(input));+ }+ }+}diff --git a/src/tests/DevToys.Tests/Helpers/JwtHelperTests.cs b/src/tests/DevToys.Tests/Helpers/JwtHelperTests.csnew file mode 100644index 000000000..02cb5387f--- /dev/null+++ b/src/tests/DevToys.Tests/Helpers/JwtHelperTests.cs@@ -0,0 +1,24 @@+using DevToys.Helpers;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace DevToys.Tests.Helpers+{+ [TestClass]+ public class JwtHelperTests+ {+ [DataTestMethod]+ [DataRow(null, false)]+ [DataRow("", false)]+ [DataRow(" ", false)]+ [DataRow("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", true)]+ [DataRow("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ", false)]+ [DataRow("Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", true)]+ [DataRow("Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ", false)]+ [DataRow("Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", true)]+ [DataRow("Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ", false)]+ public void IsValid(string input, bool expectedResult)+ {+ Assert.AreEqual(expectedResult, JwtHelper.IsValid(input));+ }+ }+}diff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/BasicPayload.json b/src/tests/DevToys.Tests/Providers/TestData/Jwt/BasicPayload.jsonnew file mode 100644index 000000000..f35d3e8f5--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/BasicPayload.json@@ -0,0 +1,22 @@+{+ "sub": "1234567890",+ "name": "John Doe",+ "object": {+ "ObjectProperty": "object value"+ },+ "objectOfObject": {+ "object": {+ "ObjectProperty": "object value"+ }+ },+ "array": [+ "array value"+ ],+ "arrayOfObject": [+ {+ "object": {+ "ObjectProperty": "object value"+ }+ }+ ]+}\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/ComplexPayload.json b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ComplexPayload.jsonnew file mode 100644index 000000000..22a3f5c9e--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ComplexPayload.json@@ -0,0 +1,31 @@+{+ "sub": "1234567890",+ "name": "John Doe",+ "true": true,+ "false": false,+ "long": 1234567890,+ "decimal": 1234567890.123,+ "object": {+ "ObjectProperty": "object value"+ },+ "objectOfObject": {+ "object": {+ "ObjectProperty": "object value"+ }+ },+ "array": [+ "array value"+ ],+ "arrayOfObject": [+ {+ "object": {+ "ObjectProperty": "object value"+ }+ }+ ],+ "nbf": 1661092370,+ "exp": 1661095970,+ "iat": 1661092370,+ "iss": "devtoys",+ "aud": "devtoys"+}\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/BasicToken.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/BasicToken.txtnew file mode 100644index 000000000..12148e7b6--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/BasicToken.txt@@ -0,0 +1 @@+eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn0sIm9iamVjdE9mT2JqZWN0Ijp7Im9iamVjdCI6eyJPYmplY3RQcm9wZXJ0eSI6Im9iamVjdCB2YWx1ZSJ9fSwiYXJyYXkiOlsiYXJyYXkgdmFsdWUiXSwiYXJyYXlPZk9iamVjdCI6W3sib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn19XX0.xplokzMM8A1Xrm8qvrTyuwSEESK2P-ctDhN4ai_EfXxrUsd9YrUJTrSeNRCXd4a8BhfekkKZwKCDXc6eCjsqWQ\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/ComplexToken.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/ComplexToken.txtnew file mode 100644index 000000000..cba03ccb6--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/ComplexToken.txt@@ -0,0 +1 @@+eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwidHJ1ZSI6dHJ1ZSwiZmFsc2UiOmZhbHNlLCJsb25nIjoxMjM0NTY3ODkwLCJkZWNpbWFsIjoxMjM0NTY3ODkwLjEyMywib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn0sIm9iamVjdE9mT2JqZWN0Ijp7Im9iamVjdCI6eyJPYmplY3RQcm9wZXJ0eSI6Im9iamVjdCB2YWx1ZSJ9fSwiYXJyYXkiOlsiYXJyYXkgdmFsdWUiXSwiYXJyYXlPZk9iamVjdCI6W3sib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn19XSwibmJmIjoxNjYxMDkyMzcwLCJleHAiOjE2NjEwOTU5NzAsImlhdCI6MTY2MTA5MjM3MCwiaXNzIjoiZGV2dG95cyIsImF1ZCI6ImRldnRveXMifQ.4i_O8nyOzYVnTKg_7Quv_7Xpn5btY269tM1B-8Ddvv1vw9pUDyeACxcAKivo3zoOth3vlHQLLH-5jK6iPetInQ\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/Header.json b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/Header.jsonnew file mode 100644index 000000000..e7429b83b--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/Header.json@@ -0,0 +1,4 @@+{+ "alg": "ES256",+ "typ": "JWT"+}\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/PrivateKey.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/PrivateKey.txtnew file mode 100644index 000000000..b6c83f1ee--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/PrivateKey.txt@@ -0,0 +1,5 @@+-----BEGIN PRIVATE KEY-----+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgevZzL1gdAFr88hb2+OF/2NxApJCzGCEDdfSp6VQO30hyhRANCAAQRWz+jn65BtOMvdyHKcvjBeBSDZH2r+1RTwjmYSi9R/zpBnuQ4EiMnCqfMPWiZqB4QdbAd0E7oH50VpuZ1P087G+-----END PRIVATE KEY-----\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/PublicKey.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/PublicKey.txtnew file mode 100644index 000000000..0d75c6a73--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/ES/PublicKey.txt@@ -0,0 +1,4 @@+-----BEGIN PUBLIC KEY-----+MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9+q9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==+-----END PUBLIC KEY-----\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/BasicToken.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/BasicToken.txtnew file mode 100644index 000000000..55956392e--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/BasicToken.txt@@ -0,0 +1 @@+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn0sIm9iamVjdE9mT2JqZWN0Ijp7Im9iamVjdCI6eyJPYmplY3RQcm9wZXJ0eSI6Im9iamVjdCB2YWx1ZSJ9fSwiYXJyYXkiOlsiYXJyYXkgdmFsdWUiXSwiYXJyYXlPZk9iamVjdCI6W3sib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn19XX0.0lAff-is2nG80W98QJjVVm3zOzpgpNptKS93XDm4px0\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/ComplexToken.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/ComplexToken.txtnew file mode 100644index 000000000..8b423b37e--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/ComplexToken.txt@@ -0,0 +1 @@+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwidHJ1ZSI6dHJ1ZSwiZmFsc2UiOmZhbHNlLCJsb25nIjoxMjM0NTY3ODkwLCJkZWNpbWFsIjoxMjM0NTY3ODkwLjEyMywib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn0sIm9iamVjdE9mT2JqZWN0Ijp7Im9iamVjdCI6eyJPYmplY3RQcm9wZXJ0eSI6Im9iamVjdCB2YWx1ZSJ9fSwiYXJyYXkiOlsiYXJyYXkgdmFsdWUiXSwiYXJyYXlPZk9iamVjdCI6W3sib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn19XSwibmJmIjoxNjYxMDkyMzcwLCJleHAiOjE2NjEwOTU5NzAsImlhdCI6MTY2MTA5MjM3MCwiaXNzIjoiZGV2dG95cyIsImF1ZCI6ImRldnRveXMifQ.taVhS7pJCx2SPpUE7TVf_A67fHA4Fea4-hHtRkDwoiY\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/Header.json b/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/Header.jsonnew file mode 100644index 000000000..7275522b4--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/Header.json@@ -0,0 +1,4 @@+{+ "alg": "HS256",+ "typ": "JWT"+}\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/Signature.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/Signature.txtnew file mode 100644index 000000000..b60c0e871--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/HS/Signature.txt@@ -0,0 +1 @@+Ym7AD3OT2kpuIRcVAXCweYhV64B0Oi9ETAO6XRbqB8LDL3tF4bMk9x/59PljcGbP5v38BSzCjD1VTwuO6iWA8uzDVAjw2fMNfcT2/LyRlMOsynblo3envlivtgHnKkZj6HqRrG5ltgwy5NsCQ7WwwYPkldhLTF+wUYAnq28+QnU=\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/BasicToken.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/BasicToken.txtnew file mode 100644index 000000000..c7477da83--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/BasicToken.txt@@ -0,0 +1 @@+eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn0sIm9iamVjdE9mT2JqZWN0Ijp7Im9iamVjdCI6eyJPYmplY3RQcm9wZXJ0eSI6Im9iamVjdCB2YWx1ZSJ9fSwiYXJyYXkiOlsiYXJyYXkgdmFsdWUiXSwiYXJyYXlPZk9iamVjdCI6W3sib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn19XX0.IbHGvcrXcI4v7V7gfxzdl5kylAwyBn0bMVwj08CEijNoOLMPHxeizHiaPZ12KrrWwNzA2KqnT58VcoRGPS8MHJ__BMSpsUOAzf61JTed3JPqd_jIcq5BoTEclgjDHinb_De3N5cqmlpEwYip6eUVheqtLe3-GKPbm5i1uPM1ybCZB2wgVaIFdzcfp8H8AO818bzhggspYmGjyXPlIbYf6WYbmhIK8FeZZ7F6S6z2aAjQwLNKFRBiEkWmdZG32OziDN-vnuHLnccS2LBouADalXxZBaLpo-_NtH8SHbTQjcyOmgL4s7m5OngCeksmF2AwO1BUBizsPdnTOhIQ-aLhOw\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/ComplexToken.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/ComplexToken.txtnew file mode 100644index 000000000..67271336a--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/ComplexToken.txt@@ -0,0 +1 @@+eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwidHJ1ZSI6dHJ1ZSwiZmFsc2UiOmZhbHNlLCJsb25nIjoxMjM0NTY3ODkwLCJkZWNpbWFsIjoxMjM0NTY3ODkwLjEyMywib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn0sIm9iamVjdE9mT2JqZWN0Ijp7Im9iamVjdCI6eyJPYmplY3RQcm9wZXJ0eSI6Im9iamVjdCB2YWx1ZSJ9fSwiYXJyYXkiOlsiYXJyYXkgdmFsdWUiXSwiYXJyYXlPZk9iamVjdCI6W3sib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn19XSwibmJmIjoxNjYxMDkyMzcwLCJleHAiOjE2NjEwOTU5NzAsImlhdCI6MTY2MTA5MjM3MCwiaXNzIjoiZGV2dG95cyIsImF1ZCI6ImRldnRveXMifQ.KOM9H46-zkIJ2hAIAt8pieNA-Fod73XFBN6Wg1_WOi3lNJ1Amq-koE4uUiY2Mi_Gs29LnVLKOwQAMa_ZnBIskrXP5yI3UdfZugJ-Y726okTY4-YOJL1ILZKqOMKOZEJMAlWmI79Ll2a1T4drCZVF77tVSIlnslPjAI3KZf9OJUo80UfIWQ4eJNAy97b0SLGLdcXKmsOKpe3bMchrKyLx01JpaAkzg2hAWp7BVjHuWLw1AP47voFJDkpBojaJvJgHrY6j-9AyHpqHXRt4sq_a04PFfC_0NVBnitRVKEbKPj3NpfUcyGrrpYT7uY3mTgxS7l61o6-Bl04xx87NPirKJw\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/Header.json b/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/Header.jsonnew file mode 100644index 000000000..5bce20f8d--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/Header.json@@ -0,0 +1,4 @@+{+ "alg": "PS256",+ "typ": "JWT"+}\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/PrivateKey.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/PrivateKey.txtnew file mode 100644index 000000000..4e3788651--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/PrivateKey.txt@@ -0,0 +1,28 @@+-----BEGIN PRIVATE KEY-----+MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC7VJTUt9Us8cKj+MzEfYyjiWA4R4/M2bS1GB4t7NXp98C3SC6dVMvDuictGeurT8jNbvJZHtCSuYEvu+NMoSfm76oqFvAp8Gy0iz5sxjZmSnXyCdPEovGhLa0VzMaQ8s+CLOyS56YyCFGeJZ+qgtzJ6GR3eqoYSW9b9UMvkBpZODSctWSNGj3P7jRFDO5VoTwCQAWbFnOjDfH5Ulg+p2PKSQnSJP3AJLQNFNe7br1XbrhV//eO+t51mIpGSDCUv3E0DDFcWDTH9cXDTTlR+ZVEiR2BwpZOOkE/Z0/BVnhZYL71oZV34bKfWjQIt6V/isSMahdsAASACp4ZTGtwi+VuNd9tybAgMBAAECggEBAKTmjaS6tkK8BlPXClTQ2vpz/N6uxDeS35mXpqasqskV+laAidgg/sWqpjXDbXr93otIMLlWsM+X0CqMDgSXKejLS2jx4GDjI1ZTXg++0AMJ8+sJ74pWzVDOfmCEQ/7wXs3+cbnXhKriO8Z036q92Qc1+N87SI38nkGa0ABH9CN83H+mQqt4fB7UdHzuIRe/me2PGhIq5ZBzj6h3BpoPGzEP+x3l9YmK8t/1cN0pqI+dQwY+dgfGjackLu/2qH80MCF7IyQaseZUOJyKrCLtSD/Iixv/hzDEUPfOCjFDgTpzf3cw+ta8+oE4wHCo1iI1/4TlPkwmXx4qSXtmw4aQPz7IDQvECgYEA8KNThCO2gsC2I9PQ+DM/8Cw0O983WCDY+oi+7JPiNAJwv5DYBqEZB1QYdj06YD16XlC/HAZMsMku1na2T+N0driwenQQWzoev3g2S7gRDoS/FCJSI3jJ+kjgtaA7Qmzlgk1TxODN+G1H91HW7t+0l7VnL27IWyYo2qRRK3jzxqUiPUCgYEAx0oQs2reBQGMVZnApD1jeq7n4MvNLcPv+t8b/eU9iUv6Y4Mj0Suo/AU8lYZXm8ubbqAlwz2VSVunD2tOplHyMUrtCtObAfVDU+AhCndKaA9gApgfb3xw1IKbuQ1u4IF1FJl3VtumfQn//LiH1B3rXhcdyo3/vIttEk+48RakUKClU8CgYEAzV7W3COOlDDcQd935DdtKBFRAPRPAlspQUnzMi5eSHMD/ISL+DY5IiQHbIH83D4bvXq0X7qQoSBSNP7Dvv3HYuqMhf0DaegrlBuJllFVVq9qPVRnK+xt1Il2HgxOBvbhOT+9in1BzA+YJ99UzC85O0Qz06A+CmtHEy4aZ2kj5hHjECgYEA+mNS4+A8Fkss8Js1RieK2LniBxMgmYml3pfVLKGnzmng7H2+cwPLhPIzIuwytXywh+2bzbsYEfYx3EoEVgMEpPhoarQnYPukrJO4gwE2o5Te6T5mJSZGlQJQj9q4ZB2Dfz+et6INsK0oG8XVGXSpQvQh3RUYekCZQkBBFcpqWpbIEsCgYAnM3DQf3FJoSnXaMhr+VBIovic5l0xFkEHskAjFTevO86Fsz1C2aSeRKSqGFoOQ0tmJzBEs1R6KqnHInicD+TQrKhArgLXX4v3CddjfTRJkFWDbE/CkvKZNOrcf1nhaGCPspRJj2KUkj1Fhl9Cnc+dn/RsYEONbwQSjIfMPkvxF+8HQ==+-----END PRIVATE KEY-----\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/PublicKey.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/PublicKey.txtnew file mode 100644index 000000000..7126789c0--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/PS/PublicKey.txt@@ -0,0 +1,9 @@+-----BEGIN PUBLIC KEY-----+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo+4lgOEePzNm0tRgeLezV6ffAt0gunVTLw7onLRnrq0/IzW7yWR7QkrmBL7jTKEn5u++qKhbwKfBstIs+bMY2Zkp18gnTxKLxoS2tFczGkPLPgizskuemMghRniWaoLcyeh+kd3qqGElvW/VDL5AaWTg0nLVkjRo9z+40RQzuVaE8AkAFmxZzow3x+VJYKdjykkJ+0iT9wCS0DRTXu269V264Vf/3jvredZiKRkgwlL9xNAwxXFg0x/XFw005UWVRIkdg+cKWTjpBP2dPwVZ4WWC+9aGVd+Gyn1o0CLelf4rEjGoXbAAEgAqeGUxrcIlbjXfbc+mwIDAQAB+-----END PUBLIC KEY-----\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/BasicToken.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/BasicToken.txtnew file mode 100644index 000000000..91845b92c--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/BasicToken.txt@@ -0,0 +1 @@+eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn0sIm9iamVjdE9mT2JqZWN0Ijp7Im9iamVjdCI6eyJPYmplY3RQcm9wZXJ0eSI6Im9iamVjdCB2YWx1ZSJ9fSwiYXJyYXkiOlsiYXJyYXkgdmFsdWUiXSwiYXJyYXlPZk9iamVjdCI6W3sib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn19XX0.ueRrFO5OD7JcVPkwAKl03tt_hFI6t4y78oTonb10sYbVXASz40Ll0YHSPSPYA2gGWO-dixbESsw31UIifCyaG2xrEMCfmp8QdzNT7geo53PWwowhR67lfv8ScRAzmyM76cL12B2xkbPOsMN71FNqkV6xhovFK5ThCNqUhKt44-imMw7zWSURlNbEsQYeIdlW2b9ggZ8qh6oRsFST_mZcnOyJX2j8n8UIMVGFIQuYpNuvAJ0q-myBHcy1w8QDShtRCkcijsfXPFe50zYlX4HPFJzwg9DsNf_wbJul81OM7L3LWvIWHukgglUotoNKU_uCJljjp-3bc9KzxCtWYtn-qA\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/ComplexToken.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/ComplexToken.txtnew file mode 100644index 000000000..1aa68942a--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/ComplexToken.txt@@ -0,0 +1 @@+eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwidHJ1ZSI6dHJ1ZSwiZmFsc2UiOmZhbHNlLCJsb25nIjoxMjM0NTY3ODkwLCJkZWNpbWFsIjoxMjM0NTY3ODkwLjEyMywib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn0sIm9iamVjdE9mT2JqZWN0Ijp7Im9iamVjdCI6eyJPYmplY3RQcm9wZXJ0eSI6Im9iamVjdCB2YWx1ZSJ9fSwiYXJyYXkiOlsiYXJyYXkgdmFsdWUiXSwiYXJyYXlPZk9iamVjdCI6W3sib2JqZWN0Ijp7Ik9iamVjdFByb3BlcnR5Ijoib2JqZWN0IHZhbHVlIn19XSwibmJmIjoxNjYxMDkyMzcwLCJleHAiOjE2NjEwOTU5NzAsImlhdCI6MTY2MTA5MjM3MCwiaXNzIjoiZGV2dG95cyIsImF1ZCI6ImRldnRveXMifQ.JudxYaw-Gs9AT8uQQCVFuxLTmgcxbMAWsmVj6VBo-2Q0d7KkwLmyNr325CyGDuo6-zZSOVwyMKFleal6Aea8gdPB81izufag2_cogTYWgzQlNbYlDUUITQqziVvh115XTuFx8rjXAr7YHgDjK5iNhfA-0lnpXkgtYeIvl4ejVJpGA_mOimjxOKSV0pgIDBuW1IufS3clPKCNMX-qVI1WD8_28rUrjP05WWWARfX8TlbMcpIkqA5GiZiis99qt2yfdU9yA-MFQYznpy85f_nd9AW2xsQdaxppAYs5pY63EzWdCIKjCggGZ9W3dkLAVSbTpzf6U3prKsZK5MRFBB-ItA\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/Header.json b/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/Header.jsonnew file mode 100644index 000000000..136c3e7d3--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/Header.json@@ -0,0 +1,4 @@+{+ "alg": "RS256",+ "typ": "JWT"+}\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/PrivateKey.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/PrivateKey.txtnew file mode 100644index 000000000..4e3788651--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/PrivateKey.txt@@ -0,0 +1,28 @@+-----BEGIN PRIVATE KEY-----+MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC7VJTUt9Us8cKj+MzEfYyjiWA4R4/M2bS1GB4t7NXp98C3SC6dVMvDuictGeurT8jNbvJZHtCSuYEvu+NMoSfm76oqFvAp8Gy0iz5sxjZmSnXyCdPEovGhLa0VzMaQ8s+CLOyS56YyCFGeJZ+qgtzJ6GR3eqoYSW9b9UMvkBpZODSctWSNGj3P7jRFDO5VoTwCQAWbFnOjDfH5Ulg+p2PKSQnSJP3AJLQNFNe7br1XbrhV//eO+t51mIpGSDCUv3E0DDFcWDTH9cXDTTlR+ZVEiR2BwpZOOkE/Z0/BVnhZYL71oZV34bKfWjQIt6V/isSMahdsAASACp4ZTGtwi+VuNd9tybAgMBAAECggEBAKTmjaS6tkK8BlPXClTQ2vpz/N6uxDeS35mXpqasqskV+laAidgg/sWqpjXDbXr93otIMLlWsM+X0CqMDgSXKejLS2jx4GDjI1ZTXg++0AMJ8+sJ74pWzVDOfmCEQ/7wXs3+cbnXhKriO8Z036q92Qc1+N87SI38nkGa0ABH9CN83H+mQqt4fB7UdHzuIRe/me2PGhIq5ZBzj6h3BpoPGzEP+x3l9YmK8t/1cN0pqI+dQwY+dgfGjackLu/2qH80MCF7IyQaseZUOJyKrCLtSD/Iixv/hzDEUPfOCjFDgTpzf3cw+ta8+oE4wHCo1iI1/4TlPkwmXx4qSXtmw4aQPz7IDQvECgYEA8KNThCO2gsC2I9PQ+DM/8Cw0O983WCDY+oi+7JPiNAJwv5DYBqEZB1QYdj06YD16XlC/HAZMsMku1na2T+N0driwenQQWzoev3g2S7gRDoS/FCJSI3jJ+kjgtaA7Qmzlgk1TxODN+G1H91HW7t+0l7VnL27IWyYo2qRRK3jzxqUiPUCgYEAx0oQs2reBQGMVZnApD1jeq7n4MvNLcPv+t8b/eU9iUv6Y4Mj0Suo/AU8lYZXm8ubbqAlwz2VSVunD2tOplHyMUrtCtObAfVDU+AhCndKaA9gApgfb3xw1IKbuQ1u4IF1FJl3VtumfQn//LiH1B3rXhcdyo3/vIttEk+48RakUKClU8CgYEAzV7W3COOlDDcQd935DdtKBFRAPRPAlspQUnzMi5eSHMD/ISL+DY5IiQHbIH83D4bvXq0X7qQoSBSNP7Dvv3HYuqMhf0DaegrlBuJllFVVq9qPVRnK+xt1Il2HgxOBvbhOT+9in1BzA+YJ99UzC85O0Qz06A+CmtHEy4aZ2kj5hHjECgYEA+mNS4+A8Fkss8Js1RieK2LniBxMgmYml3pfVLKGnzmng7H2+cwPLhPIzIuwytXywh+2bzbsYEfYx3EoEVgMEpPhoarQnYPukrJO4gwE2o5Te6T5mJSZGlQJQj9q4ZB2Dfz+et6INsK0oG8XVGXSpQvQh3RUYekCZQkBBFcpqWpbIEsCgYAnM3DQf3FJoSnXaMhr+VBIovic5l0xFkEHskAjFTevO86Fsz1C2aSeRKSqGFoOQ0tmJzBEs1R6KqnHInicD+TQrKhArgLXX4v3CddjfTRJkFWDbE/CkvKZNOrcf1nhaGCPspRJj2KUkj1Fhl9Cnc+dn/RsYEONbwQSjIfMPkvxF+8HQ==+-----END PRIVATE KEY-----\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/PublicKey.txt b/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/PublicKey.txtnew file mode 100644index 000000000..7126789c0--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/TestData/Jwt/RS/PublicKey.txt@@ -0,0 +1,9 @@+-----BEGIN PUBLIC KEY-----+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo+4lgOEePzNm0tRgeLezV6ffAt0gunVTLw7onLRnrq0/IzW7yWR7QkrmBL7jTKEn5u++qKhbwKfBstIs+bMY2Zkp18gnTxKLxoS2tFczGkPLPgizskuemMghRniWaoLcyeh+kd3qqGElvW/VDL5AaWTg0nLVkjRo9z+40RQzuVaE8AkAFmxZzow3x+VJYKdjykkJ+0iT9wCS0DRTXu269V264Vf/3jvredZiKRkgwlL9xNAwxXFg0x/XFw005UWVRIkdg+cKWTjpBP2dPwVZ4WWC+9aGVd+Gyn1o0CLelf4rEjGoXbAAEgAqeGUxrcIlbjXfbc+mwIDAQAB+-----END PUBLIC KEY-----\ No newline at end of filediff --git a/src/tests/DevToys.Tests/Providers/Tools/JwtDecoderEncoderTests.cs b/src/tests/DevToys.Tests/Providers/Tools/JwtDecoderEncoderTests.csnew file mode 100644index 000000000..f2ecbb812--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/Tools/JwtDecoderEncoderTests.cs@@ -0,0 +1,434 @@+using System.Collections.Generic;+using System.Linq;+using System.Threading.Tasks;+using DevToys.Api.Tools;+using DevToys.Core.Threading;+using DevToys.Models;+using DevToys.Models.JwtDecoderEncoder;+using DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace DevToys.Tests.Providers.Tools+{+ [TestClass]+ public class JwtDecoderEncoderTests : MefBaseTest+ {+ private static InfoBarData _validationResult;++ [DataTestMethod]+ [DataRow(null, false)]+ [DataRow("", false)]+ [DataRow(" ", false)]+ [DataRow("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", true)]+ [DataRow("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ", false)]+ [DataRow("Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", true)]+ [DataRow("Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ", false)]+ [DataRow("Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", true)]+ [DataRow("Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ", false)]+ public async Task CanBeTreatedByTool(string input, bool expectedResult)+ {+ await ThreadHelper.RunOnUIThreadAsync(() =>+ {+ System.Collections.Generic.IEnumerable<ToolProviderViewItem> result = ExportProvider.Import<IToolProviderFactory>().GetAllTools();+ ToolProviderViewItem jwtTool = result.First(item => item.Metadata.ProtocolName == "jwt");++ Assert.AreEqual(expectedResult, jwtTool.ToolProvider.CanBeTreatedByTool(input));+ });+ }++ #region GenerateAndDecodeHS++ [TestMethod]+ public async Task JwtDecoderEncoder_Generate_And_Decode_Basic_HS_Token_Without_Signature_Validation()+ {+ string signature = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt");+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.HS384,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ Signature = signature+ };+ var jwtEncoder = new JwtEncoder();+ TokenResult result = jwtEncoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);++ // Decode+ string header = await TestDataProvider.GetFileContent("Jwt.HS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters();+ tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.HS384,+ Token = result.Token+ };++ var jwtDecoder = new JwtDecoder();+ result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Payload, payload);+ }++ [TestMethod]+ public async Task JwtDecoderEncoder_Generate_And_Decode_Complex_HS_Token_With_Signature_Validation()+ {+ string signature = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt");+ string header = await TestDataProvider.GetFileContent("Jwt.HS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.ComplexPayload.json");++ var encoderParameters = new EncoderParameters()+ {+ HasAudience = true,+ HasExpiration = true,+ HasIssuer = true,+ HasDefaultTime = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.HS512,+ Payload = payload,+ Signature = signature,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ ExpirationYear = 1,+ ExpirationMonth = 1,+ ExpirationDay = 1,+ ExpirationHour = 0,+ ExpirationMinute = 0+ };++ var jwtEncoder = new JwtEncoder();+ TokenResult result = jwtEncoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);++ // Decode+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateActor = true,+ ValidateIssuer = true,+ ValidateAudience = true+ };+ tokenParameters = new TokenParameters()+ {+ Token = result.Token,+ Signature = signature,+ TokenAlgorithm = JwtAlgorithm.HS512,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ };+ var jwtDecoder = new JwtDecoder();+ result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ }++ #endregion++ #region GenerateRS++ [TestMethod]+ public async Task JwtDecoderEncoder_Generate_And_Decode_Basic_RS_Token_Without_Signature_Validation()+ {+ string header = await TestDataProvider.GetFileContent("Jwt.RS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");++ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS384,+ Payload = payload,+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.RS.PrivateKey.txt")+ };+ var jwtEncoder = new JwtEncoder();+ TokenResult result = jwtEncoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);++ // Decode+ var decodeParameters = new DecoderParameters();+ tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS384,+ Token = result.Token+ };++ var jwtDecoder = new JwtDecoder();+ result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ }++ [TestMethod]+ public async Task JwtDecoderEncoder_Generate_And_Decode_Complex_RS_Token_With_Signature_Validation()+ {+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ string privateKey = await TestDataProvider.GetFileContent("Jwt.RS.PrivateKey.txt");+ var encoderParameters = new EncoderParameters()+ {+ HasAudience = true,+ HasExpiration = true,+ HasIssuer = true,+ HasDefaultTime = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS512,+ Payload = payload,+ PrivateKey = privateKey,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ ExpirationYear = 1,+ ExpirationMonth = 1,+ ExpirationDay = 1,+ ExpirationHour = 0,+ ExpirationMinute = 0+ };++ var jwtEncoder = new JwtEncoder();+ TokenResult result = jwtEncoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);++ // decode+ string publicKey = await TestDataProvider.GetFileContent("Jwt.RS.PublicKey.txt");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateActor = true,+ ValidateIssuer = true,+ ValidateAudience = true+ };+ tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS512,+ Token = result.Token,+ PublicKey = publicKey,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ };+ var jwtDecoder = new JwtDecoder();+ result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ }++ #endregion++ #region GeneratePS++ [TestMethod]+ public async Task JwtDecoderEncoder_Generate_And_Decode_Basic_PS_Token_Without_Signature_Validation()+ {+ string header = await TestDataProvider.GetFileContent("Jwt.PS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");++ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS384,+ Payload = payload,+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.PS.PrivateKey.txt")+ };+ var jwtEncoder = new JwtEncoder();+ TokenResult result = jwtEncoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);++ // Decode+ var decodeParameters = new DecoderParameters();+ tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS384,+ Token = result.Token+ };++ var jwtDecoder = new JwtDecoder();+ result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ }++ [TestMethod]+ public async Task JwtDecoderEncoder_Generate_And_Decode_Complex_PS_Token_With_Signature_Validation()+ {+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ string privateKey = await TestDataProvider.GetFileContent("Jwt.PS.PrivateKey.txt");+ var encoderParameters = new EncoderParameters()+ {+ HasAudience = true,+ HasExpiration = true,+ HasIssuer = true,+ HasDefaultTime = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS512,+ Payload = payload,+ PrivateKey = privateKey,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ ExpirationYear = 1,+ ExpirationMonth = 1,+ ExpirationDay = 1,+ ExpirationHour = 0,+ ExpirationMinute = 0+ };++ var jwtEncoder = new JwtEncoder();+ TokenResult result = jwtEncoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);++ // decode+ string publicKey = await TestDataProvider.GetFileContent("Jwt.RS.PublicKey.txt");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateActor = true,+ ValidateIssuer = true,+ ValidateAudience = true+ };+ tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS512,+ Token = result.Token,+ PublicKey = publicKey,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ };+ var jwtDecoder = new JwtDecoder();+ result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ }++ #endregion++ #region GenerateES++ [TestMethod]+ public async Task JwtDecoderEncoder_Generate_And_Decode_Basic_ES_Token_Without_Signature_Validation()+ {+ string header = await TestDataProvider.GetFileContent("Jwt.ES.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");++ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES384,+ Payload = payload,+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.ES.PrivateKey.txt")+ };+ var jwtEncoder = new JwtEncoder();+ TokenResult result = jwtEncoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);++ // Decode+ var decodeParameters = new DecoderParameters();+ tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES384,+ Token = result.Token+ };++ var jwtDecoder = new JwtDecoder();+ result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ }++ [TestMethod]+ public async Task JwtDecoderEncoder_Generate_And_Decode_Complex_ES_Token_With_Signature_Validation()+ {+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ string privateKey = await TestDataProvider.GetFileContent("Jwt.ES.PrivateKey.txt");+ var encoderParameters = new EncoderParameters()+ {+ HasAudience = true,+ HasExpiration = true,+ HasIssuer = true,+ HasDefaultTime = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES512,+ Payload = payload,+ PrivateKey = privateKey,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ ExpirationYear = 1,+ ExpirationMonth = 1,+ ExpirationDay = 1,+ ExpirationHour = 0,+ ExpirationMinute = 0+ };++ var jwtEncoder = new JwtEncoder();+ TokenResult result = jwtEncoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);++ // decode+ string publicKey = await TestDataProvider.GetFileContent("Jwt.ES.PublicKey.txt");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateActor = true,+ ValidateIssuer = true,+ ValidateAudience = true+ };+ tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES512,+ Token = result.Token,+ PublicKey = publicKey,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ };+ var jwtDecoder = new JwtDecoder();+ result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ }++ #endregion++ internal static void DecodingErrorCallBack(TokenResultErrorEventArgs e)+ => _validationResult = new InfoBarData(e.Severity, e.Message);++ [TestCleanup]+ public void TestCleanup()+ {+ _validationResult = null;+ }+ }+}diff --git a/src/tests/DevToys.Tests/Providers/Tools/JwtDecoderTests.cs b/src/tests/DevToys.Tests/Providers/Tools/JwtDecoderTests.csnew file mode 100644index 000000000..6a07378cc--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/Tools/JwtDecoderTests.cs@@ -0,0 +1,650 @@+using System;+using System.Diagnostics.CodeAnalysis;+using System.Threading.Tasks;+using DevToys.Core.Threading;+using DevToys.Models.JwtDecoderEncoder;+using DevToys.Models;+using DevToys.Shared.Api.Core;+using DevToys.Shared.Core;+using DevToys.ViewModels;+using DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder;+using Microsoft.UI.Xaml.Controls;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Windows.Storage;+using System.Collections.Generic;++namespace DevToys.Tests.Providers.Tools+{+ [TestClass]+ [ExcludeFromCodeCoverage]+ public class JwtDecoderTest+ {+ private static InfoBarData _validationResult;+ private static JwtDecoderEncoderStrings _localizedStrings;++ [TestInitialize]+ public void TestInitialize()+ {+ _localizedStrings = new JwtDecoderEncoderStrings();+ }++ [TestMethod]+ [ExpectedException(typeof(ArgumentNullException))]+ public void JwtDecoder_DecodeToken_With_Null_DecoderParameters_Should_Throw_ArgumentNullException()+ {+ var jwtDecoder = new JwtDecoder();+ jwtDecoder.DecodeToken(null, null, DecodingErrorCallBack);+ }++ [TestMethod]+ [ExpectedException(typeof(ArgumentNullException))]+ public void JwtDecoder_DecodeToken_With_Null_TokenParameters_Should_Throw_ArgumentNullException()+ {+ var jwtDecoder = new JwtDecoder();+ jwtDecoder.DecodeToken(new DecoderParameters(), null, DecodingErrorCallBack);+ }++ [TestMethod]+ [ExpectedException(typeof(ArgumentNullException))]+ public void JwtDecoder_DecodeToken_With_Null_TokenResultErrorEventArgs_Should_Throw_ArgumentNullException()+ {+ var jwtDecoder = new JwtDecoder();+ jwtDecoder.DecodeToken(new DecoderParameters(), new TokenParameters(), null);+ }++ [TestMethod]+ [ExpectedException(typeof(ArgumentNullException))]+ public void JwtDecoder_DecodeToken_With_Null_Token_Should_Throw_ArgumentNullException()+ {+ var decodeParameters = new DecoderParameters();+ var tokenParameters = new TokenParameters()+ {+ Token = null+ };+++ var jwtDecoder = new JwtDecoder();+ jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);+ }++ [TestMethod]+ public void JwtDecoder_DecodeToken_With_Invalid_Token_Should_Fail_With_Error()+ {+ var decodeParameters = new DecoderParameters();+ var tokenParameters = new TokenParameters()+ {+ Token = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ"+ };+++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Severity, InfoBarSeverity.Error);+ Assert.IsNotNull(_validationResult.Message);+ }++ [TestMethod]+ public async Task JwtDecoder_DecodeToken_Valid_Token_With_Signature_Validation_And_Without_Signature_Should_Fail_With_ErrorAsync()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt");+ string signature = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt");+ string header = await TestDataProvider.GetFileContent("Jwt.HS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateAudience = true+ };+ var tokenParameters = new TokenParameters()+ {+ Token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt"),+ };++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Severity, InfoBarSeverity.Error);+ Assert.IsNotNull(_validationResult.Message);+ }++ [TestMethod]+ public async Task JwtDecoder_DecodeToken_Valid_Token_With_Signature_And_Invalid_Issuers_Should_Fail_With_ErrorAsync()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt");+ string signature = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt");+ string header = await TestDataProvider.GetFileContent("Jwt.HS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateIssuer = true+ };+ var tokenParameters = new TokenParameters()+ {+ Token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt"),+ Signature = signature+ };++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Severity, InfoBarSeverity.Error);+ Assert.AreEqual(_validationResult.Message, _localizedStrings.ValidIssuersError);+ }++ [TestMethod]+ public async Task JwtDecoder_DecodeToken_Valid_Token_With_Signature_And_Invalid_Audiences_Should_Fail_With_ErrorAsync()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt");+ string signature = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt");+ string header = await TestDataProvider.GetFileContent("Jwt.HS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateAudience = true+ };+ var tokenParameters = new TokenParameters()+ {+ Token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt"),+ Signature = signature+ };++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Severity, InfoBarSeverity.Error);+ Assert.AreEqual(_validationResult.Message, _localizedStrings.ValidAudiencesError);+ }++ [TestMethod]+ public async Task JwtDecoder_DecodeToken_Valid_Token_With_Signature_And_Invalid_LifeTime_Should_Fail_With_ErrorAsync()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt");+ string signature = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt");+ string header = await TestDataProvider.GetFileContent("Jwt.HS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.ComplexPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateActor = true,+ ValidateIssuer = true,+ ValidateAudience = true,+ ValidateLifetime = true+ };+ var tokenParameters = new TokenParameters()+ {+ Token = await TestDataProvider.GetFileContent("Jwt.HS.ComplexToken.txt"),+ Signature = signature,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ };+ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ }++ [TestMethod]+ public async Task JwtDecoder_DecodeToken_Valid_Token_With_Signature_And_Invalid_PublicKey_Should_Fail_With_ErrorAsync()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.RS.BasicToken.txt");+ string publicKey = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt");+ string header = await TestDataProvider.GetFileContent("Jwt.RS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateActor = true,+ ValidateIssuer = true,+ ValidateAudience = true,+ ValidateLifetime = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS512,+ Token = await TestDataProvider.GetFileContent("Jwt.RS.BasicToken.txt"),+ PublicKey = publicKey,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ };+ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ }++ #region DecodeHS++ [TestMethod]+ public async Task JwtDecoder_Decode_Basic_HS_Token_Without_Signature_Validation()+ {+ string header = await TestDataProvider.GetFileContent("Jwt.HS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.HS256,+ Token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt")+ };+++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Header, header);+ Assert.AreEqual(result.Payload, payload);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Basic_HS_Token_With_Signature_Validation()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt");+ string signature = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.HS256,+ Token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt"),+ Signature = signature+ };+ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Payload, payload);+ Assert.AreEqual(result.Signature, signature);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Complex_HS_Token_Without_Signature_Validation()+ {+ string header = await TestDataProvider.GetFileContent("Jwt.HS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.ComplexPayload.json");+ var decodeParameters = new DecoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.HS512,+ Token = await TestDataProvider.GetFileContent("Jwt.HS.ComplexToken.txt")+ };+++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Header, header);+ Assert.AreEqual(result.Payload, payload);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Complex_HS_Token_With_Signature_Validation()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt");+ string signature = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt");+ string header = await TestDataProvider.GetFileContent("Jwt.HS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.ComplexPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateActor = true,+ ValidateIssuer = true,+ ValidateAudience = true+ };+ var tokenParameters = new TokenParameters()+ {+ Token = await TestDataProvider.GetFileContent("Jwt.HS.ComplexToken.txt"),+ Signature = signature,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ };+ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Header, header);+ Assert.AreEqual(result.Payload, payload);+ Assert.AreEqual(result.Signature, signature);+ }++ #endregion++ #region DecodeRS++ [TestMethod]+ public async Task JwtDecoder_Decode_Basic_RS_Token_Without_Signature_Validation()+ {+ string header = await TestDataProvider.GetFileContent("Jwt.RS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS256,+ Token = await TestDataProvider.GetFileContent("Jwt.RS.BasicToken.txt")+ };+++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Header, header);+ Assert.AreEqual(result.Payload, payload);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Basic_RS_Token_With_Signature_Validation()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.RS.BasicToken.txt");+ string publicKey = await TestDataProvider.GetFileContent("Jwt.RS.PublicKey.txt");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS384,+ Token = await TestDataProvider.GetFileContent("Jwt.RS.BasicToken.txt"),+ PublicKey = publicKey,+ };+ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Payload, payload);+ Assert.AreEqual(result.PublicKey, publicKey);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Complex_RS_Token_Without_Signature_Validation()+ {+ string payload = await TestDataProvider.GetFileContent("Jwt.ComplexPayload.json");+ var decodeParameters = new DecoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS512,+ Token = await TestDataProvider.GetFileContent("Jwt.RS.ComplexToken.txt")+ };+++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Payload, payload);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Complex_RS_Token_With_Signature_Validation()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.RS.BasicToken.txt");+ string publicKey = await TestDataProvider.GetFileContent("Jwt.RS.PublicKey.txt");+ string header = await TestDataProvider.GetFileContent("Jwt.RS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.ComplexPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateActor = true,+ ValidateIssuer = true,+ ValidateAudience = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS384,+ Token = await TestDataProvider.GetFileContent("Jwt.RS.ComplexToken.txt"),+ PublicKey = publicKey,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ };+ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Header, header);+ Assert.AreEqual(result.Payload, payload);+ Assert.AreEqual(result.PublicKey, publicKey);+ }++ #endregion++ #region DecodePS++ [TestMethod]+ public async Task JwtDecoder_Decode_Basic_PS_Token_Without_Signature_Validation()+ {+ string header = await TestDataProvider.GetFileContent("Jwt.PS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS256,+ Token = await TestDataProvider.GetFileContent("Jwt.PS.BasicToken.txt")+ };+++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Header, header);+ Assert.AreEqual(result.Payload, payload);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Basic_PS_Token_With_Signature_Validation()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.PS.BasicToken.txt");+ string publicKey = await TestDataProvider.GetFileContent("Jwt.PS.PublicKey.txt");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS384,+ Token = await TestDataProvider.GetFileContent("Jwt.PS.BasicToken.txt"),+ PublicKey = publicKey,+ };+ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Payload, payload);+ Assert.AreEqual(result.PublicKey, publicKey);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Complex_PS_Token_Without_Signature_Validation()+ {+ string payload = await TestDataProvider.GetFileContent("Jwt.ComplexPayload.json");+ var decodeParameters = new DecoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS512,+ Token = await TestDataProvider.GetFileContent("Jwt.PS.ComplexToken.txt")+ };+++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Payload, payload);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Complex_PS_Token_With_Signature_Validation()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.PS.BasicToken.txt");+ string publicKey = await TestDataProvider.GetFileContent("Jwt.PS.PublicKey.txt");+ string header = await TestDataProvider.GetFileContent("Jwt.PS.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.ComplexPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateActor = true,+ ValidateIssuer = true,+ ValidateAudience = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS384,+ Token = await TestDataProvider.GetFileContent("Jwt.PS.ComplexToken.txt"),+ PublicKey = publicKey,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ };+ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Header, header);+ Assert.AreEqual(result.Payload, payload);+ Assert.AreEqual(result.PublicKey, publicKey);+ }++ #endregion++ #region DecodeES++ [TestMethod]+ public async Task JwtDecoder_Decode_Basic_ES_Token_Without_Signature_Validation()+ {+ string header = await TestDataProvider.GetFileContent("Jwt.ES.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES256,+ Token = await TestDataProvider.GetFileContent("Jwt.ES.BasicToken.txt")+ };+++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Header, header);+ Assert.AreEqual(result.Payload, payload);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Basic_ES_Token_With_Signature_Validation()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.ES.BasicToken.txt");+ string publicKey = await TestDataProvider.GetFileContent("Jwt.ES.PublicKey.txt");+ string payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES256,+ Token = await TestDataProvider.GetFileContent("Jwt.ES.BasicToken.txt"),+ PublicKey = publicKey,+ };+ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Payload, payload);+ Assert.AreEqual(result.PublicKey, publicKey);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Complex_ES_Token_Without_Signature_Validation()+ {+ string payload = await TestDataProvider.GetFileContent("Jwt.ComplexPayload.json");+ var decodeParameters = new DecoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES512,+ Token = await TestDataProvider.GetFileContent("Jwt.ES.ComplexToken.txt")+ };+++ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Payload, payload);+ }++ [TestMethod]+ public async Task JwtDecoder_Decode_Complex_ES_Token_With_Signature_Validation()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.ES.BasicToken.txt");+ string publicKey = await TestDataProvider.GetFileContent("Jwt.ES.PublicKey.txt");+ string header = await TestDataProvider.GetFileContent("Jwt.ES.Header.json");+ string payload = await TestDataProvider.GetFileContent("Jwt.ComplexPayload.json");+ var decodeParameters = new DecoderParameters()+ {+ ValidateSignature = true,+ ValidateActor = true,+ ValidateIssuer = true,+ ValidateAudience = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES384,+ Token = await TestDataProvider.GetFileContent("Jwt.ES.ComplexToken.txt"),+ PublicKey = publicKey,+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ };+ var jwtDecoder = new JwtDecoder();+ TokenResult result = jwtDecoder.DecodeToken(decodeParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.AreEqual(result.Header, header);+ Assert.AreEqual(result.Payload, payload);+ Assert.AreEqual(result.PublicKey, publicKey);+ }++ #endregion++ internal static void DecodingErrorCallBack(TokenResultErrorEventArgs e)+ => _validationResult = new InfoBarData(e.Severity, e.Message);++ [TestCleanup]+ public void TestCleanup()+ {+ _validationResult = null;+ }+ }+}diff --git a/src/tests/DevToys.Tests/Providers/Tools/JwtEncoderTests.cs b/src/tests/DevToys.Tests/Providers/Tools/JwtEncoderTests.csnew file mode 100644index 000000000..4d3df38bc--- /dev/null+++ b/src/tests/DevToys.Tests/Providers/Tools/JwtEncoderTests.cs@@ -0,0 +1,521 @@+using System;+using System.Collections.Generic;+using System.Diagnostics.CodeAnalysis;+using System.Text;+using System.Threading.Tasks;+using DevToys.Models;+using DevToys.Models.JwtDecoderEncoder;+using DevToys.ViewModels.Tools.EncodersDecoders.JwtDecoderEncoder;+using Microsoft.UI.Xaml.Controls;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace DevToys.Tests.Providers.Tools+{+ [TestClass]+ [ExcludeFromCodeCoverage]+ public class JwtEncoderTests+ {+ private static InfoBarData _validationResult;+ private static JwtDecoderEncoderStrings _localizedStrings;++ [TestInitialize]+ public void TestInitialize()+ {+ _localizedStrings = new JwtDecoderEncoderStrings();+ }++ [TestMethod]+ [ExpectedException(typeof(ArgumentNullException))]+ public void JwtEncoder_Generate_With_Null_DecoderParameters_Should_Throw_ArgumentNullException()+ {+ var jwtDecoder = new JwtEncoder();+ jwtDecoder.GenerateToken(null, null, DecodingErrorCallBack);+ }++ [TestMethod]+ [ExpectedException(typeof(ArgumentNullException))]+ public void JwtEncoder_Generate_With_Null_TokenParameters_Should_Throw_ArgumentNullException()+ {+ var jwtDecoder = new JwtEncoder();+ jwtDecoder.GenerateToken(new EncoderParameters(), null, DecodingErrorCallBack);+ }++ [TestMethod]+ [ExpectedException(typeof(ArgumentNullException))]+ public void JwtEncoder_Generate_With_Null_TokenResultErrorEventArgs_Should_Throw_ArgumentNullException()+ {+ var jwtDecoder = new JwtEncoder();+ jwtDecoder.GenerateToken(new EncoderParameters(), new TokenParameters(), null);+ }++ [TestMethod]+ [ExpectedException(typeof(ArgumentNullException))]+ public void JwtEncoder_Generate_With_Null_Payload_Should_Throw_ArgumentNullException()+ {+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ Payload = null+ };+++ var jwtDecoder = new JwtEncoder();+ jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);+ }++ [TestMethod]+ public void JwtEncoder_Generate_With_Invalid_Token_Should_Fail_With_Error()+ {+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ Payload = "xxx"+ };++ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Severity, InfoBarSeverity.Error);+ Assert.IsNotNull(_validationResult.Message);+ }++ #region GenerateHS++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_HS_Token_Without_Signature_Should_Fail()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.HS.BasicToken.txt");+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.HS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Message, _localizedStrings.InvalidSignatureError);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_HS_Token()+ {+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.HS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ Signature = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt")+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_HS_Token_With_Base64_Signature()+ {+ string signature = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt");++ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.HS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ Signature = Convert.ToBase64String(Encoding.UTF8.GetBytes(signature))+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Complex_HS_Token()+ {+ var encoderParameters = new EncoderParameters()+ {+ HasAudience = true,+ HasExpiration = true,+ HasIssuer = true,+ HasDefaultTime = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.HS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ Signature = await TestDataProvider.GetFileContent("Jwt.HS.Signature.txt"),+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ ExpirationYear = 1,+ ExpirationMonth = 1,+ ExpirationDay = 1,+ ExpirationHour = 0,+ ExpirationMinute = 0+ };++ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ #endregion++ #region GenerateRS++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_RS_Token_Without_Signature_Should_Fail()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.RS.BasicToken.txt");+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Message, _localizedStrings.InvalidPrivateKeyError);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_RS_Token()+ {+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.RS.PrivateKey.txt")+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Complex_RS_Token()+ {+ var encoderParameters = new EncoderParameters()+ {+ HasAudience = true,+ HasExpiration = true,+ HasIssuer = true,+ HasDefaultTime = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.RS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.RS.PrivateKey.txt"),+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ ExpirationYear = 1,+ ExpirationMonth = 1,+ ExpirationDay = 1,+ ExpirationHour = 0,+ ExpirationMinute = 0+ };++ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_RS_Token_With_Partial_Private_Key()+ {+ string privateKey = await TestDataProvider.GetFileContent("Jwt.RS.PrivateKey.txt");+ privateKey = privateKey.Remove(0, "-----BEGIN PRIVATE KEY-----".Length).Trim();+ privateKey = privateKey.Remove(privateKey.Length - "-----END PRIVATE KEY-----".Length, "-----END PRIVATE KEY-----".Length).Trim();++ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = privateKey+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_RS_Token_With_Public_Key_Should_Faild()+ {+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.RS.PublicKey.txt")+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Severity, InfoBarSeverity.Error);+ }++ #endregion++ #region GeneratePS++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_PS_Token_Without_Signature_Should_Fail()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.PS.BasicToken.txt");+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Message, _localizedStrings.InvalidPrivateKeyError);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_PS_Token()+ {+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.PS.PrivateKey.txt")+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Complex_PS_Token()+ {+ var encoderParameters = new EncoderParameters()+ {+ HasAudience = true,+ HasExpiration = true,+ HasIssuer = true,+ HasDefaultTime = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.PS.PrivateKey.txt"),+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ ExpirationYear = 1,+ ExpirationMonth = 1,+ ExpirationDay = 1,+ ExpirationHour = 0,+ ExpirationMinute = 0+ };++ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_PS_Token_With_Partial_Private_Key()+ {+ string privateKey = await TestDataProvider.GetFileContent("Jwt.PS.PrivateKey.txt");+ privateKey = privateKey.Remove(0, "-----BEGIN PRIVATE KEY-----".Length).Trim();+ privateKey = privateKey.Remove(privateKey.Length - "-----END PRIVATE KEY-----".Length, "-----END PRIVATE KEY-----".Length).Trim();++ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = privateKey+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_PS_Token_With_Public_Key_Should_Faild()+ {+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.PS256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.PS.PublicKey.txt")+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Severity, InfoBarSeverity.Error);+ }++ #endregion++ #region GenerateES++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_ES_Token_Without_Signature_Should_Fail()+ {+ string token = await TestDataProvider.GetFileContent("Jwt.ES.BasicToken.txt");+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Message, _localizedStrings.InvalidPrivateKeyError);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_ES_Token()+ {+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.ES.PrivateKey.txt")+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_ES_Token_With_Partial_Private_Key()+ {+ string privateKey = await TestDataProvider.GetFileContent("Jwt.ES.PrivateKey.txt");+ privateKey = privateKey.Remove(0, "-----BEGIN PRIVATE KEY-----".Length).Trim();+ privateKey = privateKey.Remove(privateKey.Length - "-----END PRIVATE KEY-----".Length, "-----END PRIVATE KEY-----".Length).Trim();++ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = privateKey+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Complex_ES_Token()+ {+ var encoderParameters = new EncoderParameters()+ {+ HasAudience = true,+ HasExpiration = true,+ HasIssuer = true,+ HasDefaultTime = true+ };+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.ES.PrivateKey.txt"),+ ValidIssuers = new HashSet<string> { "devtoys" },+ ValidAudiences = new HashSet<string> { "devtoys" },+ ExpirationYear = 1,+ ExpirationMonth = 1,+ ExpirationDay = 1,+ ExpirationHour = 0,+ ExpirationMinute = 0+ };++ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNotNull(result);+ Assert.IsNull(_validationResult);+ Assert.IsNotNull(result.Token);+ }++ [TestMethod]+ public async Task JwtEncoder_Generate_Basic_ES_Token_With_Public_Key_Should_Faild()+ {+ var encoderParameters = new EncoderParameters();+ var tokenParameters = new TokenParameters()+ {+ TokenAlgorithm = JwtAlgorithm.ES256,+ Payload = await TestDataProvider.GetFileContent("Jwt.BasicPayload.json"),+ PrivateKey = await TestDataProvider.GetFileContent("Jwt.ES.PublicKey.txt")+ };+ var jwtDecoder = new JwtEncoder();+ TokenResult result = jwtDecoder.GenerateToken(encoderParameters, tokenParameters, DecodingErrorCallBack);++ Assert.IsNull(result);+ Assert.IsNotNull(_validationResult);+ Assert.AreEqual(_validationResult.Severity, InfoBarSeverity.Error);+ }++ #endregion++ internal static void DecodingErrorCallBack(TokenResultErrorEventArgs e)+ => _validationResult = new InfoBarData(e.Severity, e.Message);++ [TestCleanup]+ public void TestCleanup()+ {+ _validationResult = null;+ }+ }+}