private string SaveConfig(string connectionstr) { string result; try { Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath); using (System.Security.Cryptography.RijndaelManaged cryptographer = this.GetCryptographer()) { configuration.AppSettings.Settings["IV"].Value = System.Convert.ToBase64String(cryptographer.IV); configuration.AppSettings.Settings["Key"].Value = System.Convert.ToBase64String(cryptographer.Key); } System.Web.Configuration.MachineKeySection machineKeySection = (System.Web.Configuration.MachineKeySection)configuration.GetSection("system.web/machineKey"); machineKeySection.ValidationKey = Isv.CreateKey(20); machineKeySection.DecryptionKey = Isv.CreateKey(24); machineKeySection.Validation = System.Web.Configuration.MachineKeyValidation.SHA1; machineKeySection.Decryption = "3DES"; configuration.ConnectionStrings.ConnectionStrings["HidistroSqlServer"].ConnectionString = connectionstr; configuration.ConnectionStrings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); configuration.Save(); configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath); configuration.AppSettings.Settings.Remove("Installer"); configuration.Save(); result = ""; } catch (System.Exception ex) { result = ex.Message; } return(result); }
public UniMembershipProvider() { pApplicationName = "unicloud"; pName = "UniMembershipProvider"; Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); }
// the only required parameter is 'machineKeySection'; other parameters are just used for unit testing internal MachineKeyMasterKeyProvider(MachineKeySection machineKeySection, string applicationId = null, string applicationName = null, CryptographicKey autogenKeys = null, KeyDerivationFunction keyDerivationFunction = null) { _machineKeySection = machineKeySection; _applicationId = applicationId; _applicationName = applicationName; _autogenKeys = autogenKeys; _keyDerivationFunction = keyDerivationFunction; }
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 override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentException("config"); if (String.IsNullOrEmpty(name)) name = DEFAULT_PROVIDER_NAME; base.Initialize(name, config); applicationName = ConfigurationHelper.GetConfigStringValueOrDefault(config, ConfigurationHelper.CONFIG_APPLICATION_NAME_FIELD, System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); description = ConfigurationHelper.GetConfigStringValueOrDefault(config, ConfigurationHelper.CONFIG_DESCRIPTION_FIELD, "Couch DB Membership Provider"); enablePasswordReset = ConfigurationHelper.GetConfigBoolValueOrDefault(config, ConfigurationHelper.CONFIG_ENABLE_PASSWORD_RESET, false); enablePasswordRetrieval = false; maxInvalidPasswordAttempts = ConfigurationHelper.GetConfigIntValueOrDefault(config, ConfigurationHelper.CONFIG_MAX_INVALID_PASSWORD_ATTEMPTS, 5); minRequiredNonAlphanumericCharacters = ConfigurationHelper.GetConfigIntValueOrDefault(config, ConfigurationHelper.CONFIG_MIN_REQUIRED_NON_ALPHANUMERIC_CHARACTERS, 0); minRequiredPasswordLength = ConfigurationHelper.GetConfigIntValueOrDefault(config, ConfigurationHelper.CONFIG_MIN_REQUIRED_PASSWORD_LENGTH, 8); passwordAttemptWindow = ConfigurationHelper.GetConfigIntValueOrDefault(config, ConfigurationHelper.CONFIG_PASSWORD_ATTEMPT_WINDOW, 10); passwordFormat = MembershipPasswordFormat.Hashed; passwordStrengthRegularExpression = ConfigurationHelper.GetConfigStringValueOrDefault(config, ConfigurationHelper.CONFIG_PASSWORD_STRENGTH_REGULAR_EXPRESSION, String.Empty); requiresQuestionAndAnswer = ConfigurationHelper.GetConfigBoolValueOrDefault(config, ConfigurationHelper.CONFIG_REQUIRES_QUESTION_AND_ANSWER, false); requiresUniqueEmail = true; providerName = name; couchDbServerName = ConfigurationHelper.MembershipCouchDbServerName; couchDbServerPort = ConfigurationHelper.MembershipCouchDbServerPort; couchDbDatabaseName = ConfigurationHelper.MembershipCouchDbDatabaseName; if (String.IsNullOrEmpty(couchDbDatabaseName)) throw new ProviderException(Strings.CouchDbConfigurationDatabaseNameMissing); machineKeySection = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection("system.web/machineKey"); if(machineKeySection == null) throw new ProviderException(Strings.HashedPasswordsRequireMachineKey); if (machineKeySection.ValidationKey.ToLower().Contains("Autogenerate".ToLower())) throw new ProviderException(Strings.HashedPasswordsRequireMachineKey); }
private bool SaveConfig(out string errorMsg) { bool result; try { Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(base.Request.ApplicationPath); using (System.Security.Cryptography.RijndaelManaged cryptographer = this.GetCryptographer()) { configuration.AppSettings.Settings["IV"].Value = System.Convert.ToBase64String(cryptographer.IV); configuration.AppSettings.Settings["Key"].Value = System.Convert.ToBase64String(cryptographer.Key); } System.Web.Configuration.MachineKeySection machineKeySection = (System.Web.Configuration.MachineKeySection)configuration.GetSection("system.web/machineKey"); machineKeySection.ValidationKey = Install.CreateKey(20); machineKeySection.DecryptionKey = Install.CreateKey(24); machineKeySection.Validation = System.Web.Configuration.MachineKeyValidation.SHA1; machineKeySection.Decryption = "3DES"; configuration.ConnectionStrings.ConnectionStrings["HidistroSqlServer"].ConnectionString = this.GetConnectionString(); configuration.ConnectionStrings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); configuration.Save(); errorMsg = null; result = true; } catch (System.Exception ex) { errorMsg = ex.Message; result = false; } return(result); }
public void Decryption_RC2 () { MachineKeySection section = new MachineKeySection (); Assert.AreEqual ("Auto", section.Decryption, "before"); section.Decryption = "alg:RC2"; Assert.AreEqual ("alg:RC2", section.Decryption, "after"); }
protected override MachineKeySection GetMachineKeySection() { var mk = new MachineKeySection(); mk.DecryptionKey = "0A5D40CA5C48726556180200D9DBE44A8FE58A8E6A3E8CC153BFC631833BA0FE"; mk.ValidationKey = "7D30287B722BF7141915476F0609FFD604CBB5243D8574F85BA5B496FA58D3EE49A8CE1E07E958F145967495A56E5B6298082070C0488F7B4FC42EDE9956422E"; mk.Validation = MachineKeyValidation.SHA1; mk.Decryption = "AES"; return mk; }
public void GetMachineKey_MachineKeyConfigured_ReturnsMachineKey() { var config = new MachineKeySection { ValidationKey = MachineKeyValidation }; var helper = new MachineKeyConfigurationHelper(config); var key = helper.GetMachineKey(); Assert.AreEqual(_expectedMachineKey, key); }
public UniMembershipProvider() { _pApplicationName = "unicloud"; _pName = "UniMembershipProvider"; var cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath); _machineKey = (MachineKeySection) cfg.GetSection("system.web/machineKey"); _userRepository = UniContainer.Resolve<IUserRepository>(); _userRoleRepository = UniContainer.Resolve<IUserRoleRepository>(); }
public void Decryption_InvalidName () { MachineKeySection section = new MachineKeySection (); Assert.AreEqual ("Auto", section.Decryption, "before"); section.Decryption = "alg:UnexistingType"; // looks like the problem is found (much) later Assert.AreEqual ("alg:UnexistingType", section.Decryption, "Decryption"); }
public AccountManagement() { // 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"); formsConfig = (AuthenticationSection) cfg.GetSection("system.web/authentication"); }
public void DefaultValues () { MachineKeySection section = new MachineKeySection (); Assert.AreEqual (MachineKeyCompatibilityMode.Framework20SP1, section.CompatibilityMode, "CompatibilityMode"); Assert.AreEqual ("Auto", section.Decryption, "Decryption"); Assert.AreEqual ("AutoGenerate,IsolateApps", section.DecryptionKey, "DecryptionKey"); Assert.AreEqual (MachineKeyValidation.HMACSHA256, section.Validation, "Validation"); Assert.AreEqual ("HMACSHA256", section.ValidationAlgorithm, "ValidationAlgorithm"); Assert.AreEqual ("AutoGenerate,IsolateApps", section.ValidationKey, "ValidationKey"); }
/// <summary> /// 静态构造方法。 /// </summary> static SecurityExtensions() { var config = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath); MachineKey = (MachineKeySection)config.GetSection("system.web/machineKey"); if (MachineKey.Decryption == "Auto") { MachineKey.DecryptionKey = KeyCreator.CreateKey(0x18); MachineKey.ValidationKey = KeyCreator.CreateKey(0x40); } }
internal static byte [] DecryptionKey192Bits(MachineKeySection section) { if (section == null) { throw new ArgumentNullException("section"); } if (decryption_key_192bits == null) { SetDecryptionKey(section.DecryptionKey); } return(decryption_key_192bits); }
// This constructor is used only for testing purposes and by the singleton provider // and should not otherwise be called during ASP.NET request processing. internal AspNetCryptoServiceProvider(MachineKeySection machineKeySection = null, ICryptoAlgorithmFactory cryptoAlgorithmFactory = null, IMasterKeyProvider masterKeyProvider = null, IDataProtectorFactory dataProtectorFactory = null, KeyDerivationFunction keyDerivationFunction = null) { _machineKeySection = machineKeySection; _cryptoAlgorithmFactory = cryptoAlgorithmFactory; _masterKeyProvider = masterKeyProvider; _dataProtectorFactory = dataProtectorFactory; _keyDerivationFunction = keyDerivationFunction; // This CryptoServiceProvider is active if specified as such in the <system.web/machineKey> section IsDefaultProvider = (machineKeySection != null && machineKeySection.CompatibilityMode >= MachineKeyCompatibilityMode.Framework45); // The DataProtectorCryptoService is active if specified as such in config _isDataProtectorEnabled = (machineKeySection != null && !String.IsNullOrWhiteSpace(machineKeySection.DataProtectorType)); }
internal static byte [] ValidationKeyBytes(MachineKeySection section) { if (section == null) { throw new ArgumentNullException("section"); } if (validation_key == null) { SetValidationKey(section.ValidationKey); } return(validation_key); }
private static void EnsureConfig() { if (s_config == null) { lock (s_initLock) { if (s_config == null) { MachineKeySection machineKey = RuntimeConfig.GetAppConfig().MachineKey; machineKey.ConfigureEncryptionObject(); s_config = machineKey; s_compatMode = machineKey.CompatibilityMode; } } } }
// It test all existing (as of r61933) configuration // sections that use PropertyHelper.NonEmptyStringValidator. public void NullableStringProperties () { new AnonymousIdentificationSection ().CookieName = null; new AnonymousIdentificationSection ().CookiePath = null; new AssemblyInfo (null); new BufferModeSettings (null, 0x10000, 0x1000, 10, TimeSpan.FromMinutes (1), TimeSpan.FromSeconds (30), 10); new BuildProvider (null, null); new ClientTarget (null, null); new CodeSubDirectory (null); new EventMappingSettings (null, null); new ExpressionBuilder (null, null); FormsAuthenticationConfiguration fac = new FormsAuthenticationConfiguration (); // I don't like this test though. fac.DefaultUrl = null; fac.LoginUrl = null; fac.Name = null; fac.Path = null; new HttpHandlerAction (null, null, null); new HttpModuleAction (null, null); MachineKeySection mks = new MachineKeySection (); // algorithms are limited // mks.Decryption = null; mks.DecryptionKey = null; mks.ValidationKey = null; new MembershipSection ().DefaultProvider = null; new NamespaceInfo (null); new OutputCacheProfile (null); new ProfileSettings (null); RoleManagerSection rms = new RoleManagerSection (); rms.CookieName = null; rms.CookiePath = null; rms.DefaultProvider = null; new RuleSettings (null, null, null); new SqlCacheDependencyDatabase (null, null); new TagMapInfo (null, null); new TagPrefixInfo (null, null, null, null, null); new TransformerInfo (null, null); new TrustLevel (null, null); new TrustSection ().Level = null; new UrlMapping (null, null); // WebControlsSection.ClientScriptsLocation is not settable new WebPartsPersonalization ().DefaultProvider = null; }
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); Assert.IsNull (MachineKeySectionUtils.Decrypt (section, encdata), "bad padding"); }
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_HMACSHA512 () { MachineKeySection section = new MachineKeySection (); section.Validation = MachineKeyValidation.HMACSHA512; Validation_RoundTrip (section); }
public void EncryptSign_RoundTrip_HMACSHA384 () { MachineKeySection section = new MachineKeySection (); section.Validation = MachineKeyValidation.HMACSHA384; EncryptSign_RoundTrip (section); }
public void Validation_RoundTrip (MachineKeySection section) { byte [] data = new byte [] { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 }; byte [] block = MachineKeySectionUtils.Sign (section, data); Assert.AreEqual (data, MachineKeySectionUtils.Verify (section, block), "OK"); // changing last byte for (int i = 0; i < data.Length; i++) { byte b = block [i]; block [i] = ChangeByte (b); Assert.IsNull (MachineKeySectionUtils.Verify (section, block), "bad-" + i.ToString ()); block [i] = b; } }
public void EncryptSign_RoundTrip (MachineKeySection section) { byte [] data = new byte [14]; byte [] block = MachineKeySectionUtils.EncryptSign (section, data); byte [] decdata = MachineKeySectionUtils.VerifyDecrypt (section, block); Assert.AreEqual (data, decdata, "roundtrip"); // changing a byte of the data byte b0 = block [0]; block [0] = ChangeByte (b0); Assert.IsNull (MachineKeySectionUtils.VerifyDecrypt (section, block), "bad data"); block [0] = b0; // changing a byte of the signature byte be = block [block.Length - 1]; block [block.Length - 1] = ChangeByte (be); Assert.IsNull (MachineKeySectionUtils.VerifyDecrypt (section, block), "bad signature"); }
public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "ELMemebershipProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "ELinq Membership provider"); } base.Initialize(name, config); maxInvalidPasswordAttempts = config.Get<int>( "maxInvalidPasswordAttempts",5); passwordAttemptWindow = config.Get<int>("passwordAttemptWindow",10); minRequiredNonAlphanumericCharacters = config.Get<int>("minRequiredNonAlphanumericCharacters",1); minRequiredPasswordLength = config.Get<int>("minRequiredPasswordLength",7); passwordStrengthRegularExpression =config.Get<string>("passwordStrengthRegularExpression", ""); enablePasswordReset =config.Get<bool>("enablePasswordReset",true); enablePasswordRetrieval = config.Get<bool>("enablePasswordRetrieval",true); requiresQuestionAndAnswer = config.Get<bool>("requiresQuestionAndAnswer",false); requiresUniqueEmail =config.Get<bool>("requiresUniqueEmail",true); switch (config.Get<string>("passwordFormat", "Clear")) { case "Hashed": passwordFormat = MembershipPasswordFormat.Hashed; break; case "Encrypted": passwordFormat = MembershipPasswordFormat.Encrypted; break; case "Clear": passwordFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException("Password format not supported."); } //Encryption skipped var 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."); var connectionStringName = config["connectionStringName"]; UnitOfWork.Configure(connectionStringName); ApplicationName = config["applicationName"]; if (ApplicationName.IsNullOrEmpty()) ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath; else if(ApplicationName != "/") { var site = UnitOfWork.Current.CreateRepository<Site>().FirstOrDefault(p => p.Id == ApplicationName && p.Status == Enums.SiteStatus.Enable); if(site == null) throw new ProviderException("ApplicationName not exists."); } }
public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "IridioMembershipProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Iridio Membership provider"); } base.Initialize(name, config); ValidatingPassword += IridioMembershipProvider_ValidatingPassword; 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")); WriteExceptionsToEventLog = Convert.ToBoolean(GetConfigValue(config["writeExceptionsToEventLog"], "true")); string temp_format = config["passwordFormat"]; if (temp_format == null) temp_format = "Clear"; temp_format = temp_format.ToUpper(); 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's format not supported"); } machineKey = GetMachineKeySection(); if (machineKey.ValidationKey.Contains("AutoGenerate")) if (PasswordFormat != MembershipPasswordFormat.Clear) throw new ProviderException("Hashed or Encrypted passwords do not support autogenerated keys"); SetUserRepository(); }
public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "CMSMembershipProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "CMS Membership provider"); } base.Initialize(name, config); pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); var Db = GetDb(); pMinRequiredPasswordLength = Db.Setting("PasswordMinLength", "7").ToInt(); pMinRequiredNonAlphanumericCharacters = DbUtil.Db.Setting("PasswordRequireSpecialCharacter", "true").ToBool() ? 1 : 0; 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")); 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."); } // 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."); }
protected override void Reset(ConfigurationElement parentElement) { MachineKeySection section = parentElement as MachineKeySection; base.Reset(parentElement); }
/// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception> /// /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception> /// /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized.</exception> 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 = "MongoDBMembershipProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Sample MongoDB 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")); pMongoProviderDatabaseName = Convert.ToString(GetConfigValue(config["mongoProviderDatabaseName"], "ASPNetProviderDB")); pmongoProviderMembershipCollectionName = Convert.ToString(GetConfigValue(config["mongoProviderCollectionName"], "Users")); 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 MongoDB ConnectionString. // ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]]; if (ConnectionStringSettings == null || ConnectionStringSettings.ConnectionString.Trim() == "") { throw new ProviderException("Connection string cannot be blank."); } connectionString = ConnectionStringSettings.ConnectionString; Configuration cfg = null; if (System.Web.HttpContext.Current != null && !System.Web.HttpContext.Current.Request.PhysicalPath.Equals(string.Empty)) cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); //if (Directory.Exists(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath)) // When running from a web app // cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); else // when running from a test case. cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Get encryption and decryption key information from the configuration. 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."); // Ensures that the MongoDB collection has the proper indices defined. EnsureIndices(); }
public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException("config"); } if (String.IsNullOrEmpty(name)) { name = "SimpleDbMembershipProvider"; } base.Initialize(name, config); string tempFormat = config["passwordFormat"]; if (tempFormat == null) { tempFormat = "Hashed"; } switch (tempFormat) { case "Hashed": { this._passwordFormat = MembershipPasswordFormat.Hashed; break; } case "Encrypted": { this._passwordFormat = MembershipPasswordFormat.Encrypted; break; } case "Clear": { this._passwordFormat = MembershipPasswordFormat.Clear; break; } } this._simpleDBClient = new AmazonSimpleDBClient( Settings.Default.AWSAccessKey.Trim(), Settings.Default.AWSSecretAccessKey.Trim() ); CreateDomainRequest cdRequest = new CreateDomainRequest() .WithDomainName(Settings.Default.AWSMembershipDomain); try { this._simpleDBClient.CreateDomain(cdRequest); } catch (Exception e) { System.Diagnostics.Debug.Write(String.Concat(e.Message, "\r\n", e.StackTrace)); this.VerifyKeys(); } Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath); this._machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); }
public void Encrypt_RoundTrip_TripleDES () { MachineKeySection section = new MachineKeySection (); section.Validation = MachineKeyValidation.TripleDES; Encrypt_RoundTrip (section); }
public void EncryptSign_RoundTrip_AES () { MachineKeySection section = new MachineKeySection (); section.Validation = MachineKeyValidation.AES; EncryptSign_RoundTrip (section); }
public void Encrypt_RoundTrip_SHA1 () { MachineKeySection section = new MachineKeySection (); section.Validation = MachineKeyValidation.SHA1; Encrypt_RoundTrip (section); }
public static MachineKeySection GetEncryptedMachineKey() { var mk = new MachineKeySection(); mk.ValidationKey = "32F2AABDF6A7B29A509296629C659885774B58A8FF63FC59B5A68E72F7C10591AD68DA58FA312F93F6D8EAE3CE13424D356811DC9254145A4899AA99B83AE4C8"; mk.DecryptionKey = "2FFF6B9F5703111234CD41A13D7ABF9176554A37F219952D39E1398EE53B830F"; mk.Validation = MachineKeyValidation.SHA1; mk.Decryption = "AES"; return mk; }