public void Update(HttpContextBase context, string name, T content) { var cookie = context.Request.Cookies[name]; if (cookie != null) { var cookieContent = JsonConvert.SerializeObject(content); var encodedContent = Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(cookieContent))); cookie.Value = encodedContent; context.Response.SetCookie(cookie); } }
public static HttpCookie SetCookie(string accountName, bool rememberMe) { HttpCookie cookie_user = new HttpCookie("user"); var cookieText = Encoding.UTF8.GetBytes(accountName); var encryptedValue = Convert.ToBase64String(MachineKey.Protect(cookieText, "protectedCookie")); cookie_user.Values["user_accountname"] = encryptedValue; if (rememberMe == true) { cookie_user.Expires = DateTime.Now.AddDays(7); } return(cookie_user); }
byte[] TokenToBytes(SessionSecurityToken token) { if (token == null) { return(null); } using (var ms = new MemoryStream()) { var f = new BinaryFormatter(); f.Serialize(ms, token); var bytes = ms.ToArray(); bytes = MachineKey.Protect(bytes, Purpose); return(bytes); } }
public EncrypDecryptModel GetStrValue() { EncrypDecryptModel encrypDecrypt = new EncrypDecryptModel(); string encryptStr = "MyProtectionKey"; byte[] x = Encoding.ASCII.GetBytes(encryptStr); var encryted = MachineKey.Protect(x); var decrypt = Encoding.ASCII.GetString(MachineKey.Unprotect(encryted)); encrypDecrypt.protectedPayload = Encoding.ASCII.GetString(encryted); encrypDecrypt.unprotectedPayload = decrypt.ToString(); return(encrypDecrypt); }
/// <summary> /// Creates a user profile, which is stored on disk. Password will be encrypted using machine key. Created profile will be set as active profile. /// </summary> /// <param name="email">Email of user</param> /// <param name="password">Password of user</param> public void CreateProfile(string email, string password) { Profile profile = new Profile(); profile.Email = email.ToLower(); //Encrypt password var passwordData = Encoding.UTF8.GetBytes(password); var encryptedData = MachineKey.Protect(passwordData); profile.Password = Convert.ToBase64String(encryptedData); profile.Save(); _Cache.Remove(Constants.CACHE_PROFILEJSON); _CurrentProfile = profile; _Http = new HttpHelper(_CurrentProfile); }
public void Create(HttpContextBase context, string name, T content, int expireDays) { var cookieContent = JsonConvert.SerializeObject(content); var encodedContent = Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(cookieContent))); var userCookie = new HttpCookie(name, encodedContent) { Expires = DateTime.Now.AddDays(expireDays), Secure = true, HttpOnly = true, }; context.Response.Cookies.Add(userCookie); }
/// <summary> /// Write this item to a folder. /// </summary> /// <param name="folderPath">The folder path.</param> /// <param name="telemetry">The cache item telemetry.</param> private void Save(string folderPath, CacheItemTelemetry telemetry) { if (telemetry.Request != null) { var request = CrmJsonConvert.SerializeObject(telemetry.Request); var key = request.GetHashCode(); var filename = string.Format(this.Settings.FilenameFormat, key); var fullPath = Path.Combine(folderPath, filename); var bytes = MachineKey.Protect(Encoding.UTF8.GetBytes(request), this.Settings.GetType().ToString()); ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Writing: " + fullPath); this.Settings.AppDataRetryPolicy.WriteAllBytes(fullPath, bytes); } }
/// <summary> /// Protects the specified data by encrypting. /// </summary> /// <param name="data">The data to be encrypted.</param> /// <returns>Base64 encoded string that represented the protected data.</returns> /// <exception cref="ArgumentException"> /// <paramref name="data"/> is empty or null. /// </exception> public string Protect(string data) { byte[] buffer; data.AssertNotEmpty(nameof(data)); try { buffer = Encoding.ASCII.GetBytes(data); return(Convert.ToBase64String(MachineKey.Protect(buffer, purposes))); } finally { buffer = null; } }
public ActionResult Index() { var helloProtected = MachineKey.Protect(Encoding.UTF8.GetBytes("hello"), "testprotector"); var base64HelloProtected = Convert.ToBase64String(helloProtected); lock (lockObjet) { System.IO.File.WriteAllText("c:\\keys\\protectedFile.txt", base64HelloProtected); } if (!MyDataProtectionStartup.DataProtectionLoaded) { return(Json("Dataprotection not set", JsonRequestBehavior.AllowGet)); } return(Json(base64HelloProtected, JsonRequestBehavior.AllowGet)); }
private Dictionary <string, object> Crypt(Dictionary <string, object> item) { for (int index = 0; index < item.Count; index++) { var candidate = item.ElementAt(index); if (candidate.Key.ToUpperInvariant().Contains("PASSWORD") || candidate.Key.ToUpperInvariant().Contains("SECRET")) { var bytes = Encoding.UTF8.GetBytes(candidate.Value.ToString()); item[candidate.Key] = Encoding.UTF8.GetString(MachineKey.Protect(bytes, "ScrudFactory")); } } return(item); }
// Notification raised after ADAL accessed the cache. // If the HasStateChanged flag is set, ADAL changed the content of the cache void AfterAccessNotification(TokenCacheNotificationArgs args) { // if state changed if (this.HasStateChanged) { Cache = new UserTokenCache { webUserUniqueId = userId, cacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"), LastWrite = DateTime.Now }; // update the DB and the lastwrite db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified; db.SaveChanges(); this.HasStateChanged = false; } }
/// <summary> /// Encrypts the specified data. /// </summary> /// <param name="data">The data.</param> /// <returns></returns> public string Encrypt(string data) { //Encode byte[] plain = Encoding.UTF8.GetBytes(data); byte[] cipher = MachineKey.Protect(plain); //Base64 storable value string base64 = string.Empty; if (cipher != null) { base64 = Convert.ToBase64String(cipher); } return(base64); }
/* function ius use to check user authentication as well set session AdminUserName , UserID, AdminUserType as well check remember me on this pc */ public void GetUser() { try { User ObjUser = new User(); DataSet DT = ObjUser.GetUser(txtUserId.Text, txtPass.Text); if (DT.Tables[0].Rows.Count > 0) { Session["AdminUserName"] = DT.Tables[0].Rows[0]["Firstname"].ToString() + " " + DT.Tables[0].Rows[0]["Lastname"].ToString(); Session["AdminID"] = DT.Tables[0].Rows[0]["UserID"].ToString(); Session["AdminUserType"] = DT.Tables[0].Rows[0]["UserType"].ToString(); if (chkRemember.Checked) { Request.Cookies.Remove("RemeberMe"); Request.Cookies.Remove("RemeberMePassword"); HttpContext.Current.Request.Cookies.Clear(); var cookieTextUserName = Encoding.UTF8.GetBytes(txtUserId.Text); var cookieTextUserPassword = Encoding.UTF8.GetBytes(txtPass.Text); var encryptedUserNameValue = Convert.ToBase64String(MachineKey.Protect(cookieTextUserName, "myAdminKey")); var encryptedPasswordValue = Convert.ToBase64String(MachineKey.Protect(cookieTextUserPassword, "myAdminKey")); HttpCookie c = new HttpCookie("RemeberMe", encryptedUserNameValue); c.Expires = DateTime.Now.AddDays(Convert.ToDouble(ConfigurationManager.AppSettings["addCookieForDay"])); Response.Cookies.Add(c); HttpCookie c1 = new HttpCookie("RemeberMePassword", encryptedPasswordValue); c1.Expires = DateTime.Now.AddDays(Convert.ToDouble(ConfigurationManager.AppSettings["addCookieForDay"])); Response.Cookies.Add(c1); } else { Response.Cookies["RemeberMe"].Expires = DateTime.Now.AddYears(-30); Response.Cookies["RemeberMePassword"].Expires = DateTime.Now.AddYears(-30); } Response.Redirect("~/Admin/AdminHome.aspx", false); } else { ErrMessage("Please verify your username and password"); } } catch (Exception ex) { lblError.Text = ex.Message.ToString(); } }
// Se genera una notificación después de que ADAL acceda a la caché. // Si la marca HasStateChanged está establecida, ADAL cambió el contenido de la memoria caché void AfterAccessNotification(TokenCacheNotificationArgs args) { // Si el estado ha cambiado if (this.HasStateChanged) { Cache = new UserTokenCache { webUserUniqueId = userId, cacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"), LastWrite = DateTime.Now }; // Actualizar la base de datos y la última escritura db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified; db.SaveChanges(); this.HasStateChanged = false; } }
// Notification générée une fois qu'ADAL a accédé au cache. // Si l'indicateur HasStateChanged est défini, ADAL a changé le contenu du cache void AfterAccessNotification(TokenCacheNotificationArgs args) { // Si l'état a changé if (this.HasStateChanged) { Cache = new UserTokenCache { webUserUniqueId = userId, cacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"), LastWrite = DateTime.Now }; // Mettre à jour la base de données et la dernière écriture db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified; db.SaveChanges(); this.HasStateChanged = false; } }
/// <summary> /// Protects the specified plain text. /// </summary> /// <param name="plainText">The plain text.</param> /// <param name="purpose">The purpose. The same string must be supplied when calling the Unprotect method to decipher the ciphertext</param> /// <returns> /// string Encrypted based on machine key /// </returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public string Protect(string plainText, string purpose) { if (string.IsNullOrWhiteSpace(plainText)) { throw new ArgumentNullException(nameof(plainText)); } if (string.IsNullOrWhiteSpace(purpose)) { throw new ArgumentNullException(nameof(purpose)); } var plainTextBytes = Encoding.UTF8.GetBytes(plainText); var protectedBytes = MachineKey.Protect(plainTextBytes, purpose); var protectedText = Convert.ToBase64String(protectedBytes); return(protectedText); }
public async Task <HttpResponseMessage> OAuthCode(string code) { var callback = Encoder.UrlPathEncode(ToAbsolute("~/")); var client = new HttpClient(); var dictionary = new Dictionary <string, string>(); dictionary.Add("grant_type", "authorization_code"); dictionary.Add("code", code); dictionary.Add("client_id", Config.Id); dictionary.Add("client_secret", Config.Key); dictionary.Add("redirect_uri", callback); var content = new FormUrlEncodedContent(dictionary); var tokenResponse = await client.PostAsync(Config.BaseUri.ToString() + "/APIIntegration/Token", content); var token = await tokenResponse.Content.ReadAsAsync <TokenResponseDto>(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth2", token.access_token); var meResponse = await client.GetAsync(Config.BaseUri.ToString() + "/api/info/me"); var me = await meResponse.Content.ReadAsAsync <InfoMeDto>(); var tokenMe = new AccessTokenAndMe() { AccessToken = token, Me = me }; var cookieToken = JsonConvert.SerializeObject(tokenMe); var bytes = System.Text.Encoding.UTF8.GetBytes(cookieToken); bytes = MachineKey.Protect(bytes, "COOKIE-TOKEN"); cookieToken = Convert.ToBase64String(bytes); var cookie = new CookieHeaderValue("AUTH", cookieToken); cookie.HttpOnly = true; cookie.Expires = DateTime.Now.AddMinutes(20); //cookie.Secure = true; //ALWAYS USE THIS IN PRODUCTION!! var response = new HttpResponseMessage(System.Net.HttpStatusCode.Redirect); response.Headers.Location = new Uri(ToAbsolute("~")); response.Headers.AddCookies(new[] { cookie }); return(response); }
protected void PtcSubmit_Click(object sender, EventArgs e) { if (chkRememberMe.Checked) { Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(30); Response.Cookies["Password"].Expires = DateTime.Now.AddDays(30); } else { Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1); Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-1); } Response.Cookies["UserName"].Value = Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(UserName.Text.Trim()), "UserName")); Response.Cookies["Password"].Value = Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(Password.Text.Trim()), "Password")); Response.Cookies["LoginMethod"].Value = "Ptc"; Ptc(UserName.Text, Password.Text, ""); }
public static string ProtectData(string value) { string str; using (MemoryStream stream = new MemoryStream()) using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Write(value); writer.Flush(); byte[] dst = new byte[stream.Length]; Buffer.BlockCopy(stream.GetBuffer(), 0, dst, 0, (int)stream.Length); byte[] result = MachineKey.Protect(dst, typeof(CryptoHelper).FullName, "User: " + CurrentUser.Identity.Name); str = Convert.ToBase64String(result); } return(str); }
public Result<ServiceResponse> ForgotPassword(ForgotPasswordRequest request) { return this.UseConnection("Default", connection => { request.CheckNotNull(); if (string.IsNullOrEmpty(request.Email)) throw new ArgumentNullException("email"); var user = connection.TryFirst<UserRow>(UserRow.Fields.Email == request.Email); if (user == null) throw new ValidationError("CantFindUserWithEmail", Texts.Validation.CantFindUserWithEmail); byte[] bytes; using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { bw.Write(DateTime.UtcNow.AddHours(3).ToBinary()); bw.Write(user.UserId.Value); bw.Flush(); bytes = ms.ToArray(); } var token = Convert.ToBase64String(MachineKey.Protect(bytes, "ResetPassword")); var externalUrl = Config.Get<EnvironmentSettings>().SiteExternalUrl ?? Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/"); var resetLink = UriHelper.Combine(externalUrl, "Account/ResetPassword?t="); resetLink = resetLink + Uri.EscapeDataString(token); var emailModel = new ResetPasswordEmailModel(); emailModel.Username = user.Username; emailModel.DisplayName = user.DisplayName; emailModel.ResetLink = resetLink; var emailSubject = Texts.Forms.Membership.ResetPassword.EmailSubject.ToString(); var emailBody = TemplateHelper.RenderTemplate( MVC.Views.Membership.Account.ResetPassword.AccountResetPasswordEmail, emailModel); Common.EmailHelper.Send(emailSubject, emailBody, user.Email); return new ServiceResponse(); }); }
public static string Protect(string text, string purpose) { if (string.IsNullOrEmpty(text)) { return(string.Empty); } try { byte[] stream = Encoding.UTF8.GetBytes(text); byte[] encoded = MachineKey.Protect(stream, purpose); return(HttpServerUtility.UrlTokenEncode(encoded)); } catch (Exception e) { return(string.Empty); } }
// GET: Home public ActionResult Index() { // Set Data in Cookie var cookieText = Encoding.UTF8.GetBytes("Text for Cookie"); var encryptedValue = Convert.ToBase64String(MachineKey.Protect(cookieText, "ProtectCookie")); //**// nice //--- Create cookie object and pass name of the cookie and value to be stored. HttpCookie cookieObject = new HttpCookie("NameOfCookie", encryptedValue); //---- Set expiry time of cookie. cookieObject.Expires.AddDays(5); //---- Add cookie to cookie collection. Response.Cookies.Add(cookieObject); return(View()); }
public static void SetValue(string name, Dictionary <string, string> values, DateTime expires, bool?httpOnly = null, string domain = null, string path = "/") { var cookie = new HttpCookie(name) { HttpOnly = httpOnly ?? true, Expires = expires, Path = path }; foreach (var pair in values) { cookie[pair.Key] = Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(pair.Value))); } if (!string.IsNullOrEmpty(domain)) { cookie.Domain = domain; } HttpContext.Current.Response.Cookies.Add(cookie); }
public void ThenIfTheCookieDoesExistTheObjectIsReturned() { //Arrange var expectedCookieName = "TestCookie"; var data = new TestClass { TestName = "some value" }; var content = Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data)))); _httpRequest.Object.Cookies.Add(new HttpCookie(expectedCookieName, content)); //Act var actual = _cookieService.Get(_httpContext.Object, expectedCookieName); //Assert Assert.IsNotNull(actual); Assert.IsAssignableFrom <TestClass>(actual); }
public ActionResult Index() { byte[] sd = System.Text.Encoding.Default.GetBytes("a"); sd = MachineKey.Protect(sd, _purposes); ViewBag.securet = HttpServerUtility.UrlTokenEncode(sd); byte[] rawProtectedBytes = HttpServerUtility.UrlTokenDecode("DgDfVEwUNeB-oQLsjtv9s2zMfDZv_ytAEQE0okbmQ5UwztkxmprpR1l1anBZw3cNAVRP7g2"); try { byte[] ff = MachineKey.Unprotect(rawProtectedBytes, _purposes); ViewBag.result = System.Text.Encoding.Default.GetString(ff); } catch (Exception e) { ViewBag.result = "error " + e.Message; } return(View()); }
private static AntiForgeryData CreateEncryptedToken(string salt) { byte[] valueData = new byte[0x10]; byte[] systemSaltData = new byte[0x5]; AntiForgeryData token = new AntiForgeryData(); Triplet triplet = new Triplet(); ObjectStateFormatter formatter = new ObjectStateFormatter(); try { Rng.GetBytes(valueData); Rng.GetBytes(systemSaltData); triplet.First = Convert.ToBase64String(valueData); triplet.Third = Convert.ToBase64String(systemSaltData); byte[] cookieBytes; using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, triplet); cookieBytes = stream.ToArray(); } token.CookieValue = MachineKey.Protect(cookieBytes, "Authentication token").ToHexString(); // token.CookieValue = MachineKey.Encode(cookieBytes, MachineKeyProtection.All); Rng.GetBytes(systemSaltData); triplet.Second = salt; triplet.Third = Convert.ToBase64String(systemSaltData); token.FormToken = MachineKey.Protect(Encoding.UTF8.GetBytes(formatter.Serialize(triplet)), "Authentication token").ToHexString(); // token.FormToken = MachineKey.Encode(Encoding.UTF8.GetBytes(formatter.Serialize(triplet)), MachineKeyProtection.All); token.Value = (string)triplet.First; return(token); } catch (Exception) { throw new HttpAntiForgeryException(); } }
private ActionResult ProcessWSFedSignOutRequest(SignOutRequestMessage message) { var idp = GetIdpCookie(); if (string.IsNullOrWhiteSpace(idp)) { return(ShowSignOutPage(message.Reply)); } var signOutMessage = new SignOutRequestMessage(new Uri(idp)); if (!string.IsNullOrWhiteSpace(message.Reply) && IsValidReplyTo(message.Reply)) { var bytes = Encoding.UTF8.GetBytes(message.Reply); bytes = MachineKey.Protect(bytes); var param = Url.Encode(Convert.ToBase64String(bytes)); var host = ConfigurationRepository.Global.PublicHostName; if (string.IsNullOrWhiteSpace(host)) { host = Request.Headers["host"]; } var builder = new UriBuilder(); builder.Host = host; builder.Scheme = Uri.UriSchemeHttps; if (ConfigurationRepository.Global.HttpsPort != 443) { builder.Port = ConfigurationRepository.Global.HttpsPort; } builder.Path = Request.ApplicationPath; if (!builder.Path.EndsWith("/")) { builder.Path += "/"; } builder.Path += Endpoints.Paths.WSFedHRDSignoutRedirect; builder.Query = "rp=" + param; signOutMessage.Reply = builder.ToString(); } return(Redirect(signOutMessage.WriteQueryString())); }
public ActionResult TwoFactorAuthenticate() { var token = Request["CodeDigit"]; TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator(); string UserUniqueKey = Session["UserUniqueKey"].ToString(); bool isValid = TwoFacAuth.ValidateTwoFactorPIN(UserUniqueKey, token); if (isValid) { HttpCookie TwoFCookie = new HttpCookie("TwoFCookie"); string UserCode = Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(UserUniqueKey))); TwoFCookie.Values.Add("UserCode", UserCode); TwoFCookie.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(TwoFCookie); Session["IsValidTwoFactorAuthentication"] = true; return(RedirectToAction("UserProfile", "Login")); } return(RedirectToAction("Login", "Login")); }
public override void Save(Uri organizationServiceUrl, AuthenticationProviderType authenticationType, string domain, string username, string password, Guid websiteId) { var xml = new XElement("settings"); xml.SetElementValue("organizationServiceUrl", organizationServiceUrl.OriginalString); xml.SetElementValue("authenticationType", authenticationType.ToString()); xml.SetElementValue("domain", domain); xml.SetElementValue("username", username); xml.SetElementValue("password", Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(password), _machineKeyPurposes))); xml.Save(_settingsPath.Value); try { SaveWebsiteBinding(websiteId); } catch (Exception) { File.Delete(_settingsPath.Value); } }
public static void AddOrUpdateState(RegisteredClient rc, HttpContext context) { // Save the cokie state Byte[] identity = Encoding.UTF8.GetBytes(rc.Identity); Byte[] encrypted = MachineKey.Protect(identity, "ShootR.Identity"); RegisteredClient temp = new RegisteredClient(rc.RegistrationID, HttpServerUtility.UrlTokenEncode(encrypted), rc.DisplayName, rc.Photo); var state = JsonConvert.SerializeObject(temp); if (context.Response.Cookies["shootr.state"] == null) { var cookie = new HttpCookie("shootr.state", state); cookie.Expires = DateTime.Now.AddDays(30); context.Response.Cookies.Add(cookie); } else { context.Response.Cookies["shootr.state"].Value = state; context.Response.Cookies["shootr.state"].Expires = DateTime.Now.AddDays(30); } }