/// <summary> /// This method constructs an Asymmetric data encryptor from a certificate found in the certificate store. /// </summary> /// <param name="storeLocation">The store location.</param> /// <param name="storeName">The store name.</param> /// <param name="certificateSelector">The certificate predicate selector, cannot be null.</param> /// <param name="keySelector">The delegate that extracts the key data from the certificate, cannot be null.</param> /// <exception cref="InvalidOperationException">The certificate could not be found or loaded.</exception> /// <exception cref="SecurityException">The calling context is denied access to the certificate store.</exception> /// <exception cref="CryptographicException">The encryption operation failed.</exception> /// <returns>The asymmetric key, cannot be null.</returns> private static AsymmetricDataEncryptor LoadCertificateKey(StoreLocation storeLocation, StoreName storeName, Predicate <X509Certificate2> certificateSelector, Func <X509Certificate2, string> keySelector) { // argument validation done in public method for first three arguments, last argument trusted to be not null X509Store store = null; try { store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); X509Certificate2 certificate = store.Certificates.Cast <X509Certificate2>().FirstOrDefault(cert => certificateSelector(cert)); if (certificate != null) { // capture keydata once so that multiple calls to encrypt/decrypt for a single instance of AsymmetricDataEncryptor always behaves the same // but keep the key under DPAPI encryption to protect from crash dump attacks IStringEncryptor encryptor = StringEncryptor.Create(CurrentUserDataEncryptor.Instance); string keyDataCipher = encryptor.Encrypt(AsymmetricDataEncryptor.InMemoryKeyName, keySelector(certificate)); return(new AsymmetricDataEncryptor(() => encryptor.Decrypt(AsymmetricDataEncryptor.InMemoryKeyName, keyDataCipher))); } } finally { if (store != null) { store.Close(); store = null; } } throw new InvalidOperationException("The requested certificate could not be loaded."); }
public string EncodePermalink(string link, bool rooted) { HttpRequest request = HttpContext.Current.Request; StringEncryptor enc = new StringEncryptor(); if (rooted) { string appPath = request.ApplicationPath; if (appPath.Equals("/")) { appPath = String.Empty; } return(String.Format("{0}://{1}{2}/default.aspx?_link={3}", request.Url.Scheme, request.Url.Authority, appPath, HttpUtility.UrlEncode(enc.Encrypt(link)))); } else { string[] linkSegments = link.Split('?'); string arguments = String.Empty; if (linkSegments.Length > 1) { arguments = linkSegments[1]; } return(String.Format("{0}?_link={1}", linkSegments[0], HttpUtility.UrlEncode(enc.Encrypt(arguments)))); } }
public void StringEncryptorHashStringTest() { const string initial = "THESTRING"; var hashed = StringEncryptor.HashString(initial); Assert.IsFalse(hashed.Contains(initial)); }
public ApplicationInsightsLogger(string instrumentationKey, IApplicationController applicationController) { InstrumentationKey = instrumentationKey; ApplicationController = applicationController; SessionId = Guid.NewGuid().ToString(); AnonymousString = "Anonymous " + StringEncryptor.HashString(UserName); TelemetryConfiguration.Active.InstrumentationKey = InstrumentationKey; #if DEBUG IsDebugMode = true; #endif var telemetryConfiguration = new TelemetryConfiguration(InstrumentationKey); //this tells to promptly send data if debugging telemetryConfiguration.TelemetryChannel.DeveloperMode = IsDebugMode; //for when debuuging if want to send data uncomment this line //IsDebugMode = false; var tc = new TelemetryClient(telemetryConfiguration); tc.InstrumentationKey = InstrumentationKey; tc.Context.Cloud.RoleInstance = ApplicationController.ApplicationName; tc.Context.User.UserAgent = $"{ApplicationController.ApplicationName} {ApplicationController.Version}"; tc.Context.User.Id = string.Empty; tc.Context.Session.Id = SessionId; tc.Context.Device.OperatingSystem = Environment.OSVersion.ToString(); TelemetryClient = tc; }
public string GetJson(int _saveSlot = 0) { string jsonText = ""; if (Application.platform == RuntimePlatform.WebGLPlayer) { //WebGLの場合はPlayerPrefsを使用する jsonText = StringEncryptor.Decrypt(PlayerPrefs.GetString(SaveKey + _saveSlot.ToString("0"), EmptySaveData)); if (jsonText == EmptySaveData) { //初期化したデータを入れておく jsonText = JsonUtility.ToJson(new SaveData()); } } else { string filePath = GetSaveFilePath(_saveSlot); if (File.Exists(filePath)) { jsonText = StringEncryptor.Decrypt(File.ReadAllText(filePath)); } else { jsonText = JsonUtility.ToJson(new SaveData()); } } return(jsonText); }
public static void Set(AppSettings settings) { Log.Debug($"Saving settings to file: '{JsonConvert.SerializeObject(settings)}'"); var configuration = ConfigurationManager. OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); UpdateSetting(nameof(AppSettings.ApiUrl), settings.ApiUrl); UpdateSetting(nameof(AppSettings.IdentityUrl), settings.IdentityUrl); var encryptedClientSecret = StringEncryptor.EncryptString(settings.ClientSecret); UpdateSetting(nameof(AppSettings.ClientSecret), encryptedClientSecret); configuration.Save(); ConfigurationManager.RefreshSection("appSettings"); void UpdateSetting(string key, string value) { if (configuration.AppSettings.Settings[key] == null) { configuration.AppSettings.Settings.Add(key, value); } else { configuration.AppSettings.Settings[key].Value = value; } } }
protected virtual void ValidateUrlParameters() { bool success = true; string link = Page.Request["_link"]; if (!(String.IsNullOrEmpty(link))) { try { StringEncryptor enc = new StringEncryptor(); link = enc.Decrypt(link.Replace(" ", "+").Split(',')[0]); if (!(link.Contains('?'))) { link = ('?' + link); } string[] permalink = link.Split('?'); ClientScript.RegisterClientScriptBlock(GetType(), "CommandLine", String.Format("var __dacl=\'{0}?{1}\';", permalink[0], BusinessRules.JavaScriptString(permalink[1])), true); } catch (Exception) { success = false; } } if (!(success)) { Response.StatusCode = 403; Response.End(); } }
public ActionResult SignIn(LoginModel model, string returnUrl) { if (ModelState.IsValid) { var info = _userService.ValidateUser(model.UserName, StringEncryptor.EncryptPassword(model.Password)); if (info != null) { if (!info.IsActive) { ModelState.AddModelError("", "The account is not allowed to access. Please contact Administrator."); } else { string userPermission = ""; var userRoleList = _userRoleService.GetMany(x => x.UserId == info.Id && !x.Role.Deleted); //foreach (var userRole in info.UserRoles.Where(x => !x.Role.Deleted)) foreach (var userRole in userRoleList) { userRole.Role = _roleService.Get(x => x.Id == userRole.RoleId && !x.Deleted); if (userRole.Role != null) { userRole.Role.RolePermissions = _rolePermissionService.GetMany(x => x.RoleId == userRole.RoleId); var rolePermission = userRole.Role.RolePermissions.Distinct().ToList(); //userPermission += GetRoleString(userRole.Role.RolePermissions) + ","; userPermission += GetRoleString(rolePermission) + ","; } } SecurityContext.CreateAuthenticationCookie(info.Username.ToUpper(), true, info.Id, userPermission.TrimEnd(','), info.FirstName, info.LastName, info.IsSLS); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return(Redirect(returnUrl)); } return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return(View(model)); }
public void StringEncryptorEncryptDecryptTest() { const string initial = "THESTRING"; var encrypted = StringEncryptor.Encrypt(initial); var decrypted = StringEncryptor.Decrypt(encrypted); Assert.IsFalse(initial == encrypted); Assert.IsTrue(initial == decrypted); }
public static void SetSaveData <T>(T obj, string name) { var json = JsonUtility.ToJson(obj); var jsonEncrypt = StringEncryptor.Encrypt(json); var path = PreparePath(name); File.WriteAllText(path, jsonEncrypt); }
/// <summary> /// Creates an AsymmetricDataEncryptor instance with a new RSA key. /// </summary> /// <returns>The asymmetric key, cannot be null.</returns> public static AsymmetricDataEncryptor GenerateRandomEncryptor() { // capture keydata once so that multiple calls to encrypt/decrypt for a single instance of AsymmetricDataEncryptor always behaves the same // but keep the key under DPAPI encryption to protect from crash dump attacks IStringEncryptor encryptor = StringEncryptor.Create(CurrentUserDataEncryptor.Instance); string keyDataCipher = encryptor.Encrypt(AsymmetricDataEncryptor.InMemoryKeyName, AsymmetricDataEncryptor.GenerateKey()); return(new AsymmetricDataEncryptor(() => encryptor.Decrypt(AsymmetricDataEncryptor.InMemoryKeyName, keyDataCipher))); }
public override string ReadData() { var data = base.ReadData(); if (!StringEncryptor.IsEncrypted(data)) { data = StringEncryptor.Encrypt(data); } return(StringEncryptor.Decrypt(data)); }
private void setEncryptedPasswordCookie(string password) { HttpCookie cookie = new HttpCookie("token2"); cookie.Expires = DateTime.Now.AddDays(30); string encryptedPassword = new StringEncryptor().Encrypt(password); cookie.Value = encryptedPassword; Response.Cookies.Add(cookie); }
private void setEncryptedUsernameCookie(string username) { HttpCookie cookie = new HttpCookie("token1"); cookie.Expires = DateTime.Now.AddDays(30); string encryptedUsername = new StringEncryptor().Encrypt(username); cookie.Value = encryptedUsername; Response.Cookies.Add(cookie); }
public void StringEncryptor_GivenIncorrectKey_CannotDecryptMessage() { string plainText = "Mary had a little lamb."; string key = "Behold, I've become the destroyer of worlds."; string encryptedText = StringEncryptor.Encrypt(plainText, key); Action act = () => StringEncryptor.Decrypt(encryptedText, "wrong key"); act.ShouldThrow <CryptographicException>(); }
public void StringEncryptor_GivenCorrectKey_DecryptsMessage() { string plainText = "Mary had a little lamb."; string key = "Behold, I've become the destroyer of worlds."; string encryptedText = StringEncryptor.Encrypt(plainText, key); string decryptedText = StringEncryptor.Decrypt(encryptedText, key); decryptedText.Should().Be(plainText); }
public JsonResult RespondCookies() { if (Request.Cookies["token1"] != null) { string encryptedUsername = Request.Cookies["token1"].Value; string decryptedUsername = new StringEncryptor().Decrypt(encryptedUsername); return(Json(new { username = decryptedUsername })); } return(Json(new { username = "", password = "" })); }
private static SqlConnection GetDbConnection(string connectionString, bool tryDecrypt) { var builder = new SqlConnectionStringBuilder(); try { builder = new SqlConnectionStringBuilder(connectionString); //decrypting the user id and password used, if applicable... if (tryDecrypt) { builder.UserID = StringEncryptor.DecryptWithPassword(builder.UserID, StringEncryptor.DefaultPassword); builder.Password = StringEncryptor.DecryptWithPassword(builder.Password, StringEncryptor.DefaultPassword); } } catch (Exception) { throw new DatabaseException($"The format for the connection string '{builder.ConnectionString}' is invalid."); } SqlConnection conn = null; var retry = 0; var sb = new StringBuilder(); while (retry < MAX_RETRIES) { try { conn = new SqlConnection(builder.ConnectionString); conn.Open(); if (conn.State != ConnectionState.Open) { conn.Open(); } return(conn); } catch (Exception e) { conn?.Dispose(); sb.AppendLine(e.ToString()); retry++; } } sb.AppendLine($"Could not obtain a connection to database '{builder.InitialCatalog}' on server '{builder.DataSource}'."); throw new DatabaseException(sb.ToString()); }
private static string ReadAndDecrypt(string name) { var path = PreparePath(name); if (File.Exists(path)) { return(null); } var text = File.ReadAllText(path); return(StringEncryptor.Decrypt(text)); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var stringValue = reader.Value as string; if (string.IsNullOrEmpty(stringValue)) { return(reader.Value); } var decryptedValue = StringEncryptor.Decrypt(stringValue, _passphrase); return(decryptedValue); }
public void DecriptMethod_On_BTE_Return_ASD_WithKey_1() { // AAA // Arrange const string str = "BTE"; const string expected_result = "ASD"; const int key = 1; // Act var actual_result = StringEncryptor.Decrypt(str, key); // Assert Assert.AreEqual(expected_result, actual_result); }
public void WrongPasswordTest() { var sr = new StringEncryptor { Password = "******" }; var encrypted = sr.EncryptString(input); Assert.AreNotEqual(input, encrypted); sr.Password = "******"; sr.DecryptString(encrypted); // throws a cryptographic exception. }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var stringValue = value as string; if (string.IsNullOrEmpty(stringValue)) { writer.WriteNull(); return; } var encryptedValue = StringEncryptor.Encrypt(stringValue, _passphrase); writer.WriteValue(encryptedValue); }
protected void Page_Load(object sender, EventArgs e) { if (Request.Params["_page"] == "_blank") return; string link = Request.Params["_link"]; if (!(String.IsNullOrEmpty(link))) { StringEncryptor enc = new StringEncryptor(); string[] permalink = enc.Decrypt(link.Split(',')[0]).Split('?'); Page.ClientScript.RegisterStartupScript(GetType(), "Redirect", String.Format("location.replace(\'{0}?_link={1}\');\r\n", permalink[0], HttpUtility.UrlEncode(link)), true); } else Response.Redirect(ApplicationServices.HomePageUrl); }
public void RoundTripTest() { var sr = new StringEncryptor { Password = "******" }; var encrypted = sr.EncryptString(input); Assert.AreNotEqual(input, encrypted); var decrypted = sr.DecryptString(encrypted); Assert.AreEqual(input, decrypted); }
protected void Page_Load(object sender, EventArgs e) { string link = Request.Params["_link"]; if (!(String.IsNullOrEmpty(link))) { StringEncryptor enc = new StringEncryptor(); string[] permalink = enc.Decrypt(link.Split(',')[0]).Split('?'); Page.ClientScript.RegisterStartupScript(GetType(), "Redirect", String.Format("location.replace(\'{0}?_link={1}\');\r\n", permalink[0], HttpUtility.UrlEncode(link)), true); } else { Response.Redirect("~/Pages/Home.aspx"); } }
public static AppSettings Get() { var settingsPath = Assembly.GetExecutingAssembly().Location; Log.Debug($"Loading settings from {settingsPath}"); var configuration = ConfigurationManager. OpenExeConfiguration(settingsPath); var appSettings = configuration.AppSettings.Settings; var clientSecret = StringEncryptor.DecryptString(appSettings[nameof(AppSettings.ClientSecret)]?.Value); return(new AppSettings(appSettings[nameof(AppSettings.IdentityUrl)]?.Value, appSettings[nameof(AppSettings.ApiUrl)]?.Value, clientSecret)); }
protected override void CompleteDialogExtention() { //stucture this and use app to reference in the test project // save to the setting exists in the settings folder then get it var folder = ApplicationController.SettingsPath; FileUtility.CheckCreateFolder(folder); var xmlString = DataContractSerializeObject(EnteredObject); var encrypt = StringEncryptor.Encrypt(xmlString); FileUtility.CheckCreateFolder(SaveTo.SaveToFolder.FolderPath); FileUtility.WriteToFile(SaveTo.SaveToFolder.FolderPath, typeof(T).Name + ".xml", encrypt); CompletionMessage = "The Object Has Been Encrypted"; }
public void WrongSeedTest() { var sr = new StringEncryptor { Password = "******" }; var encrypted = sr.EncryptString(input); Assert.AreNotEqual(input, encrypted); sr.Seed = Guid.NewGuid(); var decrypted = sr.DecryptString(encrypted); Assert.AreNotEqual(input, decrypted); }
public void Save(int _saveSlot = 0) { string jsonText = JsonUtility.ToJson(m_saveData); if (Application.platform == RuntimePlatform.WebGLPlayer) { //WebGLの時はPlayerPrefsを使用 PlayerPrefs.SetString(SaveKey + _saveSlot.ToString("0"), StringEncryptor.Encrypt(jsonText)); } else { File.WriteAllText(GetSaveFilePath(_saveSlot), StringEncryptor.Encrypt(jsonText)); } if (m_isCheckLog) { Debug.Log(_saveSlot.ToString("0") + "番のスロットに現在のデータを保存しました。"); } }
protected void Page_Load(object sender, EventArgs e) { if (!(IsPostBack)) { string link = Request.QueryString["l"]; if (String.IsNullOrEmpty(link)) { StringEncryptor se = new StringEncryptor(); link = se.Decrypt(Request.QueryString["_link"]); link = HttpUtility.UrlDecode(link.Substring(2)); } if (!(String.IsNullOrEmpty(link))) { if (!(link.Contains("&"))) { link = Encoding.Default.GetString(Convert.FromBase64String(link)); } Match m = Regex.Match(link, "(.+?)(&|$)"); if (m.Success) { Div1.Visible = true; Extender1.Controller = m.Groups[1].Value; m = m.NextMatch(); while (m.Success) { Match pair = Regex.Match(m.Groups[1].Value, "^(\\w+)=(.+)$"); if (pair.Success) { if (!(String.IsNullOrEmpty(Extender1.FilterFields))) { Extender1.FilterFields = (Extender1.FilterFields + ","); ExtenderFilter.Value = (ExtenderFilter.Value + ","); } Extender1.FilterFields = (Extender1.FilterFields + pair.Groups[1].Value); ExtenderFilter.Value = (ExtenderFilter.Value + pair.Groups[2].Value); } m = m.NextMatch(); } } } } }
public string EncodePermalink(string link, bool rooted) { HttpRequest request = HttpContext.Current.Request; StringEncryptor enc = new StringEncryptor(); if (rooted) { string appPath = request.ApplicationPath; if (appPath.Equals("/")) appPath = String.Empty; return String.Format("{0}://{1}{2}/default.aspx?_link={3}", request.Url.Scheme, request.Url.Authority, appPath, HttpUtility.UrlEncode(enc.Encrypt(link))); } else { string[] linkSegments = link.Split('?'); string arguments = String.Empty; if (linkSegments.Length > 1) arguments = linkSegments[1]; return String.Format("{0}?_link={1}", linkSegments[0], HttpUtility.UrlEncode(enc.Encrypt(arguments))); } }
protected virtual void ValidateUrlParameters() { bool success = true; string link = Page.Request["_link"]; if (!(String.IsNullOrEmpty(link))) try { StringEncryptor enc = new StringEncryptor(); link = enc.Decrypt(link.Split(',')[0]); if (!(link.Contains('?'))) link = ('?' + link); string[] permalink = link.Split('?'); ClientScript.RegisterClientScriptBlock(GetType(), "CommandLine", String.Format("var __dacl=\'{0}?{1}\';", permalink[0], BusinessRules.JavaScriptString(permalink[1])), true); } catch (Exception ) { success = false; } if (!(success)) { Response.StatusCode = 403; Response.End(); } }