const string provider = "RsaProtectedConfigurationProvider"; Configuration config = null; config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // 加密连接字符串 ConfigurationSection section = config.ConnectionStrings; if ((section.SectionInformation.IsProtected == false) && (section.ElementInformation.IsLocked == false)) { section.SectionInformation.ProtectSection(provider); section.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Full); }
这样控制台所在目录或者IIS发布目录下连接将是加密字符串.
如果报错,说明机器上没有RSA容器,可通过
aspnet_regiis -pc "MyKeys" -exp
aspnet_regiis -pa "MyKeys" "NT AUTHORITYNETWORK SERVICE"
创建,具体参见:http://msdn.microsoft.com/en-us/library/2w117ede.aspx