private static string DecryptProtectedKey(string protectedKey) { var dataProtectionProvider = DataProtectionProvider.Create(Directory.GetCurrentDirectory()); var protector = dataProtectionProvider.CreateProtector("SecretsManager"); return(protector.Unprotect(protectedKey)); }
public static void Main(string[] args) { // get the path to %LOCALAPPDATA%\myapp-keys string destFolder = Path.Combine( Environment.GetEnvironmentVariable("LOCALAPPDATA"), "myapp-keys"); // instantiate the data protection system at this folder var dataProtectionProvider = DataProtectionProvider.Create( new DirectoryInfo(destFolder)); var protector = dataProtectionProvider.CreateProtector("Program.No-DI"); Console.Write("Enter input: "); string input = Console.ReadLine(); // protect the payload string protectedPayload = protector.Protect(input); Console.WriteLine($"Protect returned: {protectedPayload}"); // unprotect the payload string unprotectedPayload = protector.Unprotect(protectedPayload); Console.WriteLine($"Unprotect returned: {unprotectedPayload}"); }
private IDataProtector GetMachineProtector(byte[] optionalEntropy) { var provider = DataProtectionProvider.Create(AppName); var purpose = CreatePurpose(optionalEntropy); return(provider.CreateProtector(purpose)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add DocumentDb client singleton instance (it's recommended to use a singleton instance for it) services.AddSingleton(InitializeDocumentClient( Configuration.GetValue <Uri>("DocumentDbClient:EndpointUri"), Configuration.GetValue <string>("DocumentDbClient:AuthorizationKey"))); // Add framework services. services.AddIdentity <ApplicationUser, DocumentDbIdentityRole>(options => { options.Cookies.ApplicationCookie.AuthenticationScheme = "ApplicationCookie"; options.Cookies.ApplicationCookie.CookieName = "Interop"; options.Cookies.ApplicationCookie.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo("C:\\Github\\Identity\\artifacts")); }) .AddDocumentDbStores(options => { options.UserStoreDocumentCollection = "AspNetIdentity"; options.Database = "AspNetCoreIdentitySample"; }) .AddDefaultTokenProviders(); services.AddMvc(); // Add application services. services.AddTransient <IEmailSender, AuthMessageSender>(); services.AddTransient <ISmsSender, AuthMessageSender>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var sqlConnectionString = "server=164.132.233.40;userid=switchlook_db;password=teoy3RroLKqqWpm0;database=switchlook_dev;"; services.AddDbContext <DataContext>(options => options.UseMySql( sqlConnectionString ) ); services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <DataContext>() .AddDefaultTokenProviders(); services.AddAuthentication() .AddCookie(); services.ConfigureApplicationCookie(options => { var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\")); options.DataProtectionProvider = protectionProvider; options.TicketDataFormat = new TicketDataFormat(protectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2")); }); services.AddMvc(); }
public void Dictionary_of_string_string_works() { Coordinator.Configure(options => options.DataProtectionProvider = DataProtectionProvider.Create("test")); var myStrings = new Dictionary <string, string> { { "first_key", "first_value" }, { "another key", "another value" }, }; var foo = new FooStringDictionary { MyStrings = myStrings }; var json = JsonSerializer.Serialize(foo); // make sure it's encrypted using (var jsonDoc = JsonDocument.Parse(json)) { var jsonProperty = jsonDoc.RootElement.GetProperty(nameof(FooStringDictionary.MyStrings)); jsonProperty.ValueKind.ShouldBe(JsonValueKind.String); } // decrypt and check var decrypted = JsonSerializer.Deserialize <FooStringDictionary>(json); decrypted.MyStrings.ShouldBe(myStrings); }
public static void Main(string[] args) { var keysFolder = Path.Combine(Directory.GetCurrentDirectory(), "temp-keys"); // instantiate the data protection system at this folder var dataProtectionProvider = DataProtectionProvider.Create( new DirectoryInfo(keysFolder), configuration => { configuration.SetApplicationName("my app name"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { configuration.ProtectKeysWithDpapi(); } }); var protector = dataProtectionProvider.CreateProtector("Program.No-DI"); // protect the payload var protectedPayload = protector.Protect("Hello World!"); Console.WriteLine($"Protect returned: {protectedPayload}"); // unprotect the payload var unprotectedPayload = protector.Unprotect(protectedPayload); Console.WriteLine($"Unprotect returned: {unprotectedPayload}"); }
public void System_CanUnprotectWithCert() { var filePath = Path.Combine(GetTestFilesPath(), "TestCert2.pfx"); var certificate = new X509Certificate2(filePath, "password"); WithUniqueTempDirectory(directory => { // Step 1: directory should be completely empty directory.Create(); Assert.Empty(directory.GetFiles()); // Step 2: instantiate the system and create some data var protector = DataProtectionProvider .Create(directory, certificate) .CreateProtector("purpose"); var data = protector.Protect("payload"); // Step 3: validate that there's now a single key in the directory and that it's is protected using the certificate var allFiles = directory.GetFiles(); Assert.Single(allFiles); Assert.StartsWith("key-", allFiles[0].Name, StringComparison.OrdinalIgnoreCase); string fileText = File.ReadAllText(allFiles[0].FullName); Assert.DoesNotContain("Warning: the key below is in an unencrypted form.", fileText, StringComparison.Ordinal); Assert.Contains("X509Certificate", fileText, StringComparison.Ordinal); // Step 4: setup a second system and validate it can decrypt keys and unprotect data var unprotector = DataProtectionProvider.Create(directory, b => b.UnprotectKeysWithAnyCertificate(certificate)); Assert.Equal("payload", unprotector.CreateProtector("purpose").Unprotect(data)); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity <ApplicationUser, IdentityRole>(options => { options.Cookies.ApplicationCookie.AuthenticationScheme = "ApplicationCookie"; var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\")); options.Cookies.ApplicationCookie.DataProtectionProvider = protectionProvider; options.Cookies.ApplicationCookie.TicketDataFormat = new TicketDataFormat(protectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2")); //options.Cookies.ApplicationCookie.AutomaticChallenge = true; //options.Cookies.ApplicationCookie.AutomaticAuthenticate = true; }) .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddMvc(); // Add application services. services.AddTransient <IEmailSender, AuthMessageSender>(); services.AddTransient <ISmsSender, AuthMessageSender>(); }
public void Internal_properties() { Coordinator.Configure(options => options.DataProtectionProvider = DataProtectionProvider.Create("test")); var foo = new FooInternalProperties { MyInt = 57, MyString = "foo" }; var json = JsonSerializer.Serialize(foo); // make sure it's encrypted using (var jsonDoc = JsonDocument.Parse(json)) { var encryptedInt = jsonDoc.RootElement.GetProperty(nameof(FooInternalProperties.MyInt)); encryptedInt.ValueKind.ShouldBe(JsonValueKind.String); encryptedInt.GetString().ShouldNotBe(JsonSerializer.Serialize(foo.MyInt)); var unencryptedString = jsonDoc.RootElement.GetProperty(nameof(FooInternalProperties.MyString)); unencryptedString.ValueKind.ShouldBe(JsonValueKind.String); unencryptedString.GetString().ShouldBe(foo.MyString); } // decrypt and check var decrypted = JsonSerializer.Deserialize <FooInternalProperties>(json); decrypted.MyString.ShouldBe(foo.MyString); decrypted.MyInt.ShouldBe(foo.MyInt); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Set connection configuration DataConnection .AddConfiguration( "Default", Configuration["Data:DefaultConnection:ConnectionString"], new SqlServerDataProvider("Default", SqlServerVersion.v2012)); DataConnection.DefaultConfiguration = "Default"; services.AddIdentity <ApplicationUser, LinqToDB.Identity.IdentityRole>() .AddLinqToDBStores(new DefaultConnectionFactory()) .AddDefaultTokenProviders(); services.AddAuthentication() .AddCookie(options => { options.Cookie.Name = "Interop"; options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo("C:\\Github\\Identity\\artifacts")); }); services.AddMvc(); // Add application services. services.AddTransient <IEmailSender, AuthMessageSender>(); services.AddTransient <ISmsSender, AuthMessageSender>(); }
public void One_property_but_not_the_other() { Coordinator.Configure(options => options.DataProtectionProvider = DataProtectionProvider.Create("test")); var foo = new FooMixedEncryption { EncryptedInt = 57, UnencryptedString = "foo" }; var json = JsonSerializer.Serialize(foo); // make sure it's encrypted using (var jsonDoc = JsonDocument.Parse(json)) { var encryptedInt = jsonDoc.RootElement.GetProperty(nameof(FooMixedEncryption.EncryptedInt)); encryptedInt.ValueKind.ShouldBe(JsonValueKind.String); encryptedInt.GetString().ShouldNotBe(JsonSerializer.Serialize(foo.EncryptedInt)); var unencryptedString = jsonDoc.RootElement.GetProperty(nameof(FooMixedEncryption.UnencryptedString)); unencryptedString.ValueKind.ShouldBe(JsonValueKind.String); unencryptedString.GetString().ShouldBe(foo.UnencryptedString); } // decrypt and check var decrypted = JsonSerializer.Deserialize <FooMixedEncryption>(json); decrypted.UnencryptedString.ShouldBe(foo.UnencryptedString); decrypted.EncryptedInt.ShouldBe(foo.EncryptedInt); }
public static void Start(string[] args) { // Get the path to %LOCALAPPDATA%\myapp-keys var destFolder = Path.Combine(Environment.CurrentDirectory, "myapp-keys"); // Instantiate the data protection system at this folder var dataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(destFolder), setup => { setup.SetApplicationName("my app name"); }); var protector = dataProtectionProvider.CreateProtector("Program.No-DI"); Console.Write("Enter input: "); var input = Console.ReadLine(); // Protect the payload var protectedPayload = protector.Protect(input); Console.WriteLine($"Protect returned: {protectedPayload}"); // Unprotect the payload var unprotectedPayload = protector.Unprotect(protectedPayload); Console.WriteLine($"Unprotect returned: {unprotectedPayload}"); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); }
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301883 public void ConfigureAuth(IAppBuilder app) { // Now we create a data protector, with a fixed purpose and sub-purpose used in key derivation. var protectionProvider = DataProtectionProvider.Create( new DirectoryInfo(ConfigurationManager.AppSettings["KeyRing.Path"]), (builder) => { builder.SetApplicationName("MicrosoftIgniteDemo"); }); var dataProtector = protectionProvider.CreateProtector( "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Identity.Application", "v2"); // And finally create a new auth ticket formatter using the data protector. var ticketFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector)); // Now configure the cookie options to have the same cookie name, and use // the common format. app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, //AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, CookieSecure = CookieSecureOption.Never, CookieName = ".MyApp.SharedCookie", TicketDataFormat = ticketFormat, CookieManager = new ChunkingCookieManager(), LoginPath = new PathString("/Login"), Provider = new CookieAuthenticationProvider() { OnApplyRedirect = ApplyRedirect } }); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add(new GolbalExceptionAttribute()); options.Filters.Add(new GobalModelValidAttribute()); options.Filters.Add <GlobalAuthorizeAttribute>(); options.Filters.Add <GobalPermCodeAttribute>(); options.ModelBinderProviders.Insert(0, new TrimModelBinderProvider());//去除空格 }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; options.SerializerSettings.Formatting = Formatting.Indented; } ); //cookies身份认证 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = AuthName; options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromDays(7); options.LoginPath = "/Account/Logon"; options.LogoutPath = "/Account/Logout"; options.SlidingExpiration = true; options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(Directory.GetCurrentDirectory())); }); services.AddScoped <GlobalAuthorizeAttribute>(); services.AddHttpContextAccessor(); //基础框架注入 services.AddSingleton(new MongoRepository(Configuration["MongoDbUrl"])); services.AddService(); }
internal static void CookieAuthOptions(CookieAuthenticationOptions options) { options.Cookie.Name = _configuration["Properties:SharedAuthCookie"]; options.Cookie.HttpOnly = true; options.Cookie.Path = "/"; options.Cookie.IsEssential = true; //Configures the ticket lifetime inside the cookie; not the cookie lifetime ::AuthCookie //This is separate from the value of , which specifies how long the browser will keep the cookie, //which should be controlled and set in IS4 Options options.ExpireTimeSpan = TimeSpan.FromSeconds(Double.Parse(_configuration["LifeTimes:AuthCookieExpireSeconds"].ToString())); //This is for session lifetimes....not token options.SlidingExpiration = true; IDataProtectionProvider protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(_configuration["SECRETS_DIR"]), options => { options.SetApplicationName(_configuration["Properties:ApplicationName"]); }); options.DataProtectionProvider = protectionProvider; IDataProtector protector = protectionProvider.CreateProtector("CookieProtector"); options.TicketDataFormat = new TicketDataFormat(protector); }
private static JwtAuthTicketFormat createAuthTicketFormat(IHostEnvironment hostEnv, IDataProtectionProvider?dataProtectionProvider, IConfiguration config) { var xtiAuthOptions = config.GetSection(XtiAuthenticationOptions.XtiAuthentication).Get <XtiAuthenticationOptions>(); var key = Encoding.ASCII.GetBytes(xtiAuthOptions.JwtSecret); var dataSerializer = new TicketSerializer(); if (dataProtectionProvider == null) { var xtiFolder = new XtiFolder(hostEnv); var keyDirPath = xtiFolder.SharedAppDataFolder() .WithSubFolder("Keys") .Path(); dataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(keyDirPath)); } var dataProtector = dataProtectionProvider.CreateProtector(new[] { "XTI_Apps_Auth1" }); var authTicketFormat = new JwtAuthTicketFormat ( new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }, dataSerializer, dataProtector ); return(authTicketFormat); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(GetKeyRingFolderPath())); services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = ".AspNet.SharedCookie"; options.DataProtectionProvider = protectionProvider; }); services.ConfigureApplicationCookie(options => { options.Cookie.Name = ".AspNet.SharedCookie"; options.DataProtectionProvider = protectionProvider; options.TicketDataFormat = new TicketDataFormat( protectionProvider.CreateProtector( "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2")); }); services.AddMvc(); }
public TicketDataFormat(Microsoft.Owin.Security.DataProtection.IDataProtector protector = null) : base( new TicketSerializer(), protector ?? new DataProtectorShim((DataProtectionProvider.Create(new DirectoryInfo(Environment.GetEnvironmentVariable("Temp"))).CreateProtector("OAuth.AspNet.AuthServer", "Access_Token", "v1"))), TextEncodings.Base64Url ) { }
public static void TestEncryptedKeys() { // Get the path to %LOCALAPPDATA%\_playground.net var destFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), KeysFolderName); // Instantiate the data protection system at this folder var dataProtectionProvider = DataProtectionProvider.Create( new DirectoryInfo(destFolder), configuration => { configuration.SetApplicationName("Playground.net 1.0"); configuration.ProtectKeysWithDpapi(); }); var protector = dataProtectionProvider.CreateProtector("Playground.net.No-DI"); Console.Write("Enter input: "); var input = Console.ReadLine(); // Protect the payload var protectedPayload = protector.Protect(input); Console.WriteLine($"Protect returned: {protectedPayload}"); // Unprotect the payload var unprotectedPayload = protector.Unprotect(protectedPayload); Console.WriteLine($"Unprotect returned: {unprotectedPayload}"); }
/// <summary> /// /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews().AddRazorRuntimeCompilation(); services.AddHttpClient <AccountServiceClient>(client => { client.BaseAddress = new Uri(Configuration["GateWayAddress"]); }); services.AddHttpClient <SystemManageServiceClient>(client => { client.BaseAddress = new Uri(Configuration["GateWayAddress"]); }); //cookies身份认证 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = "yan.admin"; options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromDays(7); options.LoginPath = "/Account/Logon"; options.LogoutPath = "/Account/Logout"; options.SlidingExpiration = true; options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(Directory.GetCurrentDirectory())); }); //注入IHttpContextAccessor,方便获取HttpContext services.AddHttpContextAccessor(); //制定控制器的实例有容器来创建,方便属性注入,Controller本身默认是由MVC模块管理的, services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services .AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.Cookie.Name = "loggedinuser"; options.LoginPath = "/Login/Login"; options.LogoutPath = "/Login/logout"; options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\temp-keys\")); }); var connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext <EntityDbContext>(options => options.UseSqlServer(connectionString), ServiceLifetime.Transient); services.AddHttpContextAccessor(); services.AddControllersWithViews(); services.AddScoped <DataHelper, DataHelper>(); services.AddMvc(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(100);//You can set Time }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(options => { //options.Filters.Add<GlobalAuthorizeAttribute>(); }).AddRazorRuntimeCompilation(); //cookiesÉí·ÝÈÏÖ¤ services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = COOKIE_NAME; options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromDays(7); options.LoginPath = "/Account/Login"; options.LogoutPath = "/Account/Logout"; options.SlidingExpiration = true; options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(Directory.GetCurrentDirectory())); }); services.AddDbContext <SkylineDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection")) ); services.AddScoped(typeof(IAsyncRepository <>), typeof(EFRepository <>)); //services.AddScoped<GlobalAuthorizeAttribute>(); services.AddSkylineService(); }
private static void PayloadDemo() { //get the path to %LOCALAPPDATA%\myapp-keys var destFolder = Path.Combine( System.Environment.GetEnvironmentVariable("LOCALAPPDATA"), "myapp-keys"); // Instantiate the data protection system at this folder var dataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(destFolder)); var protector = dataProtectionProvider.CreateProtector("Program.No-DI"); Console.Write("Enter Input:"); var input = Console.ReadLine(); //Protect the Payload var protectedPayload = protector.Protect(input); Console.WriteLine($"Protect Returned: {protectedPayload}"); //UnProtect Payload var unProtectedPayload = protector.Unprotect(protectedPayload); Console.WriteLine($"Unprotected Retured: {unProtectedPayload}"); Console.WriteLine(); Console.WriteLine("Press any Key..."); Console.ReadKey(); }
static void Main(string[] args) { var provider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\myapp-keys\")); var baseProtector = provider.CreateProtector("Contoso.TimeLimitedSample"); // convert the normal protector into a time-limited protector var timeLimitedProtector = baseProtector.ToTimeLimitedDataProtector(); // get some input and protect it for five seconds Console.Write("Enter input: "); string input = Console.ReadLine(); string protectedData = timeLimitedProtector.Protect(input, lifetime: TimeSpan.FromSeconds(5)); Console.WriteLine($"Protected data: {protectedData}"); // unprotect it to demonstrate that round-tripping works properly string roundtripped = timeLimitedProtector.Unprotect(protectedData); Console.WriteLine($"Round-tripped data: {roundtripped}"); // wait 6 seconds and perform another unprotect, demonstrating that the payload self-expires Console.WriteLine("Waiting 6 seconds..."); Thread.Sleep(6000); timeLimitedProtector.Unprotect(protectedData); Console.ReadKey(); }
public override void OnActionExecuting(ActionExecutingContext context) { var dataProtectionProvider = DataProtectionProvider.Create("WebQuery"); var protector = dataProtectionProvider.CreateProtector("WebQuery.QueryStrings"); Dictionary <string, object> decryptedParamaters = new Dictionary <string, object>(); if (context.HttpContext.Request.Query["q"].ToString() != null) { string decrptedString = protector.Unprotect(context.HttpContext.Request.Query["q"].ToString()); string[] getRandom = decrptedString.Split('['); var format = new CultureInfo("en-GB"); var dataCheck = Convert.ToDateTime(getRandom[2], format); TimeSpan diff = Convert.ToDateTime(DateTime.Now, format) - dataCheck; if (diff.Minutes > 30) { context.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Error", controller = "Error" })); } string[] paramsArrs = getRandom[1].Split(','); for (int i = 0; i < paramsArrs.Length; i++) { string[] paramArr = paramsArrs[i].Split('='); decryptedParamaters.Add(paramArr[0], Convert.ToString(paramArr[1])); } } for (int i = 0; i < decryptedParamaters.Count; i++) { context.ActionArguments[decryptedParamaters.Keys.ElementAt(i)] = decryptedParamaters.Values.ElementAt(i); } }
public static void Main(string[] args) { // Get the path to %LOCALAPPDATA%\myapp-keys var destFolder = Path.Combine( System.Environment.GetEnvironmentVariable("LOCALAPPDATA"), "myapp-keys"); // Instantiate the data protection system at this folder var dataProtectionProvider = DataProtectionProvider.Create( new DirectoryInfo(destFolder), configuration => { configuration.SetApplicationName("my app name"); configuration.ProtectKeysWithDpapi(); }); var protector = dataProtectionProvider.CreateProtector("Program.No-DI"); Console.Write("Enter input: "); var input = Console.ReadLine(); // Protect the payload var protectedPayload = protector.Protect(input); Console.WriteLine($"Protect returned: {protectedPayload}"); // Unprotect the payload var unprotectedPayload = protector.Unprotect(protectedPayload); Console.WriteLine($"Unprotect returned: {unprotectedPayload}"); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); }
public void ConfigureServices(IServiceCollection services) { services.AddDbContext <ApplicationDbContext>(options => options.UseInMemoryDatabase("InMemoryDB")); services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); #region snippet1 services.ConfigureApplicationCookie(options => { var protectionProvider = DataProtectionProvider.Create( new DirectoryInfo(GetKeyRingFolderPath())); options.Cookie.Name = ".AspNet.SharedCookie"; options.DataProtectionProvider = protectionProvider; options.TicketDataFormat = new TicketDataFormat( protectionProvider.CreateProtector( "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2")); }); #endregion services.AddTransient <IEmailSender, EmailSender>(); services.AddMvc(); }
static void Main() { var dataProtectionProvider = DataProtectionProvider.Create("Test App"); var protector = dataProtectionProvider.CreateProtector("Program.No-DI"); var plainText = "ABCDEFGH"; var protectedText = protector.Protect(plainText); }
private static void GetProtectedKey() { // Create Method 1: // var dataProtectionProvider = DataProtectionProvider.Create(Directory.GetCurrentDirectory()); // Create Method 2: string destFolder = Path.Combine( Environment.GetEnvironmentVariable("LOCALAPPDATA"), "AppSecrets"); var dataProtectionProvider = DataProtectionProvider.Create( new DirectoryInfo(destFolder), configuration => { configuration.SetApplicationName("SecretsManager"); configuration.ProtectKeysWithDpapi(); } ); // Create Method 3: // var dataProtectionProvider = DataProtectionProvider.Create("Secrete-Key"); var protector = dataProtectionProvider.CreateProtector("General.Protection"); Console.Write("Enter inputs (empty to leave): "); string input = Console.ReadLine(); if (!string.IsNullOrEmpty(input)) { string protectedInput = protector.Protect(input); Console.WriteLine($"Protect returned: {protectedInput}"); Console.WriteLine($"UnProtect returned: {protector.Unprotect(protectedInput)}"); } }