Esempio n. 1
0
        public async Task Run()
        {
            const string stringToProtect = "AccessToken";

            // Note how expiration time is specified in call to Protect
            string protectedPayload = protector.Protect(stringToProtect, TimeSpan.FromSeconds(1));

            Console.WriteLine($"Ciphertext: {protectedPayload}");

            string unprotectedPayload = protector.Unprotect(protectedPayload);

            Console.WriteLine($"Plaintext: {unprotectedPayload}");

            // Try unprotecting after expiration time -> has to fail
            await Task.Delay(TimeSpan.FromSeconds(2));

            try
            {
                protector.Unprotect(protectedPayload);
                throw new InvalidOperationException("Expected crypto exception did not happen!");
            }
            catch (CryptographicException)
            {
                Console.WriteLine("Could not unprotect after protection expired.");
            }
        }
Esempio n. 2
0
        /// <summary>
        /// 导出用户
        /// </summary>
        /// <param name="queryInput"></param>
        /// <returns></returns>
        public async Task <UserExcelOutput> Export(UserQueryInput queryInput)
        {
            var query = queryInput.Adapt <UserQuery>();
            var users = await _userRep.GetListAsync(query);

            var exportData = users.Select(a => new Dictionary <string, string> {
                { "姓名", a.Name },
                { "性别", a.Gender.ToDescription() },
                { "出生日期", a.Birthday.ToDateTimeString() },
                { "手机号", a.Phone },
                { "邮箱", a.Email },
                { "微信", a.WeChat },
                { "状态", a.Enabled.IsTrue()?"启用":"注销" },
                { "最后登录时间", a.LastLoginTime.ToDateTimeString() },
                { "最后登录地点", a.LastLoginIP }
            });

            string fileName = $"{Guid.NewGuid()}.xlsx";
            string rootPath = _appSettings.FilePath.ExportExcelPath;

            H_File.CreateDirectory(rootPath);
            string filePath = Path.Combine(rootPath, $"{fileName}");

            await H_Excel.ExportByEPPlus(filePath, exportData);

            return(new UserExcelOutput {
                FileName = fileName, FileId = _protector.Protect(fileName.Split('.')[0], TimeSpan.FromSeconds(5))
            });
        }
Esempio n. 3
0
        public void DoesNotParseMarkersWithUnknownComponentTypeAssembly()
        {
            // Arrange
            var missingUnknownComponentTypeMarker = CreateMarkers(typeof(TestComponent));

            missingUnknownComponentTypeMarker[0].Descriptor = _protector.Protect(
                SerializeComponent("UnknownAssembly", "System.String"),
                TimeSpan.FromSeconds(30));

            var markers = SerializeMarkers(missingUnknownComponentTypeMarker);
            var serverComponentDeserializer = CreateServerComponentDeserializer();

            // Act & assert
            Assert.False(serverComponentDeserializer.TryDeserializeComponentDescriptorCollection(markers, out var descriptors));
            Assert.Empty(descriptors);
        }
        public string Protect(string input)
        {
            // protect the payload
            string protectedPayload = _timeLimitedProtector.Protect(input, lifetime: TimeSpan.FromSeconds(50));

            return(protectedPayload);
        }
        public IActionResult Projects()
        {
            var user1    = new { UserName = "******", Name = "桂素伟", Role = "admin" };
            var code1    = _timeLimitedDataProtector.Protect(Newtonsoft.Json.JsonConvert.SerializeObject(user1), TimeSpan.FromSeconds(10));
            var project1 = new Project {
                Name = "项目一", Url = $"http://localhost:5000/login?code={code1}", Code = code1
            };

            var user2    = new { UserName = "******", Name = "谁是谁", Role = "system" };
            var code2    = _timeLimitedDataProtector.Protect(Newtonsoft.Json.JsonConvert.SerializeObject(user2), TimeSpan.FromSeconds(10));
            var project2 = new Project {
                Name = "项目二", Url = $"http://localhost:5001/login?code={code2}", Code = code2
            };

            return(new JsonResult(new Project[] { project1, project2 }));
        }
        public ActionResult <string> Get()
        {
            // var endstring = _dataProtector.Protect("桂素伟");
            var endstring = _timeLimitedDataProtector.Protect("桂素伟", TimeSpan.FromSeconds(54000));

            return(endstring);
        }
Esempio n. 7
0
        public IActionResult Create([FromBody] SecretItem item)
        {
            if (item == null)
            {
                return(BadRequest());
            }

            if (item.Value == null)
            {
                return(Ok());
            }

            var token = Hash.GetSecureToken(_rndProvider);


            if (item.TimeToLive == null)
            {
                // defaults to 5 minutes
                item.TimeToLive = "5";
            }

            var lifespan       = TimeSpan.FromMinutes(Convert.ToInt32(item.TimeToLive));
            var protectedValue = _protector.Protect(item.Value, lifespan);

            _context.SecretItems.Add(new SecretItem {
                Value = protectedValue, Token = token, ExpiredBy = DateTime.Now + lifespan
            });
            _context.SaveChanges();
            var link = $"https://{this.Request.Host}/api/secret/" + token;

            return(Ok(link));
        }
        public async Task <ApiResult <string> > RedirectToDownloadDocument(string documentId)
        {
            var currentUser = await userService.GetCurrentUser();

            var encryptedData = dataProtector.Protect($"{documentId}_{currentUser.Id}", DateTimeOffset.UtcNow.AddMinutes(10));

            return(ApiResult.SuccessResultWithData(Url.Action("GetDocumentContent", new { encryptedData })));
        }
Esempio n. 9
0
    public Task <string> SetAsync(AccountLinkingState state, DateTimeOffset?expiration = default)
    {
        DateTimeOffset exp                 = expiration ?? DateTimeOffset.Now + _lifeSpan;
        var            stateString         = JsonSerializer.Serialize(state);
        var            accountLinkingState = _dataProtector.Protect(stateString, exp);

        return(Task.FromResult(accountLinkingState));
    }
            public byte[] Protect(byte[] plaintext)
            {
                if (plaintext == null)
                {
                    throw new ArgumentNullException(nameof(plaintext));
                }

                return(_innerProtector.Protect(plaintext, Expiration));
            }
        /// <summary>
        /// Veri Şifreleme
        /// </summary>
        /// <param name="value">Şifrelenecek veri</param>
        /// <param name="minute">Şifrelenecek verinin süresi</param>
        /// <returns>Şifrelenmiş veri</returns>
        public string Protect(string value, int minute = 0)
        {
            if (0 >= minute)
            {
                return(_dataProtector.Protect(value));
            }

            return(_timeLimitedDataProtector.Protect(value, TimeSpan.FromMinutes(minute)));
        }
Esempio n. 12
0
        public async Task <string> Authorize(Uri serverUrl)
        {
            var headers = httpContextAccessor.HttpContext.Request.Headers;
            var base64EncodedCredentials = headers[AuthorizationHeader].ToString().Substring("Basic ".Length).Trim();
            var credentials = new Credentials(base64EncodedCredentials);

            await VerifyCredentials(serverUrl, credentials);

            var protectedPayload = dataProtector.Protect(credentials.Password, TimeSpan.FromDays(1));

            return(protectedPayload);
        }
Esempio n. 13
0
        public byte[] EncryptStream(Stream dataStream)
        {
            using (var mStream = new MemoryStream())
            {
                // TODO: Check if we can run this with one stream only
                dataStream.Position = 0;
                dataStream.CopyTo(mStream);
                var bytesData = mStream.ToArray();

                // TODO: Make time configurable parameter or at least const
                return(_protector.Protect(bytesData, TimeSpan.FromMinutes(5)));
            }
        }
        /// <summary>
        /// Cryptographically protects a piece of plaintext data, expiring the data after
        /// the specified amount of time has elapsed.
        /// </summary>
        /// <param name="protector">The protector to use.</param>
        /// <param name="plaintext">The plaintext data to protect.</param>
        /// <param name="lifetime">The amount of time after which the payload should no longer be unprotectable.</param>
        /// <returns>The protected form of the plaintext data.</returns>
        public static byte[] Protect(this ITimeLimitedDataProtector protector, byte[] plaintext, TimeSpan lifetime)
        {
            if (protector == null)
            {
                throw new ArgumentNullException(nameof(protector));
            }

            if (plaintext == null)
            {
                throw new ArgumentNullException(nameof(plaintext));
            }

            return(protector.Protect(plaintext, DateTimeOffset.UtcNow + lifetime));
        }
        // GET: Products
        public async Task <IActionResult> Index()
        {
            var products = await _context.Products.ToListAsync();

            /*
             * Protect: Koru
             * UnProtect: Korumayı Kaldır
             */
            products.ForEach((product) =>
            {
                //product.EncryptedId = _dataProtector.Protect($"{product.Id}"); //Zaman bağımsız şifreleme
                product.EncryptedId = _timeLimitedDataProtector.Protect($"{product.Id}", TimeSpan.FromSeconds(20)); //Zaman bağımlı şifreleme (Tarih, Saat, Dakika, Saniye)
            });

            return(View(products));
        }
Esempio n. 16
0
        private (int sequence, string payload) CreateSerializedServerComponent(
            ServerComponentInvocationSequence invocationId,
            Type rootComponent)
        {
            var sequence = invocationId.Next();

            var serverComponent = new ServerComponent(
                sequence,
                rootComponent.Assembly.GetName().Name,
                rootComponent.FullName,
                invocationId.Value);

            var serializedServerComponent = JsonSerializer.Serialize(serverComponent, ServerComponentSerializationSettings.JsonSerializationOptions);

            return(serverComponent.Sequence, _dataProtector.Protect(serializedServerComponent, ServerComponentSerializationSettings.DataExpiration));
        }
Esempio n. 17
0
        public void RunSample()
        {
            Console.Write("Enter input: ");
            string input = Console.ReadLine();

            // protect the payload
            string protectedPayload = _timeLimitedProtector.Protect(input, lifetime: TimeSpan.FromSeconds(2));

            Console.WriteLine($"Protect returned: {protectedPayload}");

            Thread.Sleep(2000);

            // unprotect the payload
            string unprotectedPayload = _timeLimitedProtector.Unprotect(protectedPayload);

            Console.WriteLine($"Unprotect returned: {unprotectedPayload}");
            Console.ReadLine();
        }
 private static void ProtectParams(JToken token, ITimeLimitedDataProtector protector, ParamsProtectionOptions option)
 {
     if (token is JArray array)
     {
         foreach (var j in array)
         {
             if (array.Parent is JProperty property && j is JValue val)
             {
                 var strJ = val.Value.ToString();
                 if (option.IsParamNeedProtect(property.Name, strJ))
                 {
                     val.Value = protector.Protect(strJ, TimeSpan.FromMinutes(option.ExpiresIn.GetValueOrDefault(10)));
                 }
             }
             else
             {
                 ProtectParams(j, protector, option);
             }
         }
Esempio n. 19
0
    private (int sequence, string payload) CreateSerializedServerComponent(
        ServerComponentInvocationSequence invocationId,
        Type rootComponent,
        ParameterView parameters)
    {
        var sequence = invocationId.Next();

        var(definitions, values) = ComponentParameter.FromParameterView(parameters);

        var serverComponent = new ServerComponent(
            sequence,
            rootComponent.Assembly.GetName().Name,
            rootComponent.FullName,
            definitions,
            values,
            invocationId.Value);

        var serializedServerComponentBytes = JsonSerializer.SerializeToUtf8Bytes(serverComponent, ServerComponentSerializationSettings.JsonSerializationOptions);
        var protectedBytes = _dataProtector.Protect(serializedServerComponentBytes, ServerComponentSerializationSettings.DataExpiration);

        return(serverComponent.Sequence, Convert.ToBase64String(protectedBytes));
    }
Esempio n. 20
0
        public ResultModel <string> GetDownLoadFile(string url)
        {
            var userId = Convert.ToInt32(HttpContext.User.FindFirst("id").Value);
            //根据orderNo 与 会员Id查询 订单信息

            /*
             * 此时为了跟大家演示 下载效果 只需要传参 url即可
             * 真实的业务场景,会根据登录用户,以及业务编号  我们可以根据需求去重写 对应的业务即可即可
             */

            var result = new ResultModel <string>();

            if (string.IsNullOrEmpty(url))
            {
                return(result.Error("请输入文件地址", null));
            }
            string cdipath = Directory.GetCurrentDirectory() + url;

            if (!System.IO.File.Exists(cdipath))
            {
                return(result.Error("文件不存在", null));
            }
            //根据当前登录用户验证 文件相对路径 是否包含userId值
            if (!url.Contains(userId.ToString() + "_"))
            {
                return(result.Error("您当前下载的文件不正确", null));
            }

            /*
             * 真实场景  下载客户文件时,需要根据业务信息动态获取客户源文件名,生成文件名的规则 你们也可以自定义
             * 此处 我会根据切割  地址获取文件名 /MyUpfiles/2020/09/24/55020_04-03-{文件名}_c825733e-3f87-44b5-b002-0fd4d94a94d1.zip
             */
            var getfileName = url.Split('_')[1].ToString();
            var fileKey     = _protector.Protect(getfileName, TimeSpan.FromSeconds(120));

            //fileKey 是根据文件进行加密后的秘钥,有效时间为:120s
            return(result.Success("文件秘钥生成成功", fileKey));
        }
Esempio n. 21
0
 public string GenerateAccessSecret(AccessSecret secret)
 {
    return Convert.ToBase64String(_timeLimitedProtector.Protect(
         Encoding.UTF8.GetBytes(secret.JsonSerialize()),
         new DateTimeOffset(secret.ExpiresTime, TimeSpan.FromHours(8))));
 }
Esempio n. 22
0
        public async Task <ApiResult <string> > VerifyEmailAddress([FromBody] VerifyEmailAddressModel value)
        {
            if (!ModelState.IsValid)
            {
                return(new ApiResult <string>(l, BasicControllerCodes.UnprocessableEntity,
                                              ModelErrors()));
            }

            #region 发送计数、验证是否已经达到上限
            var dailyLimitKey = RedisKeys.Limit_24Hour_Verify_Email + value.Email;

            var _dailyLimit = await redis.Get(dailyLimitKey);

            if (!string.IsNullOrWhiteSpace(_dailyLimit))
            {
                var dailyLimit = int.Parse(_dailyLimit);

                if (dailyLimit > RedisKeys.Limit_24Hour_Verify_MAX_Email)
                {
                    return(new ApiResult <string>(l, UserControllerCodes.VerifyEmailAddress.CallLimited));
                }
            }
            else
            {
                await redis.Set(dailyLimitKey, "0", TimeSpan.FromHours(24));
            }
            #endregion

            #region 验证发送间隔时间是否过快
            //两次发送间隔必须大于指定秒数
            var _lastTimeKey = RedisKeys.LastTime_SendCode_Email + value.Email;

            var lastTimeString = await redis.Get(_lastTimeKey);

            if (!string.IsNullOrWhiteSpace(lastTimeString))
            {
                var lastTime = long.Parse(lastTimeString);

                var now = DateTime.UtcNow.AddHours(8).Ticks;

                var usedTime = (now - lastTime) / 10000000;

                if (usedTime < RedisKeys.MinimumTime_SendCode_Email)
                {
                    return(new ApiResult <string>(l, UserControllerCodes.VerifyEmailAddress.TooManyRequests, string.Empty,
                                                  RedisKeys.MinimumTime_SendCode_Email - usedTime));
                }
            }
            #endregion

            #region 发送验证码
            var verifyCode = random.Next(111111, 999999).ToString();
            // 用加密算法生成具有时效性的密文
            var protectedData = protector.Protect(verifyCode, TimeSpan.FromSeconds(RedisKeys.VerifyCode_Expire_Email));
            var xsmtpapi      = JsonConvert.SerializeObject(new
            {
                to  = new string[] { value.Email },
                sub = new Dictionary <string, string[]>()
                {
                    { "%code%", new string[] { protectedData } },
                }
            });
            await email.SendEmailAsync("邮箱验证", "verify_email", xsmtpapi);

            #endregion

            // 记录发送验证码的时间,用于下次发送验证码校验间隔时间
            await redis.Set(_lastTimeKey, DateTime.UtcNow.AddHours(8).Ticks.ToString(), null);

            // 叠加发送次数
            await redis.Increment(dailyLimitKey);

            return(new ApiResult <string>());
        }
Esempio n. 23
0
 public string ProtectData(string data, DateTimeOffset dateTimeOffset)
 {
     return(_dataProtector.Protect(data, dateTimeOffset));
 }
Esempio n. 24
0
 public ActionResult <object> GetEncriptadoTiempo(string texto)
 {
     return(Ok(_dataProtectorTiempoLimitado.Protect(texto, TimeSpan.FromSeconds(5))));
 }
Esempio n. 25
0
        private string EncryptUserId(string userId)
        {
            var encryptId = dataProtector.Protect(userId);

            return(encryptId);
        }
        public string CreateToken <T>(T payload, TimeSpan lifetime)
        {
            var json = JsonConvert.SerializeObject(payload);

            return(_dataProtector.Protect(json, _dateTimeProvider.Now.Add(lifetime)));
        }