internal static byte[] Decode(CookieProtection cookieProtection, string data, Purpose purpose) { byte[] buf = HttpServerUtility.UrlTokenDecode(data); if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider) { // If we're configured to go through the new crypto routines, do so. ICryptoService cryptoService = AspNetCryptoServiceProvider.Instance.GetCryptoService(purpose); return(cryptoService.Unprotect(buf)); } #pragma warning disable 618 // calling obsolete methods // Otherwise fall back to using MachineKeySection. if (buf == null || cookieProtection == CookieProtection.None) { return(buf); } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) { buf = MachineKeySection.EncryptOrDecryptData(false, buf, null, 0, buf.Length); if (buf == null) { return(null); } } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) { return(MachineKeySection.GetUnHashedData(buf)); } return(buf); #pragma warning restore 618 // calling obsolete methods }
private string SaveConfig(string connectionstr) { try { System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); using (RijndaelManaged managed = this.GetCryptographer()) { configuration.AppSettings.Settings["IV"].Value = Convert.ToBase64String(managed.IV); configuration.AppSettings.Settings["Key"].Value = Convert.ToBase64String(managed.Key); } MachineKeySection section = (MachineKeySection)configuration.GetSection("system.web/machineKey"); section.ValidationKey = CreateKey(20); section.DecryptionKey = CreateKey(0x18); section.Validation = MachineKeyValidation.SHA1; section.Decryption = "3DES"; configuration.ConnectionStrings.ConnectionStrings["HidistroSqlServer"].ConnectionString = connectionstr; configuration.ConnectionStrings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); configuration.Save(); configuration = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); configuration.AppSettings.Settings.Remove("Installer"); configuration.Save(); return(""); } catch (Exception exception) { return(exception.Message); } }
public string GetKey() { try { // Set the path of the config file. string configPath = ""; // Get the Web application configuration object. Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath); // Get the section related object. MachineKeySection configSection = (MachineKeySection)config.GetSection("system.web/machineKey"); return(configSection.DecryptionKey); } catch (Exception e) { // Unknown error. // Console.WriteLine(e.ToString()); return(null); } }
public SystemProperties(string applicationName, bool enablePasswordReset, bool enablePasswordRetrieval, int maxInvalidPasswordAttempts, int minRequiredNonAlphanumericCharacters, int minRequiredPasswordLength, int passwordAttemptWindow, MembershipPasswordFormat passwordFormat, string passwordStrengthRegularExpression, bool requiresQuestionAndAnswer, bool requiresUniqueEmail, string connectionName, int userIsOnlineTimeWindow, MachineKeySection machineKey) { _applicationName = applicationName; _enablePasswordReset = enablePasswordReset; _enablePasswordRetrieval = enablePasswordRetrieval; _maxInvalidPasswordAttempts = maxInvalidPasswordAttempts; _minRequiredNonAlphanumericCharacters = minRequiredNonAlphanumericCharacters; _minRequiredPasswordLength = minRequiredPasswordLength; _passwordAttemptWindow = passwordAttemptWindow; _passwordFormat = passwordFormat; _passwordStrengthRegularExpression = passwordStrengthRegularExpression; _requiresQuestionAndAnswer = requiresQuestionAndAnswer; _requiresUniqueEmail = requiresUniqueEmail; _connectionName = connectionName; _machineKey = machineKey; }
internal static String Encrypt(FormsAuthenticationTicket ticket, bool hexEncodedTicket) { if (ticket == null) { throw new ArgumentNullException("ticket"); } Initialize(); ////////////////////////////////////////////////////////////////////// // Step 1a: Make it into a binary blob byte[] bBlob = MakeTicketIntoBinaryBlob(ticket); if (bBlob == null) { return(null); } ////////////////////////////////////////////////////////////////////// // Step 1b: If new crypto routines are enabled, call them instead. if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider) { ICryptoService cryptoService = AspNetCryptoServiceProvider.Instance.GetCryptoService(Purpose.FormsAuthentication_Ticket); byte[] protectedData = cryptoService.Protect(bBlob); bBlob = protectedData; } else { #pragma warning disable 618 // calling obsolete methods // otherwise.. ////////////////////////////////////////////////////////////////////// // Step 2: Get the MAC and add to the blob if (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Validation) { byte[] bMac = MachineKeySection.HashData(bBlob, null, 0, bBlob.Length); if (bMac == null) { return(null); } byte[] bAll = new byte[bMac.Length + bBlob.Length]; Buffer.BlockCopy(bBlob, 0, bAll, 0, bBlob.Length); Buffer.BlockCopy(bMac, 0, bAll, bBlob.Length, bMac.Length); bBlob = bAll; } if (_Protection == FormsProtectionEnum.All || _Protection == FormsProtectionEnum.Encryption) { ////////////////////////////////////////////////////////////////////// // Step 3: Do the actual encryption // DevDiv Bugs 137864: Include a random IV if under the right compat mode // for improved encryption semantics bBlob = MachineKeySection.EncryptOrDecryptData(true, bBlob, null, 0, bBlob.Length, false, false, IVType.Random); } #pragma warning restore 618 // calling obsolete methods } //if (!hexEncodedTicket) // return HttpServerUtility.UrlTokenEncode(bBlob); //else return(CryptoUtil.BinaryToHex(bBlob)); }
public void Validation_Custom() { MachineKeySection section = new MachineKeySection(); section.Validation = MachineKeyValidation.Custom; // cannot be set directly }
internal HashAlgorithm GetAlgo() { if (algo != null) { return(algo); } if (!EnableMac) { return(null); } byte [] algoKey; if (page != null) { #if NET_2_0 MachineKeySection mconfig = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection("system.web/machineKey"); algoKey = MachineKeySectionUtils.ValidationKeyBytes(mconfig); #else MachineKeyConfig mconfig = HttpContext.GetAppConfig("system.web/machineKey") as MachineKeyConfig; algoKey = mconfig.ValidationKey; #endif } else { algoKey = vkey; } algo = new HMACSHA1(algoKey); return(algo); }
SymmetricAlgorithm GetAlg() { MachineKeySection section = (MachineKeySection)WebConfigurationManager.GetSection("system.web/machineKey"); if (section.DecryptionKey.StartsWith("AutoGenerate")) { throw new ProviderException("You must explicitly specify a decryption key in the <machineKey> section when using encrypted passwords."); } string alg_type = section.Decryption; if (alg_type == "Auto") { alg_type = "AES"; } SymmetricAlgorithm alg = null; if (alg_type == "AES") { alg = Rijndael.Create(); } else if (alg_type == "3DES") { alg = TripleDES.Create(); } else { throw new ProviderException(String.Format("Unsupported decryption attribute '{0}' in <machineKey> configuration section", alg_type)); } alg.Key = MachineKeySectionUtils.DecryptionKey192Bits(section); return(alg); }
static public byte [] Encrypt(MachineKeySection section, byte [] data) { using (SymmetricAlgorithm sa = GetDecryptionAlgorithm(section)) { sa.Key = GetDecryptionKey(section); return(Encrypt(sa, data)); } }
// note: take no shortcut (timing attack) while verifying or decrypting public static byte [] VerifyDecrypt(MachineKeySection section, byte [] block) { bool valid = true; int signlen; using (KeyedHashAlgorithm kha = GetValidationAlgorithm(section)) { kha.Key = GetValidationKey(section); signlen = kha.HashSize >> 3; // bits to bytes byte [] signature = Sign(section, block, 0, block.Length - signlen); for (int i = 0; i < signature.Length; i++) { if (signature [i] != block [block.Length - signature.Length + i]) { valid = false; // do not return (timing attack) } } } // whatever the signature continue with decryption try { byte [] decdata = Decrypt(section, block, 0, block.Length - signlen); return(valid ? decdata : null); } catch { return(null); } }
static byte [] Decrypt(MachineKeySection section, byte [] encodedData, int offset, int length) { using (SymmetricAlgorithm sa = GetDecryptionAlgorithm(section)) { sa.Key = GetDecryptionKey(section); return(Decrypt(sa, encodedData, offset, length)); } }
public string Serialize(object stateGraph) { string str = null; MemoryStream memoryStream = GetMemoryStream(); try { this.Serialize(memoryStream, stateGraph); memoryStream.SetLength(memoryStream.Position); byte[] buf = memoryStream.GetBuffer(); int length = (int)memoryStream.Length; if ((this._page != null) && this._page.RequiresViewStateEncryptionInternal) { buf = MachineKeySection.EncryptOrDecryptData(true, buf, this.GetMacKeyModifier(), 0, length); length = buf.Length; } else if (((this._page != null) && this._page.EnableViewStateMac) || (this._macKeyBytes != null)) { buf = MachineKeySection.GetEncodedData(buf, this.GetMacKeyModifier(), 0, ref length); } str = Convert.ToBase64String(buf, 0, length); } finally { ReleaseMemoryStream(memoryStream); } return(str); }
private bool SaveConfig(out string errorMsg) { try { Configuration configuration = WebConfigurationManager.OpenWebConfiguration(base.Request.ApplicationPath); configuration.AppSettings.Settings.Remove("Installer"); using (RijndaelManaged rijndaelManaged = this.GetCryptographer()) { configuration.AppSettings.Settings["IV"].Value = Convert.ToBase64String(rijndaelManaged.IV); configuration.AppSettings.Settings["Key"].Value = Convert.ToBase64String(rijndaelManaged.Key); } MachineKeySection machineKeySection = (MachineKeySection)configuration.GetSection("system.web/machineKey"); machineKeySection.ValidationKey = Install.CreateKey(20); machineKeySection.DecryptionKey = Install.CreateKey(24); machineKeySection.Validation = MachineKeyValidation.SHA1; machineKeySection.Decryption = "3DES"; configuration.ConnectionStrings.ConnectionStrings["HidistroSqlServer"].ConnectionString = this.GetConnectionString(); configuration.ConnectionStrings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); configuration.Save(); errorMsg = null; return(true); } catch (Exception ex) { errorMsg = ex.Message; return(false); } }
public void ValidationAlgorithm_Null() { MachineKeySection section = new MachineKeySection(); section.ValidationAlgorithm = null; Assert.AreEqual("HMACSHA256", section.ValidationAlgorithm, "ValidationAlgorithm"); }
/// <summary> /// 保存配置文件 /// </summary> /// <param name="errorMsg"></param> /// <returns></returns> bool SaveConfig(out string errorMsg) { bool flag = false; try { //获取配置文件 Configuration configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); //移去配置文件的Installer项 configuration.AppSettings.Settings.Remove("Installer"); MachineKeySection section = (MachineKeySection)configuration.GetSection("system.web/machineKey"); //设置数据 section.ValidationKey = CreateKey(20); section.DecryptionKey = CreateKey(24); section.Validation = MachineKeyValidation.SHA1; section.Decryption = "3DES"; configuration.ConnectionStrings.ConnectionStrings["HidistroSqlServer"].ConnectionString = GetConnectionString(); configuration.ConnectionStrings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); //保存到配置文件 configuration.Save(); errorMsg = null; flag = true; } catch (Exception exception) { errorMsg = exception.Message; } return(flag); }
public static string HashPasswordForStoringInConfigFile(string password, string passwordFormat) { HashAlgorithm algorithm; if (password == null) { throw new ArgumentNullException("password"); } if (passwordFormat == null) { throw new ArgumentNullException("passwordFormat"); } if (StringUtil.EqualsIgnoreCase(passwordFormat, "sha1")) { algorithm = SHA1.Create(); } else { if (!StringUtil.EqualsIgnoreCase(passwordFormat, "md5")) { throw new ArgumentException(System.Web.SR.GetString("InvalidArgumentValue", new object[] { "passwordFormat" })); } algorithm = MD5.Create(); } return(MachineKeySection.ByteArrayToHexString(algorithm.ComputeHash(Encoding.UTF8.GetBytes(password)), 0)); }
public void Encrypt_RoundTrip(MachineKeySection section) { byte [] data = new byte [14]; byte [] encdata = MachineKeySectionUtils.Encrypt(section, data); byte [] decdata = MachineKeySectionUtils.Decrypt(section, encdata); Assert.AreEqual(data, decdata, "roundtrip"); // changing length (missing first byte) byte [] cut = new byte [encdata.Length - 1]; Array.Copy(encdata, 1, cut, 0, cut.Length); Assert.IsNull(MachineKeySectionUtils.Decrypt(section, cut), "bad length"); // changing last byte (padding) byte be = encdata [encdata.Length - 1]; encdata [encdata.Length - 1] = ChangeByte(be); byte[] result = MachineKeySectionUtils.Decrypt(section, encdata); // this will return null if a bad padding is detected - OTOH since we're using a random key and we // encrypt a random IV it's possible the decrypted stuff will randomly have a "valid" padding (there's // only so much possible values and the bots runs those tests pretty often and give false positive) // To avoid this we fallback to ensure the data is invalid (if should be empty) int total = 0; if (result != null) { for (int i = 0; i < result.Length; i++) { total += result [i]; } } Assert.IsTrue(result == null || total != 0, "bad padding"); }
public void Encrypt_RoundTrip_TripleDES() { MachineKeySection section = new MachineKeySection(); section.Validation = MachineKeyValidation.TripleDES; Encrypt_RoundTrip(section); }
public void Validation_RoundTrip_HMACSHA512() { MachineKeySection section = new MachineKeySection(); section.Validation = MachineKeyValidation.HMACSHA512; Validation_RoundTrip(section); }
public void Validation_RoundTrip_Custom_RIPEMD160() { MachineKeySection section = new MachineKeySection(); section.ValidationAlgorithm = "alg:HMACRIPEMD160"; Validation_RoundTrip(section); }
public void Validation_RoundTrip_MD5() { MachineKeySection section = new MachineKeySection(); section.Validation = MachineKeyValidation.MD5; Validation_RoundTrip(section); }
public void Validation_RoundTrip_SHA1() { MachineKeySection section = new MachineKeySection(); section.Validation = MachineKeyValidation.SHA1; Validation_RoundTrip(section); }
public void EncryptSign_RoundTrip_AES() { MachineKeySection section = new MachineKeySection(); section.Validation = MachineKeyValidation.AES; EncryptSign_RoundTrip(section); }
public void EncryptSign_RoundTrip_HMACSHA384() { MachineKeySection section = new MachineKeySection(); section.Validation = MachineKeyValidation.HMACSHA384; EncryptSign_RoundTrip(section); }
public static string Encrypt(FormsAuthenticationTicket ticket) { if (ticket == null) { throw new ArgumentNullException("ticket"); } Initialize(); byte [] ticket_bytes = ticket.ToByteArray(); if (protection == FormsProtectionEnum.None) { return(Convert.ToBase64String(ticket_bytes)); } byte [] result = null; MachineKeySection config = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection(machineKeyConfigPath); if (protection == FormsProtectionEnum.All) { result = MachineKeySectionUtils.EncryptSign(config, ticket_bytes); } else if (protection == FormsProtectionEnum.Encryption) { result = MachineKeySectionUtils.Encrypt(config, ticket_bytes); } else if (protection == FormsProtectionEnum.Validation) { result = MachineKeySectionUtils.Sign(config, ticket_bytes); } return(Convert.ToBase64String(result)); }
public static string Encode(byte[] data, MachineKeyProtection protectionOption) { if (data == null) { throw new ArgumentNullException("data"); } ////////////////////////////////////////////////////////////////////// // Step 1: Get the MAC and add to the blob if (protectionOption == MachineKeyProtection.All || protectionOption == MachineKeyProtection.Validation) { byte[] bHash = MachineKeySection.HashData(data, null, 0, data.Length); byte[] bAll = new byte[bHash.Length + data.Length]; Buffer.BlockCopy(data, 0, bAll, 0, data.Length); Buffer.BlockCopy(bHash, 0, bAll, data.Length, bHash.Length); data = bAll; } if (protectionOption == MachineKeyProtection.All || protectionOption == MachineKeyProtection.Encryption) { ////////////////////////////////////////////////////////////////////// // Step 2: Encryption data = MachineKeySection.EncryptOrDecryptData(true, data, null, 0, data.Length, false, false, IVType.Random, !AppSettings.UseLegacyMachineKeyEncryption); } ////////////////////////////////////////////////////////////////////// // Step 3: Covert the buffer to HEX string and return it return(CryptoUtil.BinaryToHex(data)); }
static FormsAuthenticationTicket Decrypt2(byte [] bytes) { if (protection == FormsProtectionEnum.None) { return(FormsAuthenticationTicket.FromByteArray(bytes)); } MachineKeySection config = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection(machineKeyConfigPath); byte [] result = null; if (protection == FormsProtectionEnum.All) { result = MachineKeySectionUtils.VerifyDecrypt(config, bytes); } else if (protection == FormsProtectionEnum.Encryption) { result = MachineKeySectionUtils.Decrypt(config, bytes); } else if (protection == FormsProtectionEnum.Validation) { result = MachineKeySectionUtils.Verify(config, bytes); } return(FormsAuthenticationTicket.FromByteArray(result)); }
public static string DecifrarAESdeBase64(string dataToDeCrypt) { //Get the decryption key from the machine key section of the web.config MachineKeySection machineKey = (MachineKeySection)ConfigurationManager.GetSection("system.web/machineKey"); string key = machineKey.DecryptionKey; byte[] keyBytes = new UTF8Encoding(false).GetBytes(key); Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(key, keyBytes, 1000); AesManaged decryptor = new AesManaged(); //decryptor.Mode = CipherMode.CBC; decryptor.Key = rfc.GetBytes(16); decryptor.IV = rfc.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream decrypt = new CryptoStream(ms, decryptor.CreateDecryptor(), CryptoStreamMode.Write)) { byte[] dataBytes = Convert.FromBase64String(dataToDeCrypt); decrypt.Write(dataBytes, 0, dataBytes.Length); decrypt.FlushFinalBlock(); decrypt.Close(); return(new UTF8Encoding(false).GetString(ms.ToArray())); } } }
public static MachineKeySection GetUnencryptedMachineKey() { var mk = new MachineKeySection(); mk.ValidationKey = "AutoGenerate"; return(mk); }
public void ValidationAlgorithm() { MachineKeySection section = new MachineKeySection(); section.ValidationAlgorithm = "HMACRIPEMD160"; // syntax is: alg:something-deriving-from-KeyedHashAlgorithm }
public iVoteLoginProvider() { Configuration config = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); machineKey = (MachineKeySection)config.GetSection("system.web/machineKey"); }
public override void Initialize(string name, NameValueCollection config) { // // Initialize values from web.config. // if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "CustomMembershipProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "CustomMembershipProvider - Membership Provider"); } // Initialize the abstract base class. base.Initialize(name, config); pApplicationName = GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7")); pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); pWriteExceptionsToEventLog = Convert.ToBoolean(GetConfigValue(config["writeExceptionsToEventLog"], "true")); string temp_format = config["passwordFormat"]; if (temp_format == null) { temp_format = "Hashed"; } switch (temp_format) { case "Hashed": pPasswordFormat = MembershipPasswordFormat.Hashed; break; case "Encrypted": pPasswordFormat = MembershipPasswordFormat.Encrypted; break; case "Clear": pPasswordFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException("Password format not supported."); } // // Initialize Connection. // /* ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["ManPro_Memeberships_Roles"]]; if (ConnectionStringSettings == null || ConnectionStringSettings.ConnectionString.Trim() == "") { throw new ProviderException("Connection string cannot be blank."); } connectionString = ConnectionStringSettings.ConnectionString; */ //connectionString = ConfigurationManager.AppSettings["ManPro_Memeberships_Roles"]; connectionString = ConfigurationManager.ConnectionStrings["GRASP_MemberShip"].ConnectionString; // Get encryption and decryption key information from the configuration. Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); if (machineKey.ValidationKey.Contains("AutoGenerate")) if (PasswordFormat != MembershipPasswordFormat.Clear) throw new ProviderException("Hashed or Encrypted passwords " + "are not supported with auto-generated keys."); }