Ejemplo 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.");
            }
        }
Ejemplo n.º 2
0
        public async Task <FileStreamResult> GetDocumentContent(string encryptedData)
        {
            string decryptedData;

            try
            {
                decryptedData = dataProtector.Unprotect(encryptedData);
            }
            catch (CryptographicException)
            {
                throw new ApiServiceException("Download data is not valid");
            }

            var index      = decryptedData.LastIndexOf('_');
            var documentId = decryptedData.Substring(0, index);
            var userId     = new Guid(decryptedData.Substring(index + 1));
            var document   = await documentStorage.GetDocument(
                new DocumentIdentity(documentId, userId),
                CancellationToken.None);

            contentTypeProvider.TryGetContentType(document.FileName, out var contentType);

            return(new FileStreamResult(
                       await document.Content.OpenReadStream(CancellationToken.None),
                       contentType ?? "application/octet-stream")
            {
                FileDownloadName = document.FileName,
                EnableRangeProcessing = true
            });
        }
Ejemplo n.º 3
0
        private async Task <bool> IsTokenValid(string token)
        {
            try
            {
                using (var scope = await _shellHost.GetScopeAsync(_shellSettingsManager.GetSettings(ShellHelper.DefaultShellName)))
                {
                    var dataProtectionProvider = scope.ServiceProvider.GetService <IDataProtectionProvider>();
                    ITimeLimitedDataProtector dataProtector = dataProtectionProvider.CreateProtector("Tokens").ToTimeLimitedDataProtector();

                    var tokenValue = dataProtector.Unprotect(token, out var expiration);

                    if (_clock.UtcNow < expiration.ToUniversalTime())
                    {
                        if (_shellSettings.Secret == tokenValue)
                        {
                            return(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in decrypting the token");
            }

            return(false);
        }
        public string Unprotect(string protectedPayload)
        {
            // protect the payload
            string unprotectedPayload = _timeLimitedProtector.Unprotect(protectedPayload);

            return(unprotectedPayload);
        }
        public IActionResult Read(string code)
        {
            DateTimeOffset dateTimeOffset;
            var            result = _timeLimitedDataProtector.Unprotect(code, out dateTimeOffset);

            return(Content($"{result}:{dateTimeOffset.LocalDateTime}"));
        }
            public byte[] Unprotect(byte[] protectedData)
            {
                if (protectedData == null)
                {
                    throw new ArgumentNullException(nameof(protectedData));
                }

                return(_innerProtector.Unprotect(protectedData, out Expiration));
            }
        /// <summary>
        /// Veri Şifre Çözücü
        /// </summary>
        /// <param name="value">Şifrelenmiş veri</param>
        /// <param name="isTimeLimited">Şifrelenmiş veriye bir süre verilmiş mi?</param>
        /// <returns>Şifresi çözülmüş veri</returns>
        public string Unprotect(string value, bool isTimeLimited)
        {
            if (!isTimeLimited)
            {
                return(_dataProtector.Unprotect(value));
            }

            return(_timeLimitedDataProtector.Unprotect(value));
        }
Ejemplo n.º 8
0
 public byte[] DecryptStream(MemoryStream 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();
         return(_protector.Unprotect(bytesData));
     }
 }
Ejemplo n.º 9
0
    public Task <(AccountLinkingState state, DateTimeOffset expiration)> GetAsync(string accountLinkingState)
    {
        string unprotectedStateString = _dataProtector.Unprotect(accountLinkingState, out DateTimeOffset expiration);

        var stateObject = JsonSerializer.Deserialize <AccountLinkingState>(unprotectedStateString);

        if (stateObject == default)
        {
            _logger.LogWarning("Failed to deserialize the state object");
            throw new Exception("Verification failed, state object invalid");
        }
        return(Task.FromResult((stateObject, expiration)));
    }
 public ActionResult <string> Get(string endstring)
 {
     try
     {
         //return _dataProtector.Unprotect(endstring);
         DateTimeOffset dateTimeOffset;
         var            result = _timeLimitedDataProtector.Unprotect(endstring, out dateTimeOffset);
         return($"{result},{dateTimeOffset.LocalDateTime}");
     }
     catch (CryptographicException exc)
     {
         return($"{exc.Message},当前时间:{DateTime.Now}");
     }
 }
Ejemplo n.º 11
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();
        }
        // GET: Products/Details/5
        public async Task <IActionResult> Details(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return(NotFound());
            }

            // int decryptedId = int.Parse(_dataProtector.Unprotect(id)); //Zaman bağımsız şifre çözme işlemi
            int decryptedId = int.Parse(_timeLimitedDataProtector.Unprotect(id)); //Zaman bağımlı şifre çözme

            var product = await _context.Products
                          .FirstOrDefaultAsync(m => m.Id == decryptedId);

            if (product == null)
            {
                return(NotFound());
            }

            return(View(product));
        }
Ejemplo n.º 13
0
        public bool TryDecryptToken <T>(string token, out T payload)
        {
            payload = default;

            try
            {
                var json = _dataProtector.Unprotect(token, out var expiration);

                if (_clock.UtcNow < expiration.ToUniversalTime())
                {
                    payload = JsonConvert.DeserializeObject <T>(json);
                    return(true);
                }
            }
            catch
            {
            }

            return(false);
        }
        public bool TryDecryptToken <T>(string token, out T payload)
        {
            payload = default;

            try
            {
                var json = _dataProtector.Unprotect(token, out var expiration);

                if (_dateTimeProvider.Now < expiration.ToUniversalTime())
                {
                    payload = JsonConvert.DeserializeObject <T>(json);
                    return(true);
                }
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch
            {
            }

            return(false);
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> Login(string code)
        {
            try
            {
                //单点登录系统中的过期时间
                DateTimeOffset dateTimeOffset;
                var            result  = _timeLimitedDataProtector.Unprotect(code, out dateTimeOffset);
                var            userPro = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(result);

                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Sid, userPro.UserName.ToString()));
                identity.AddClaim(new Claim(ClaimTypes.Role, userPro.Role.ToString()));
                identity.AddClaim(new Claim(ClaimTypes.Name, userPro.Name.ToString()));
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

                return(Redirect("/"));
            }
            catch (CryptographicException)//过期
            {
                return(Redirect("/home/error"));
            }
        }
Ejemplo n.º 16
0
        public IActionResult GetRawFile(string fileKey, string url)
        {
            try
            {
                /*
                 * 文件下载时,我会先根据 文件路径 创建一个文件key,然后设置他的过期时间
                 * 当前为了跟大家演示效果,为了读取 加密的url,所有 将url进行传入,
                 * 真实业务场景,会传入一个 订单编号 或者业务编号去动态查询 上传地址
                 */

                //通过订单编号-orderNo 查询客户上传的文件路径
                var    rawFileInfo = _protector.Unprotect(fileKey);
                string cdipath     = Directory.GetCurrentDirectory() + url;
                var    stream      = System.IO.File.OpenRead(cdipath);
                stream.Position = 0;
                return(File(stream, "application/oct-stream", rawFileInfo));
            }
            catch
            {
                return(StatusCode(401));
            }
        }
Ejemplo n.º 17
0
        public (bool result, string message) VerifyAccessSecret(AccessSecret secret, string accessKey, string accessSecret)
        {
            try
            {
                if (secret.ExpiresTime < DateTime.Now.Date)
                    return (false, "服务时间已到期");

                var deserializeSecret = Encoding.UTF8.GetString(_timeLimitedProtector.Unprotect(Convert.FromBase64String(accessSecret))).JsonDeserialize<AccessSecret>();

                if (deserializeSecret.Key != accessKey)
                    return (false, "AccessKey、AccessSecret异常");

                if (deserializeSecret.Version != secret.Version)
                    return (false, "AccessKey、AccessSecret版本错误");

                return (true, "");
            }
            catch (CryptographicException ex)
            {
                return (false, ex.Message);
            }

        }
Ejemplo n.º 18
0
        public IActionResult GetByToken(string token)
        {
            var id = _context.SecretItems
                     .FirstOrDefault(b => b.Token == token);

            try
            {
                var item        = _context.SecretItems.Find(id.Id);
                var secretValue = item.Value;
                _context.SecretItems.Remove(item);
                _context.SaveChanges();

                return(Ok(_protector.Unprotect(secretValue)));
            }
            catch (NullReferenceException)
            {
                return(NotFound());
            }

            catch (CryptographicException)
            {
                return(Ok("This secret has expired"));
            }
        }
Ejemplo n.º 19
0
        private string DecryptUserId(string encryptUserId)
        {
            var deCryptId = dataProtector.Unprotect(encryptUserId);

            return(deCryptId);
        }
Ejemplo n.º 20
0
 public ActionResult <object> GetDesencriptadoTiempo(string textoEncriptado)
 {
     return(Ok(_dataProtectorTiempoLimitado.Unprotect(textoEncriptado)));
 }
Ejemplo n.º 21
0
 public string Decrypt(Credentials credentials)
 {
     return(dataProtector.Unprotect(credentials.Password));
 }