public string Encrypt(string inputText) { if (inputText == null) { throw new ArgumentNullException(nameof(inputText)); } var inputBytes = Encoding.UTF8.GetBytes(inputText); var bytes = _dataProtector.Protect(inputBytes); return(Convert.ToBase64String(bytes)); }
public ActionResult <IEnumerable <string> > Get() { var encripted = _protector.Protect("Apurba"); Console.WriteLine(encripted); var dycripted = _protector.Unprotect(encripted); Console.WriteLine(encripted); return(new string[] { $"Encripted -> Apurba : {encripted}", $"Decripted -> {encripted} : {dycripted}" }); }
public IActionResult GetLog(string app) { var token = dataProtector.Protect(App.Id.ToString()); var url = urlsOptions.BuildUrl($"/api/apps/log/{token}/"); var response = new LogDownloadDto { DownloadUrl = url }; return(Ok(response)); }
public ViewResult Index() { var model = _employeeRepository.GetAllEmployee() .Select(e => { // Encrypt the ID value and store in EncryptedId property e.EncryptedId = protector.Protect(e.Id.ToString()); return(e); }); return(View(model)); }
public string Protect(AuthenticationProperties data, string purpose) { var key = Guid.NewGuid().ToString(); var cacheKey = $"{CacheKeyPrefix}{key}"; var serialized = _serializer.Serialize(data); // Rather than encrypt the full AuthenticationProperties // cache the data and encrypt the key that points to the data _cache.Set(cacheKey, serialized); return(_dataProtector.Protect(key)); }
public ViewResult Index() { var model = _talentRepository.GetTalentList() .Select(t => { t.EncryptedId = _protector.Protect(t.Id.ToString()); return(t); } ); return(View(model)); }
public ProposalMemoryService(IDataProtectionProvider protectionProvider, PurposeStringConstants purposeStringConstants) { protector = protectionProvider.CreateProtector(purposeStringConstants.ConferenceIdQueryString); proposals.Add(new ProposalModel { Id = 1, ConferenceId = 1, EncryptedConferenceId = protector.Protect("1"), Speaker = "Nikolay Filippov", Title = "ASP.NET Core 2.x" }); proposals.Add(new ProposalModel { Id = 2, ConferenceId = 2, EncryptedConferenceId = protector.Protect("2"), Speaker = "John Doe", Title = "Understanding C#" }); }
public string TokenizePath(string path) { var pathParts = path.Split('?'); var parsed = QueryHelpers.ParseQuery(pathParts.Length > 1 ? pathParts[1] : string.Empty); // If no commands or only a version command don't bother tokenizing. if (parsed.Count == 0 || parsed.Count == 1 && parsed.ContainsKey(ImageVersionProcessor.VersionCommand)) { return(path); } var processingCommands = new Dictionary <string, string>(); var otherCommands = new Dictionary <string, string>(); foreach (var command in parsed) { if (_knownCommands.Contains(command.Key)) { processingCommands[command.Key] = command.Value.ToString(); } else { otherCommands[command.Key] = command.Value.ToString(); } } // Using the command values as a key retrieve from cache var key = String.Concat(processingCommands.Values); var queryStringTokenKey = TokenCacheKeyPrefix + key; var queryStringToken = _memoryCache.GetOrCreate(queryStringTokenKey, entry => { entry.SlidingExpiration = TimeSpan.FromHours(5); var json = JsonConvert.SerializeObject(processingCommands); return(_dataProtector.Protect(json)); }); otherCommands["token"] = queryStringToken; var commandCacheKey = CommandCacheKeyPrefix + key; var query = _memoryCache.GetOrCreate(commandCacheKey, entry => { entry.SlidingExpiration = TimeSpan.FromHours(24); return(processingCommands); }); return(QueryHelpers.AddQueryString(pathParts[0], otherCommands)); }
public ViewResult Index() { //查询所有的学生信息 List <Student> model = _studentRepository.GetAllStudents().Select(s => { //加密ID值并存储在EncryptedId属性中 s.EncryptedId = _protector.Protect(s.Id.ToString()); return(s); }).ToList(); //将学生列表传递到视图 return(View(model)); }
public IActionResult Index() { //LaunchProcess(); var model = _employeeRepository.GetAllEmployees() .Select(e => { e.EncryptedId = protector.Protect(e.Id.ToString()); return(e); }); return(View(model)); }
/// <summary> /// GetNewTokenAsync /// </summary> /// <param name="expiredSeconds"></param> /// <returns></returns> /// <exception cref="CacheException"></exception> public async Task <string> GetNewTokenAsync(int expiredSeconds) { string token = _prefix + Guid.NewGuid().ToString(); await _cache.SetStringAsync( token, _defaultValue, TimeUtil.UtcNowTicks, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(expiredSeconds) }).ConfigureAwait(false); return(_dataProtector.Protect(token)); }
public string Protect(AuthenticationProperties data, string purpose) { var key = Guid.NewGuid().ToString(); var cacheKey = $"{options.Prefix}{key}"; var serialized = options.Serializer.Serialize(data); cache.Set(cacheKey, serialized, options.CacheOptions); var p = dataProtector.Protect(key); return(p); }
/// <summary> /// encrypts generic data /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <returns></returns> public string Encrypt <T>(T data) { _logger.LogDebug(new { action = nameof(Encrypt) }.ToString()); var dataString = JsonConvert.SerializeObject(data); var protectedDataString = _protector.Protect(dataString); return(protectedDataString); }
//public string LoginHint { get; set; } //public string AuthenticationMethod { get; set; } public string Protect(int ttl, IDataProtector protector) { ValidTo = DateTime.UtcNow.AddSeconds(ttl); var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; var json = JsonConvert.SerializeObject(this, settings); return protector.Protect(json, "signinmessage"); }
public async Task <ViewResult> Index() { // Get all the employee but populate their Encrypted with an encryped string IEnumerable <Employee> model = _employeeRepository.GetAllEmployee() .Select(e => { e.EncryptedId = protector.Protect(e.Id.ToString()); return(e); }); return(View(model)); }
public void RunSample() { Console.Write("Enter input:"); string input = Console.ReadLine(); string protectedPayload = _protector.Protect(input); Console.WriteLine($"protect returned: {protectedPayload}"); string unprotectedPayload = _protector.Unprotect(protectedPayload); Console.WriteLine($"unprotect returned: {unprotectedPayload}"); }
public string Serialize(AntiforgeryToken token) { if (token == null) { throw new ArgumentNullException(nameof(token)); } var serializationContext = _pool.Get(); try { var writer = serializationContext.Writer; writer.Write(TokenVersion); writer.Write(token.SecurityToken !.GetData()); writer.Write(token.IsCookieToken); if (!token.IsCookieToken) { if (token.ClaimUid != null) { writer.Write(true /* isClaimsBased */); writer.Write(token.ClaimUid.GetData()); } else { writer.Write(false /* isClaimsBased */); writer.Write(token.Username !); } writer.Write(token.AdditionalData); } writer.Flush(); var stream = serializationContext.Stream; var bytes = _cryptoSystem.Protect(stream.ToArray()); var count = bytes.Length; var charsRequired = WebEncoders.GetArraySizeRequiredToEncode(count); var chars = serializationContext.GetChars(charsRequired); var outputLength = WebEncoders.Base64UrlEncode( bytes, offset: 0, output: chars, outputOffset: 0, count: count); return(new string(chars, startIndex : 0, length : outputLength)); } finally { _pool.Return(serializationContext); } }
public IdentityResult RegisterUser(RegisterUserDTO sent, DateTime?date = null) { if (date.HasValue == false) { date = DateTime.Now; } var user = new User() { UserName = sent.Email, FirstName = protector.Protect(sent.FirstName), LastName = protector.Protect(sent.LastName), Email = sent.Email, PhoneNumber = protector.Protect(sent.PhoneNumber), Activity = new List <Activity> { new Activity() { Date = date.Value, Type = ActivityType.AccountCreate, Message = "Account created" } }, DateCreated = date.Value }; return(userManager.CreateAsync(user, sent.Password).Result); }
private async Task <IspitniTerminVM> BuildSingleIspitniTerminVM(int ispitniTerminId) { var ispitniTermin = await _context.IspitniTermini.FindAsync(ispitniTerminId); if (ispitniTermin == null) { return(new IspitniTerminVM()); } return(new IspitniTerminVM { Id = _protector.Protect(ispitniTermin.Id.ToString()), DatumIspita = ispitniTermin.DatumIspita, BrojStudenataNepolozeno = ispitniTermin.BrojNepolozenih, BrojPrijavljenihStudenata = ispitniTermin.BrojPrijavljenihStudenata, EvidentiraniRazultati = ispitniTermin.EvidentiraniRezultati }); //new IspitniTerminVM //{ // Id = _protector.Protect(t.Id.ToString()), // DatumIspita = t.DatumIspita, // BrojStudenataNepolozeno = t.BrojNepolozenih, // BrojPrijavljenihStudenata = t.BrojPrijavljenihStudenata, // EvidentiraniRazultati = t.EvidentiraniRezultati //} }
public static void Apply(this CommandResult commandResult, IOwinContext context, IDataProtector dataProtector) { if (commandResult == null) { throw new ArgumentNullException(nameof(commandResult)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } context.Response.ContentType = commandResult.ContentType; context.Response.StatusCode = (int)commandResult.HttpStatusCode; if (commandResult.Location != null) { context.Response.Headers["Location"] = commandResult.Location.OriginalString; } if (commandResult.Content != null) { // Remove value set by other middleware and let the host calculate // a new value. See issue #295 for discussion on this. context.Response.ContentLength = null; context.Response.Write(commandResult.Content); } if (commandResult.TerminateLocalSession) { context.Authentication.SignOut(); } if (!string.IsNullOrEmpty(commandResult.SetCookieData)) { var protectedData = HttpRequestData.EscapeBase64CookieValue( Convert.ToBase64String( dataProtector.Protect( Encoding.UTF8.GetBytes( commandResult.SetCookieData)))); context.Response.Cookies.Append( commandResult.SetCookieName, protectedData, new CookieOptions() { HttpOnly = true, }); } }
public static void Apply(this CommandResult commandResult, IOwinContext context, IDataProtector dataProtector) { if (commandResult == null) { throw new ArgumentNullException(nameof(commandResult)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } context.Response.ContentType = commandResult.ContentType; context.Response.StatusCode = (int)commandResult.HttpStatusCode; if (commandResult.Location != null) { context.Response.Headers["Location"] = commandResult.Location.OriginalString; } if (commandResult.Content != null) { // Remove value set by other middleware and let the host calculate // a new value. See issue #295 for discussion on this. context.Response.ContentLength = null; context.Response.Write(commandResult.Content); } if(commandResult.TerminateLocalSession) { context.Authentication.SignOut(); } if(!string.IsNullOrEmpty(commandResult.SetCookieData)) { var protectedData = HttpRequestData.EscapeBase64CookieValue( Convert.ToBase64String( dataProtector.Protect( Encoding.UTF8.GetBytes( commandResult.SetCookieData)))); context.Response.Cookies.Append( commandResult.SetCookieName, protectedData, new CookieOptions() { HttpOnly = true, }); } }
public ActionResult Encriptar() { var textoPlano = "Felipe Gavilán"; var textoCifrado = dataProtector.Protect(textoPlano); var textoDesencriptado = dataProtector.Unprotect(textoCifrado); return(Ok(new { textoPlano = textoPlano, textoCifrado = textoCifrado, textoDesencriptado = textoDesencriptado })); }
private IEnumerable <Region> GetRegions() { string[] regionNames = new[] { "Taipei", "Taichung", "Chiayi", "Kaohsiung", "Taitung" }; return(Enumerable.Range(0, regionNames.Length).Select(index => new Region { EncryptedId = _protector.Protect(index.ToString()), Id = index, Name = regionNames[index], WeatherForecast = GetWeatherForecast() }).ToArray()); }
public Task <string> ProtectAsync(string key) { try { var value = _protector.Protect(key); return(Task.FromResult(value)); } catch (Exception ex) { _logger.LogError(ex, "Exception writing protected key"); throw; } }
public IActionResult Index() { //return Json(new { test = _employeeRepository.GetEmployee(1).Name }); //return View(); //return Json(new { yo="yooo",id=1337}); var model = _employeeRepository.GetAllEmployees().Select(e => { e.EncryptedId = protector.Protect(e.Id.ToString()); return(e); }); return(View(model)); }
public async Task <Merchant> AddAsync(Merchant merchant) { merchant.Id = Guid.NewGuid(); string generated_key = String.Concat("key_", GenerateRandomCryptographicKey(32)); merchant.Secret_Key = _protector.Protect(generated_key); await _merchants.AddAsync(merchant); await SaveChangesAsync(); merchant.Secret_Key = generated_key; return(merchant); }
//public string LoginHint { get; set; } //public string AuthenticationMethod { get; set; } public string Protect(int ttl, IDataProtector protector) { ValidTo = DateTime.UtcNow.AddSeconds(ttl); var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; var json = JsonConvert.SerializeObject(this, settings); return(protector.Protect(json, "signinmessage")); }
public async Task <IActionResult> Create(Contato contato) { if (ModelState.IsValid) { contato.Senha = _protectorProvider.Protect(contato.Senha); _context.Add(contato); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(contato)); }
public IActionResult Create(Contato contato) { if (!ModelState.IsValid) { return(View(contato)); } contato.Senha = _protectorProvider.Protect(contato.Senha); _contexto.Add(contato); _contexto.SaveChanges(); return(RedirectToAction("Index")); }
[AllowAnonymous] // <= AllownAnonymous attribute, membuat anonymous user bisa mengakses route tersebut public ViewResult Index() { var model = _employeeRepository.GetAllEmployee() .Select(e => { // kita gunakan method Proect() untuk melakukan enksripsi // kita menyimpan enksripsi employee id ke properti enksripsiId e.EnkripsiId = protector.Protect(e.Id.ToString()); return(e); }); return(View(model)); }
public Key WriteValue(Key key) { ValidateAccess(FileAccess.Write); string encryptedValue = _dataProtector.Protect(key.Value); return(new Key { Name = key.Name, Value = encryptedValue, IsEncrypted = true }); }
/// <summary> /// Protect a string value. /// </summary> /// <param name="protector"> /// The data protector. /// </param> /// <param name="unprotectedValue"> /// The value to protect. /// </param> /// <returns> /// The protected value (Base64-encoded). /// </returns> public static string Protect(this IDataProtector protector, string unprotectedValue) { if (protector == null) { throw new ArgumentNullException(nameof(protector)); } byte[] unprotectedData = Encoding.Unicode.GetBytes(unprotectedValue); byte[] protectedData = protector.Protect(unprotectedData); string protectedValue = Encoding.Unicode.GetString(protectedData); return(protectedValue); }
//public string LoginHint { get; set; } //public string AuthenticationMethod { get; set; } public string Protect(int ttl, IDataProtector protector) { ValidTo = DateTime.UtcNow.AddSeconds(ttl); var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore, }; var json = JsonConvert.SerializeObject(this, settings); Logger.DebugFormat("Protecting signin message: {0}", json); return protector.Protect(json, "signinmessage"); }
private static void ApplyCookies(CommandResult commandResult, IOwinContext context, IDataProtector dataProtector) { var serializedCookieData = commandResult.GetSerializedRequestState(); if (serializedCookieData != null) { var protectedData = HttpRequestData.ConvertBinaryData( dataProtector.Protect(serializedCookieData)); context.Response.Cookies.Append( commandResult.SetCookieName, protectedData, new CookieOptions() { HttpOnly = true, }); } commandResult.ApplyClearCookie(context); }
internal static byte[] EncryptKey(IDataProtector protector, RSAParameters parameters, string usage) { if (protector == null) { throw new ArgumentNullException(nameof(protector)); } if (string.IsNullOrEmpty(usage)) { throw new ArgumentNullException(nameof(usage)); } using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) { writer.Write(/* version: */ 2); writer.Write(/* algorithm: */ "RSA"); writer.Write(/* usage: */ usage); // Serialize the RSA parameters to the key file. writer.Write(parameters.D.Length); writer.Write(parameters.D); writer.Write(parameters.DP.Length); writer.Write(parameters.DP); writer.Write(parameters.DQ.Length); writer.Write(parameters.DQ); writer.Write(parameters.Exponent.Length); writer.Write(parameters.Exponent); writer.Write(parameters.InverseQ.Length); writer.Write(parameters.InverseQ); writer.Write(parameters.Modulus.Length); writer.Write(parameters.Modulus); writer.Write(parameters.P.Length); writer.Write(parameters.P); writer.Write(parameters.Q.Length); writer.Write(parameters.Q); // Encrypt the key using the data protection block. return protector.Protect(stream.ToArray()); } }