├── README.md ├── ServerApi ├── appsettings.Development.json ├── appsettings.json ├── ServerApi.csproj ├── Properties │ └── launchSettings.json ├── Program.cs ├── Controllers │ └── TesteController.cs └── Startup.cs ├── Client ├── Client.csproj └── Program.cs ├── AsymetricEncryptionDemo ├── PrivateKey.csproj ├── CryptoService.cs └── Program.cs ├── LICENSE ├── AsymetricEncryptionDemo.sln └── .gitignore /README.md: -------------------------------------------------------------------------------- 1 | # JWE Experimnt 2 | 3 | Using JWE to cryptograph a credit card before send it through network to Server. -------------------------------------------------------------------------------- /ServerApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ServerApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /Client/Client.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /ServerApi/ServerApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /AsymetricEncryptionDemo/PrivateKey.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /ServerApi/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:41401", 8 | "sslPort": 44361 9 | } 10 | }, 11 | "profiles": { 12 | "Kestrel": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": "true", 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ServerApi/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.Hosting; 4 | using Microsoft.Extensions.Logging; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace ServerApi 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Bruno Brito 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /AsymetricEncryptionDemo/CryptoService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Security.Cryptography; 3 | using Microsoft.IdentityModel.Logging; 4 | using Microsoft.IdentityModel.Tokens; 5 | 6 | namespace PrivateKey 7 | { 8 | internal static class CryptoService 9 | { 10 | private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create(); 11 | /// 12 | /// Creates a new RSA security key. 13 | /// Key size recommendations: https://www.keylength.com/en/compare/ 14 | /// 15 | /// 16 | public static RsaSecurityKey CreateRsaSecurityKey(int keySize = 2048) 17 | { 18 | return new RsaSecurityKey(RSA.Create(keySize)) 19 | { 20 | KeyId = CreateUniqueId() 21 | }; 22 | } 23 | 24 | internal static string CreateUniqueId(int length = 16) 25 | { 26 | return Base64UrlEncoder.Encode(CreateRandomKey(length)); 27 | } 28 | 29 | /// Creates a random key byte array. 30 | /// The length. 31 | /// 32 | internal static byte[] CreateRandomKey(int length) 33 | { 34 | byte[] data = new byte[length]; 35 | Rng.GetBytes(data); 36 | return data; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /ServerApi/Controllers/TesteController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Security.Claims; 7 | using System.Threading.Tasks; 8 | using Microsoft.IdentityModel.JsonWebTokens; 9 | using Microsoft.IdentityModel.Tokens; 10 | using NetDevPack.Security.Jwt.Interfaces; 11 | 12 | namespace ServerApi.Controllers 13 | { 14 | [ApiController] 15 | [Route("teste")] 16 | public class TesteController : ControllerBase 17 | { 18 | private readonly ILogger _logger; 19 | private readonly IJsonWebKeySetService _jwksService; 20 | 21 | public TesteController(ILogger logger, IJsonWebKeySetService jsonWebKeySetService) 22 | { 23 | _logger = logger; 24 | _jwksService = jsonWebKeySetService; 25 | } 26 | 27 | [HttpGet] 28 | public IActionResult Get(string jwe) 29 | { 30 | var handler = new JsonWebTokenHandler(); 31 | var encryptingCredentials = _jwksService.GetCurrentEncryptingCredentials(); 32 | var result = handler.ValidateToken(jwe, 33 | new TokenValidationParameters 34 | { 35 | ValidIssuer = "me", 36 | ValidAudience = "you", 37 | RequireSignedTokens = false, 38 | TokenDecryptionKey = encryptingCredentials.Key, 39 | }); 40 | if (!result.IsValid) 41 | BadRequest(); 42 | 43 | return Ok(result.Claims); 44 | } 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Client/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IdentityModel.Tokens.Jwt; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Net.Http; 7 | using System.Security.Claims; 8 | using System.Text.Json; 9 | using System.Threading.Tasks; 10 | using Microsoft.IdentityModel.Tokens; 11 | 12 | namespace Client 13 | { 14 | class Program 15 | { 16 | private static string PublicKeyLocation = @"C:\Users\BRUNO BRITO\source\repos\AsymetricEncryptionDemo\AsymetricEncryptionDemo\bin\Debug\net5.0\publickey.json"; 17 | private static HttpClient client = new HttpClient(); 18 | static async Task Main(string[] args) 19 | { 20 | var tokenHandler = new JwtSecurityTokenHandler(); 21 | var key = await Loadkey(); 22 | 23 | var enc = new EncryptingCredentials(key, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes128CbcHmacSha256); 24 | var tokenDescriptor = new SecurityTokenDescriptor 25 | { 26 | Issuer = "me", 27 | Audience = "you", 28 | Subject = new ClaimsIdentity(new Claim[] 29 | { 30 | new Claim("cc", "4000-0000-0000-0002"), 31 | }), 32 | EncryptingCredentials = enc 33 | }; 34 | 35 | var token = tokenHandler.CreateToken(tokenDescriptor); 36 | 37 | 38 | Console.WriteLine(tokenHandler.WriteToken(token)); 39 | } 40 | 41 | 42 | private static async Task Loadkey() 43 | { 44 | var publicKey = await client.GetStringAsync("https://localhost:5001/jwks_e"); 45 | var key = JsonWebKeySet.Create(publicKey); 46 | return key.Keys.FirstOrDefault(); 47 | } 48 | 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /AsymetricEncryptionDemo.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31612.314 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PrivateKey", "AsymetricEncryptionDemo\PrivateKey.csproj", "{B075F926-2043-479F-B16A-BE5061A40A16}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client", "Client\Client.csproj", "{9E71B61D-94B1-4230-ACBB-E482C2770331}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServerApi", "ServerApi\ServerApi.csproj", "{939FE293-30BB-4767-80C0-FAEE5DF89C32}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {B075F926-2043-479F-B16A-BE5061A40A16}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {B075F926-2043-479F-B16A-BE5061A40A16}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {B075F926-2043-479F-B16A-BE5061A40A16}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {B075F926-2043-479F-B16A-BE5061A40A16}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {9E71B61D-94B1-4230-ACBB-E482C2770331}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {9E71B61D-94B1-4230-ACBB-E482C2770331}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {9E71B61D-94B1-4230-ACBB-E482C2770331}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {9E71B61D-94B1-4230-ACBB-E482C2770331}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {939FE293-30BB-4767-80C0-FAEE5DF89C32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {939FE293-30BB-4767-80C0-FAEE5DF89C32}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {939FE293-30BB-4767-80C0-FAEE5DF89C32}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {939FE293-30BB-4767-80C0-FAEE5DF89C32}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {D569921E-407F-4E9A-8039-13A4CBE51322} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /ServerApi/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.HttpsPolicy; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | using Microsoft.OpenApi.Models; 10 | using System; 11 | using System.Collections.Generic; 12 | using System.IO; 13 | using System.Linq; 14 | using System.Threading.Tasks; 15 | using NetDevPack.Security.Jwt; 16 | using NetDevPack.Security.Jwt.AspNetCore; 17 | using NetDevPack.Security.Jwt.Store.FileSystem; 18 | 19 | namespace ServerApi 20 | { 21 | public class Startup 22 | { 23 | public Startup(IConfiguration configuration) 24 | { 25 | Configuration = configuration; 26 | } 27 | 28 | public IConfiguration Configuration { get; } 29 | 30 | // This method gets called by the runtime. Use this method to add services to the container. 31 | public void ConfigureServices(IServiceCollection services) 32 | { 33 | services.AddControllers(); 34 | services.AddSwaggerGen(c => 35 | { 36 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "ServerApi", Version = "v1" }); 37 | }); 38 | services.AddDataProtection(); 39 | services.AddMemoryCache(); 40 | services.AddJwksManager(o => o.Jws = JwsAlgorithm.RS256).PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory())); 41 | } 42 | 43 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 44 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 45 | { 46 | if (env.IsDevelopment()) 47 | { 48 | app.UseDeveloperExceptionPage(); 49 | app.UseSwagger(); 50 | app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ServerApi v1")); 51 | } 52 | 53 | app.UseHttpsRedirection(); 54 | 55 | app.UseRouting(); 56 | 57 | app.UseAuthorization(); 58 | app.UseJwksDiscovery(); 59 | 60 | app.UseEndpoints(endpoints => 61 | { 62 | endpoints.MapControllers(); 63 | }); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | 11 | # User-specific files (MonoDevelop/Xamarin Studio) 12 | *.userprefs 13 | 14 | # Build results 15 | [Dd]ebug/ 16 | [Dd]ebugPublic/ 17 | [Rr]elease/ 18 | [Rr]eleases/ 19 | [Xx]64/ 20 | [Xx]86/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | [Dd]ist/ 25 | 26 | # Visual Studio 2015 cache/options directory 27 | .vs/ 28 | .sonarqube/ 29 | .nuget/ 30 | # Uncomment if you have tasks that create the project's static files in wwwroot 31 | #wwwroot/ 32 | 33 | # Vs publish files 34 | *.pubxml 35 | *.key 36 | # MSTest test Results 37 | [Tt]est[Rr]esult*/ 38 | [Bb]uild[Ll]og.* 39 | 40 | # NUNIT 41 | *.VisualState.xml 42 | TestResult.xml 43 | coverage.opencover.xml 44 | 45 | # Build Results of an ATL Project 46 | [Dd]ebugPS/ 47 | [Rr]eleasePS/ 48 | dlldata.c 49 | 50 | # DNX 51 | project.lock.json 52 | artifacts/ 53 | 54 | *_i.c 55 | *_p.c 56 | *_i.h 57 | *.ilk 58 | *.meta 59 | *.obj 60 | *.pch 61 | *.pdb 62 | *.pgc 63 | *.pgd 64 | *.rsp 65 | *.sbr 66 | *.tlb 67 | *.tli 68 | *.tlh 69 | *.tmp 70 | *.tmp_proj 71 | *.log 72 | *.vspscc 73 | *.vssscc 74 | .builds 75 | *.pidb 76 | *.svclog 77 | *.scc 78 | 79 | # Chutzpah Test files 80 | _Chutzpah* 81 | 82 | # Visual C++ cache files 83 | ipch/ 84 | *.aps 85 | *.ncb 86 | *.opendb 87 | *.opensdf 88 | *.sdf 89 | *.cachefile 90 | *.VC.db 91 | 92 | # Visual Studio profiler 93 | *.psess 94 | *.vsp 95 | *.vspx 96 | *.sap 97 | 98 | # TFS 2012 Local Workspace 99 | $tf/ 100 | 101 | # Guidance Automation Toolkit 102 | *.gpState 103 | 104 | # ReSharper is a .NET coding add-in 105 | _ReSharper*/ 106 | *.[Rr]e[Ss]harper 107 | *.DotSettings.user 108 | 109 | # JustCode is a .NET coding add-in 110 | .JustCode 111 | 112 | # TeamCity is a build add-in 113 | _TeamCity* 114 | 115 | # DotCover is a Code Coverage Tool 116 | *.dotCover 117 | 118 | # NCrunch 119 | _NCrunch_* 120 | .*crunch*.local.xml 121 | nCrunchTemp_* 122 | 123 | # MightyMoose 124 | *.mm.* 125 | AutoTest.Net/ 126 | 127 | # Web workbench (sass) 128 | .sass-cache/ 129 | 130 | # Installshield output folder 131 | [Ee]xpress/ 132 | 133 | # DocProject is a documentation generator add-in 134 | DocProject/buildhelp/ 135 | DocProject/Help/*.HxT 136 | DocProject/Help/*.HxC 137 | DocProject/Help/*.hhc 138 | DocProject/Help/*.hhk 139 | DocProject/Help/*.hhp 140 | DocProject/Help/Html2 141 | DocProject/Help/html 142 | 143 | # Click-Once directory 144 | publish/ 145 | 146 | # Publish Web Output 147 | *.[Pp]ublish.xml 148 | *.azurePubxml 149 | 150 | # TODO: Un-comment the next line if you do not want to checkin 151 | # your web deploy settings because they may include unencrypted 152 | # passwords 153 | #*.pubxml 154 | *.publishproj 155 | 156 | # NuGet Packages 157 | *.nupkg 158 | # The packages folder can be ignored because of Package Restore 159 | **/packages/* 160 | # except build/, which is used as an MSBuild target. 161 | !**/packages/build/ 162 | # Uncomment if necessary however generally it will be regenerated when needed 163 | #!**/packages/repositories.config 164 | # NuGet v3's project.json files produces more ignoreable files 165 | *.nuget.props 166 | *.nuget.targets 167 | 168 | # Microsoft Azure Build Output 169 | csx/ 170 | *.build.csdef 171 | 172 | # Microsoft Azure Emulator 173 | ecf/ 174 | rcf/ 175 | 176 | # Windows Store app package directory 177 | AppPackages/ 178 | BundleArtifacts/ 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | [Ss]tyle[Cc]op.* 189 | ~$* 190 | *~ 191 | *.dbmdl 192 | *.dbproj.schemaview 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # RIA/Silverlight projects 199 | Generated_Code/ 200 | 201 | # Backup & report files from converting an old project file 202 | # to a newer Visual Studio version. Backup files are not needed, 203 | # because we have git ;-) 204 | _UpgradeReport_Files/ 205 | Backup*/ 206 | UpgradeLog*.XML 207 | UpgradeLog*.htm 208 | 209 | # SQL Server files 210 | *.mdf 211 | *.ldf 212 | 213 | # Business Intelligence projects 214 | *.rdl.data 215 | *.bim.layout 216 | *.bim_*.settings 217 | 218 | # Microsoft Fakes 219 | FakesAssemblies/ 220 | 221 | # GhostDoc plugin setting file 222 | *.GhostDoc.xml 223 | 224 | # Node.js Tools for Visual Studio 225 | .ntvs_analysis.dat 226 | 227 | # Visual Studio 6 build log 228 | *.plg 229 | 230 | # Visual Studio 6 workspace options file 231 | *.opt 232 | 233 | # Visual Studio LightSwitch build output 234 | **/*.HTMLClient/GeneratedArtifacts 235 | **/*.DesktopClient/GeneratedArtifacts 236 | **/*.DesktopClient/ModelManifest.xml 237 | **/*.Server/GeneratedArtifacts 238 | **/*.Server/ModelManifest.xml 239 | _Pvt_Extensions 240 | 241 | # LightSwitch generated files 242 | GeneratedArtifacts/ 243 | ModelManifest.xml 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | 248 | # FAKE - F# Make 249 | .fake/ 250 | 251 | # Sphinx 252 | *.opt 253 | docs/_build 254 | docs/.vscode 255 | 256 | # Log files 257 | **/*log*.txt 258 | *.db 259 | -------------------------------------------------------------------------------- /AsymetricEncryptionDemo/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IdentityModel.Tokens.Jwt; 4 | using System.IO; 5 | using System.Net.Http.Json; 6 | using System.Security.Claims; 7 | using System.Security.Cryptography; 8 | using System.Text; 9 | using System.Text.Json; 10 | using System.Text.Json.Serialization; 11 | using Microsoft.IdentityModel.JsonWebTokens; 12 | using Microsoft.IdentityModel.Tokens; 13 | 14 | namespace PrivateKey 15 | { 16 | class Program 17 | { 18 | private static readonly string PrivateJwkLocation = Path.Combine(Environment.CurrentDirectory, "mysupersecretkey.json"); 19 | private static readonly string PublicJwkLocation = Path.Combine(Environment.CurrentDirectory, "publickey.json"); 20 | private static RandomNumberGenerator Rng = RandomNumberGenerator.Create(); 21 | static void Main() 22 | { 23 | var key = Loadkey(); 24 | 25 | var jwe = "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJ0eXAiOiJKV1QifQ.K4-rhbkRn8CrGmLLQb_uucH23QUC1dLkJ2-lVPJ3ZhE2epWi8U6IFBFFJoGZBIeJf8sP47cD2Us54uo8RDlhLw9R_cWpnRhZ_N1uwJgrIgxdx_ldnS-WkEkHFEn3iy7-23yYVi-NfzTNwjlJF0MvGyM-nMNR_HBblHmbfT2PGjfdpS7qxN75mxr0RSeh6OExq68pvItuL2fnNljnI1ZpawDzJI3wRB3Ge0xRe7AAphV6BpEFKhcdVMcOq-vaCKWjcWSw-CBQ2hpv243lR7fN3ontvnxo5FsAY8yDgfSwEwKj4SmQ3KAa8wyGMZoFY4IugdAwEszvQ3tBL0vUu7DsOQ.X9fCTCsPKB49tiwADcc1FQ.FnMDAbr96Dy3lwR_OCMYM2390WSIv_5tl8gb9J8tl4fYXSPpH9t6kYxAmYn36hX0ySnporK7-gjYvCIDuK4Y72f9wC8P4x-jAFdJQkvgWHIZlf6yspMdyXL9YZeCL2ZGZSAs5Xp5ncvOnuRB9na6Z64qtGiJ-3iALK2uxcUAXCrojSYR8OYLeujF2wKC1422.uWTs_yH1mee7gAhKvI5t1w"; 26 | 27 | var encryptingCredentials = new EncryptingCredentials(key, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes128CbcHmacSha256); 28 | 29 | var handler = new JsonWebTokenHandler(); 30 | var result = handler.ValidateToken(jwe, 31 | new TokenValidationParameters 32 | { 33 | RequireSignedTokens = false, 34 | TokenDecryptionKey = encryptingCredentials.Key, 35 | ValidateAudience = false, 36 | ValidateIssuer = false 37 | }); 38 | 39 | 40 | } 41 | 42 | 43 | private static byte[] GenerateKey(int bytes) 44 | { 45 | var data = new byte[bytes]; 46 | Rng.GetBytes(data); 47 | return data; 48 | } 49 | 50 | private static SecurityKey Loadkey() 51 | { 52 | if (File.Exists(PrivateJwkLocation)) 53 | return JsonSerializer.Deserialize(File.ReadAllText(PrivateJwkLocation)); 54 | 55 | var key = new RsaSecurityKey(RSA.Create(2048)) 56 | { 57 | KeyId = Guid.NewGuid().ToString() 58 | }; 59 | var privateKey = JsonWebKeyConverter.ConvertFromRSASecurityKey(key); 60 | privateKey.KeyId = Base64UrlEncoder.Encode(GenerateKey(16)); 61 | File.WriteAllText(PrivateJwkLocation, JsonSerializer.Serialize(privateKey, new JsonSerializerOptions() { IgnoreNullValues = true })); 62 | 63 | 64 | var rsaPublic = new RsaSecurityKey(RSA.Create(key.Rsa.ExportParameters(false))); 65 | var publicKey = JsonWebKeyConverter.ConvertFromRSASecurityKey(rsaPublic); 66 | File.WriteAllText(PublicJwkLocation, JsonSerializer.Serialize(publicKey, new JsonSerializerOptions() { IgnoreNullValues = true })); 67 | 68 | return key; 69 | } 70 | 71 | private static JsonWebKey CreateJWK() 72 | { 73 | var key = new RsaSecurityKey(RSA.Create(2048)) 74 | { 75 | KeyId = Guid.NewGuid().ToString() 76 | }; 77 | var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key); 78 | jwk.KeyId = Base64UrlEncoder.Encode(GenerateKey(16)); 79 | 80 | 81 | 82 | 83 | return jwk; 84 | } 85 | 86 | private static void DemoRodando() 87 | { 88 | //lets take a new CSP with a new 2048 bit rsa key pair 89 | var csp = new RSACryptoServiceProvider(2048); 90 | 91 | //how to get the private key 92 | var privKey = csp.ExportParameters(true); 93 | 94 | //and the public key ... 95 | var pubKey = csp.ExportParameters(false); 96 | 97 | 98 | //converting the public key into a string representation 99 | string pubKeyString = JsonSerializer.Serialize(pubKey); 100 | 101 | //converting it back 102 | pubKey = JsonSerializer.Deserialize(pubKeyString); 103 | 104 | //conversion for the private key is no black magic either ... omitted 105 | 106 | //we have a public key ... let's get a new csp and load that key 107 | csp = new RSACryptoServiceProvider(); 108 | csp.ImportParameters(pubKey); 109 | 110 | //we need some data to encrypt 111 | var plainTextData = "foobar"; 112 | 113 | //for encryption, always handle bytes... 114 | var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData); 115 | 116 | //apply pkcs#1.5 padding and encrypt our data 117 | var bytesCypherText = csp.Encrypt(bytesPlainTextData, false); 118 | 119 | //we might want a string representation of our cypher text... base64 will do 120 | var cypherText = Convert.ToBase64String(bytesCypherText); 121 | 122 | 123 | /* 124 | * some transmission / storage / retrieval 125 | * 126 | * and we want to decrypt our cypherText 127 | */ 128 | 129 | //first, get our bytes back from the base64 string ... 130 | bytesCypherText = Convert.FromBase64String(cypherText); 131 | 132 | //we want to decrypt, therefore we need a csp and load our private key 133 | csp = new RSACryptoServiceProvider(); 134 | csp.ImportParameters(privKey); 135 | 136 | //decrypt and strip pkcs#1.5 padding 137 | bytesPlainTextData = csp.Decrypt(bytesCypherText, false); 138 | 139 | //get our original plainText back... 140 | plainTextData = System.Text.Encoding.Unicode.GetString(bytesPlainTextData); 141 | } 142 | } 143 | } 144 | --------------------------------------------------------------------------------