/// <summary> /// Gets the security question for the given User Id or Token. /// Only one has to be provided /// </summary> /// <param name="userId">The Id of the user</param> /// <param name="token">The password reset token send to the user using <see cref="M:ForgottenPassword"/></param> /// <returns>The Security Question for the user</returns> public string GetSecurityQuestion(string userId = null, string token = null) { User u = null; try { if (!string.IsNullOrWhiteSpace(userId)) { u = this.FindById(userId); } else if (!string.IsNullOrWhiteSpace(token)) { string id = MachineKeyEncryption.Decrypt(token); id = id.Substring(0, id.IndexOf("|")); u = this.FindById(id); } if (u == null) { throw this.manager.MessageHandler.GetError(ErrorCodes.USER_UNKNOWN); } Logger.Audit(new Audit(Actions.GET_SECURITY_QUESTION, AuditEventType.READ, u)); return(u != null ? u.SecurityQuestion : null); } catch (Exception ex) { Logger.Audit(new Audit(Actions.GET_SECURITY_QUESTION, AuditEventType.READ, typeof(User), "Id", userId, false, ex.Message)); throw ex; } }
/// <summary> /// Decrypts the string encrypted with <see cref="M:EncryptAnonymous"/> and puts the found data in the userId, questionniareName and formatName references /// </summary> /// <param name="anonymous">The string to decrypt</param> /// <param name="patientId">The found id of the user</param> /// <param name="questionnaireName">The found name of the questionniare</param> /// <param name="formatName">The found format name</param> /// <param name="episodeId">The episode ID to fill if it is there</param> private void DecryptAnonymous(string anonymous, ref string patientId, ref string questionnaireName, ref string formatName, ref int?episodeId) { XElement element = XElement.Parse(MachineKeyEncryption.Decrypt(anonymous)); foreach (XNode c in element.Nodes()) { XElement e = (XElement)c; switch (e.Name.LocalName) { case "p": patientId = e.Value; break; case "q": questionnaireName = e.Value; break; case "f": formatName = e.Value; break; case "e": episodeId = int.Parse(e.Value); break; } } }
/// <summary> /// Decrypts the given string into a SessionData object /// </summary> /// <param name="encryptedString">The encrypted string to decrypt</param> /// <returns>The SessionData instance</returns> public static SessionData Decrypt(string encryptedString) { string decrypted = MachineKeyEncryption.Decrypt(encryptedString); XmlSerializer xmlSerializer = new XmlSerializer(typeof(SessionData)); StringReader reader = new StringReader(decrypted); return(xmlSerializer.Deserialize(reader) as SessionData); }
public void MachineKeyEncryptionTest1() { const string data = "Some text to encrypt"; var encrypted = MachineKeyEncryption.Encode(data); var decrypted = MachineKeyEncryption.Decode(encrypted); Assert.AreEqual(data, decrypted); }
/// <summary> /// Encryps the SessionData into a single string for safe storage /// </summary> /// <param name="data">The SessionData instance to encrypt</param> /// <returns>An encrypted representation of the SessionData</returns> public static string Encrypt(SessionData data) { XmlSerializer xmlSerializer = new XmlSerializer(data.GetType()); StringWriter textWriter = new StringWriter(); xmlSerializer.Serialize(textWriter, data); textWriter.Flush(); return(MachineKeyEncryption.Encrypt(textWriter.ToString())); }
public void MachineKeyEncryptionTest2() { const string originalText = "Some text to encrypt"; // ReSharper disable once CSharpWarnings::CS0618 var data = MachineKey.Encode(Encoding.UTF8.GetBytes(originalText), MachineKeyProtection.All); var decrypted = MachineKeyEncryption.Decode(data); Assert.AreEqual(originalText, decrypted); }
/// <summary> /// Encrypts the user Id, questionniareName and format Name as an string that can be used for anonymous questionnaire excess /// </summary> /// <param name="patientId">The id of the user</param> /// <param name="questionnaireName">the name of the questionniare</param> /// <param name="formatName">The name of the format</param> /// <param name="episodeId">The If of the episode to encrypt as well.</param> /// <returns>An encrypted string based upon the parameters</returns> private string EncryptAnonymous(string patientId, string questionnaireName, string formatName, int?episodeId) { string stringToEncrypt = "<root><p>" + patientId + "</p><q>" + questionnaireName + "</q><f>" + formatName + "</f>"; if (episodeId.HasValue) { stringToEncrypt += "<e>" + episodeId.Value + "</e>"; } stringToEncrypt += "</root>"; return(MachineKeyEncryption.Encrypt(stringToEncrypt)); }
/// <summary> /// Initializes a new instance of the <see cref="WcfUserSessionSecurity"/> class /// This creates a new session for the user /// </summary> /// <param name="user">The IUser instance to user</param> /// <param name="header">The Request header</param> internal protected WcfUserSessionSecurity(IUser user, RequestHeader header) : this(header) { if (user != null) { this.InternalUser = user; this.sessionId = MachineKeyEncryption.Encrypt(this.InternalUser.Id); this.SessionData.SecurityString = header.SessionId; this.SessionData.UserId = this.InternalUser.Id; this.SessionData.IsAuthenticated = this.MultiStepVerificationEnabled ? false : true; } }
public string Decode(string encodedValue, bool urlDecode = false) { if (urlDecode) { encodedValue = HttpUtility.UrlDecode(encodedValue); } try { return(MachineKeyEncryption.Decode(encodedValue)); } catch (Exception) { _logManager.LogError($"Error trying to decode {encodedValue}", GetType()); return(null); } }
public void SetConfigValue(string key, string value) { Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (key == "Secret") { //string encryptedValue = encryption.Encrypt(value); string encryptedValue = MachineKeyEncryption.Protect(value, $"Secret for computer {computerKey}"); value = encryptedValue; } configuration.AppSettings.Settings[key].Value = value; //configuration.AppSettings.SectionInformation.ProtectSection(null); configuration.Save(); ConfigurationManager.RefreshSection("appSettings"); baseURL = configuration.AppSettings.Settings["BaseURL"].Value; computerKey = configuration.AppSettings.Settings["ComputerKey"].Value; }
public string TokenDecoder(string token) { if (string.IsNullOrWhiteSpace(token)) { return(null); } token = Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(token)); if (!MachineKeyEncryption.TryDecode(token, out token)) { return(null); } string[] decoded = token.Split('^'); return(new DateTime(long.Parse(decoded[1])) > DateTime.UtcNow ? decoded[0] : null); }
/// <summary> /// Initializes a new instance of the <see cref="WcfUserSessionSecurity"/> class /// Continues with a existing session by the user (Or no session if the Session Id if empty) /// </summary> /// <param name="header">The Request header belonging to this session</param> internal protected WcfUserSessionSecurity(RequestHeader header) { this.sessionId = header.SessionId; string userId = MachineKeyEncryption.Decrypt(this.sessionId); try { this.InternalUser = WcfUserSessionSecurity.UserManager.Find(userId /*ticket.UserData*/); this.SessionData = WcfUserSessionSecurity.SessionStore.GetSessionData(this.sessionId); this.SessionData.LastRequestHeader = header; WcfUserSessionSecurity.SessionStore.UpdateSessionData(this.sessionId, this.SessionData); } catch (Exception) { this.InternalUser = null; this.SessionData = new SessionData(); this.SessionData.LastRequestHeader = header; } }
public string Encode(string plainValue, bool urlEncode = false) { var encodedValue = string.Empty; try { encodedValue = MachineKeyEncryption.Encode(plainValue); } catch { _logManager.LogError($"Error trying to encode {plainValue}", GetType()); return(encodedValue); } if (urlEncode) { return(HttpUtility.UrlEncode(encodedValue)); } return(encodedValue); }
public StatusMessage StartGame(int id, bool install = false) { StatusMessage returnMessage = new StatusMessage(); string baseURL = ConfigurationManager.AppSettings["BaseURL"]; string computerKey = ConfigurationManager.AppSettings["ComputerKey"]; string secretKey = ConfigurationManager.AppSettings["Secret"]; // We must decrypt the secret key using the machine key //machineKeyEncryption = new Encryption("the machine key"); try { secretKey = MachineKeyEncryption.UnProtect(secretKey, $"Secret for computer {computerKey}"); } catch (Exception e) { MessageBox.Show($"Error: Unable to load settings. Contact an administrator.\n\n{e.Message}"); throw; } // Then, we can Encrypt/Decrypt using that decrypted secret key encryption = new Encryption(secretKey); string URL = $"{baseURL}/game/checkout/{id}"; SteamGame game = gc.GetSteamLogin(id, URL, computerKey, ""); returnMessage.message = game.message; returnMessage.status = game.status; if (game.status == "ok") { game.password = encryption.Decrypt(game.password); LauncherInfo.isInstall = install; LauncherInfo.StartGame(game); gc.StartSteam(LauncherInfo.game); } return(returnMessage); }
/// <summary> /// Writes the cookie. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> public static void WriteCookie(string name, string value) { Assert.ArgumentNotNull(name, "name"); Assert.ArgumentNotNull(value, "value"); if (name == WebUtil.GetLoginCookieName()) { value = MachineKeyEncryption.Encode(value); } HttpContext.Current.Response.AppendCookie(new HttpCookie(name, value) { Expires = DateTime.Now.AddMonths(3), Path = "/sitecore/login" }); var httpCookie = HttpContext.Current.Request.Cookies[name]; if (httpCookie == null) { return; } httpCookie.Value = value; }
/// <summary> /// Loads all the session details from the persistant store file and fills the <see cref="WcfUserClient.sessionDetails"/> /// </summary> private void LoadSessionDetails() { lock (ClientSessionStore.savingLock) { if (this.sessionDetails != null) { return; } this.sessionDetails = new ConcurrentDictionary <string, ClientSessionData>(); // Open the file containing the data that you want to deserialize. FileInfo file = new FileInfo(this.persistantStoreLocation); if (!file.Exists || file.Length == 0) { this.securedData = new Dictionary <string, List <SecuredClientsessionData> >(); return; } FileStream fs = file.OpenRead(); // new FileStream(WcfUserClientSession.PersistantStoreLocation, FileMode.Open); try { BinaryReader binReader = new BinaryReader(fs); string xmlData = MachineKeyEncryption.Decrypt(binReader.ReadString()); this.securedData = this.Deserialize <Dictionary <string, List <SecuredClientsessionData> > >(xmlData); } catch (SerializationException e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); } finally { fs.Close(); } } }
public string TokenEncoder(string token, TimeSpan lifetime) { token = MachineKeyEncryption.Encode(token + "^" + (DateTime.UtcNow + lifetime).Ticks); return(HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(token))); }
/// <summary> /// Saves all the session details to the hard disk. /// </summary> private void SaveSessionDetails() { if (this.sessionDetails == null) { return; } #if !DEBUG if ((DateTime.Now - ClientSessionStore.lastSaveTime).TotalSeconds < ClientSessionStore.MinimumSecondsBetweenSaves) { return; } #endif lock (savingLock) { ClientSessionStore.lastSaveTime = DateTime.Now; Dictionary <string, List <SecuredClientsessionData> > dataTostore = new Dictionary <string, List <SecuredClientsessionData> >(); // Do some cleanup of the data that is no longer valid. DateTime now = DateTime.Now; List <string> keysToremove = new List <string>(); foreach (var data in this.sessionDetails) { if (data.Value.LastTimeUpdated.AddMinutes(data.Value.UserSessionConfiguration.Sessiontimeout) < now) { keysToremove.Add(data.Key); } else { string key = data.Key.Substring(0, ClientSessionStore.SessionIdSubstringLength); SecuredClientsessionData sd = new SecuredClientsessionData(); sd.SecuredData = MachineKeyEncryption.Encrypt(this.Serialize(data.Value.UserSessionConfiguration), data.Key); sd.LastUpdated = data.Value.LastTimeUpdated; sd.SessionTimeoutInMinutes = data.Value.UserSessionConfiguration.Sessiontimeout; if (!dataTostore.ContainsKey(data.Key)) { dataTostore.Add(key, new List <SecuredClientsessionData>()); } dataTostore[key].Add(sd); } } foreach (string key in keysToremove) { ClientSessionData tmp; this.sessionDetails.TryRemove(key, out tmp); } keysToremove = new List <string>(); foreach (var data in this.securedData) { foreach (var value in data.Value) { if (value.LastUpdated.AddMinutes(value.SessionTimeoutInMinutes) >= now) { if (!dataTostore.ContainsKey(data.Key)) { dataTostore.Add(data.Key, new List <SecuredClientsessionData>()); } dataTostore[data.Key].Add(value); } else { keysToremove.Add(data.Key); } } } foreach (string key in keysToremove) { this.securedData.Remove(key); } FileStream fs = new FileStream(this.persistantStoreLocation, FileMode.Create); string xmlData = MachineKeyEncryption.Encrypt(this.Serialize(dataTostore)); // Construct a BinaryFormatter and use it to write the data to the stream. BinaryWriter writer = new BinaryWriter(fs); try { writer.Write(xmlData); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Close(); } } }
/// <summary> /// Retrieves the Client Session Data for the given session ID /// </summary> /// <param name="sessionId">The Id of the session to retrieve the data for</param> /// <returns>The Client Session Data</returns> public Model.ClientSessionData GetSessionData(string sessionId) { if (this.SessionDetails.ContainsKey(sessionId)) { return(this.sessionDetails[sessionId]); } else if (this.securedData.ContainsKey(sessionId.Substring(0, ClientSessionStore.SessionIdSubstringLength))) { List <SecuredClientsessionData> d = this.securedData[sessionId.Substring(0, ClientSessionStore.SessionIdSubstringLength)]; foreach (SecuredClientsessionData scsd in d) { try { // SecuredClientsessionData scsd = this.securedData[sessionId.Substring(0, ClientSessionStore.SessionIdSubstringLength)]; string data = scsd.SecuredData; UserSessionConfiguration config = this.Deserialize <UserSessionConfiguration>(MachineKeyEncryption.Decrypt(data, sessionId)); ClientSessionData csd = new ClientSessionData() { LastTimeUpdated = scsd.LastUpdated, UserSessionConfiguration = config }; this.SessionDetails.AddOrUpdate(sessionId, csd, (k, v) => { return(csd); }); d.Remove(scsd); return(this.sessionDetails[sessionId]); } catch (Exception) { // Obviously it wasn't this one } } } return(null); }