public static void Main(string[] args)
    {
        // create a protector for my application
         
        var provider      = new DataProtectionProvider(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);
    }
Exemplo n.º 2
0
    public static void Main(string[] args)
    {
        // get the path to %LOCALAPPDATA%\myapp-keys
        string destFolder = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "myapp-keys");
         
        // instantiate the data protection system at this folder
        var dataProtectionProvider = new DataProtectionProvider(
            new DirectoryInfo(destFolder),
            configuration =>
        {
            configuration.SetApplicationName("my app name");
            configuration.ProtectKeysWithDpapi();
        });
         
        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}");
    }
Exemplo n.º 3
0
        public DiscourseAuthenticationOptions()
        {
            CallbackPath = "/auth-discourse";

            _nonceCookieBuilder = new DiscourseNonceCookieBuilder(this)
            {
                Name         = ".CitizenFX.Discourse.Nonce.",
                HttpOnly     = true,
                SameSite     = SameSiteMode.None,
                SecurePolicy = CookieSecurePolicy.SameAsRequest,
                IsEssential  = true,
            };

            DataProtectionProvider = Microsoft.AspNetCore.DataProtection.DataProtectionProvider.Create("FXServer");

            var dataProtector = DataProtectionProvider.CreateProtector(
                typeof(DiscourseAuthenticationHandler).FullName,
                typeof(string).FullName,
                "DAO",
                "v1");

            StringDataFormat = new SecureDataFormat <string>(new StringSerializer(), dataProtector);

            StateDataFormat = new PropertiesDataFormat(dataProtector);
        }
Exemplo n.º 4
0
        public ActionResult <Student> Get(string id)
        {
            //var protector = DataProtectionProvider.CreateProtector("ProtectResourceId");
            var protector  = DataProtectionProvider.CreateProtector("A", "B", "C");
            var rawId      = protector.Unprotect(id);
            var targetItem = students.FirstOrDefault(s => s.Id == rawId);

            return(new Student {
                Id = id, Name = targetItem.Name
            });
        }
Exemplo n.º 5
0
        public static IAppBuilder UseCookieAuthentication(
            this IAppBuilder app,
            CookieAuthenticationOptions options,
            DataProtectionProvider dataProtectionProvider,
            PipelineStage stage = PipelineStage.Authenticate)
        {
            var dataProtector = dataProtectionProvider.CreateProtector(
                "Microsoft.AspNet.Authentication.Cookies.CookieAuthenticationMiddleware", // full name of the ASP.NET 5 type
                options.AuthenticationType, "v2");

            options.TicketDataFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector));

            return(app.UseCookieAuthentication(options, stage));
        }
        private void StoreTokenCookie(HttpContext httpContext, T token)
        {
            NullGuard.NotNull(httpContext, nameof(httpContext))
            .NotNull(token, nameof(token));

            IDataProtector dataProtector = DataProtectionProvider.CreateProtector("TokenProtection");

            byte[] tokenByteArray = dataProtector.Protect(token.ToByteArray());

            TimeSpan expireTimeSpan = (token.Expires.Kind == DateTimeKind.Utc ? token.Expires.ToLocalTime() : token.Expires).Subtract(DateTime.Now);

            httpContext.Response.Cookies.Append(TokenCookieName, Convert.ToBase64String(tokenByteArray), new CookieOptions {
                Expires = DateTimeOffset.Now.Add(expireTimeSpan).AddDays(1), Secure = IsHttpRequestSecure(httpContext.Request), SameSite = SameSiteMode.None
            });
        }
Exemplo n.º 7
0
        public ActionResult <IEnumerable <Student> > Get()
        {
            //var protector = DataProtectionProvider.CreateProtector("ProtectResourceId");
            var protectorA = DataProtectionProvider.CreateProtector("A");
            var protectorB = DataProtectionProvider.CreateProtector("B");
            var protector  = DataProtectionProvider.CreateProtector("C");

            var result = students.Select(s => new Student
            {
                Id   = protector.Protect(s.Id),
                Name = s.Name
            });

            return(result.ToList());
        }
Exemplo n.º 8
0
        private void TimeLimitedDataProtectorTest()
        {
            //当使用Unprotect方法解密时,如果密文已经过期,则同样会抛出CryptographicException异常
            var protector = DataProtectionProvider.CreateProtector("testing").ToTimeLimitedDataProtector();
            var content   = protector.Protect("Hello", DateTimeOffset.Now.AddMinutes(10));

            try
            {
                var rawContent = protector.Unprotect(content, out DateTimeOffset expiration);
            }
            catch (CryptographicException ex)
            {
                Logger.LogError(ex.Message, ex);
            }

            /*
             * Microsoft.AspNetCore.DataProtection包中还提供了EphemeralDataProtectionProvider类,作为IDataProtectionProvider接口的一个实现,
             * 它的加密和解密功能具有“一次性”的特点,当密文不需要持久化时,可以使用这种方式。所有的键都存储在内存中,且每个EphemeralDataProtectionProvider实例都有自己的主键。
             */
        }