bool ReEncryptKey(string oldPassword, string newPassword) { HttpContext context = HiContext.Current.Context; XmlDocument document = new XmlDocument(); string filename = context.Request.MapPath(Globals.ApplicationPath + "/config/key.config"); string str2 = context.Request.MapPath(Globals.ApplicationPath + "/config/key.config.bak"); try { document.Load(filename); } catch { document.Load(str2); } if (int.Parse(document.SelectSingleNode("Settings/Token").InnerText) == this.UserId) { XmlNode node = document.SelectSingleNode("Settings/Key"); byte[] plaintext = Cryptographer.DecryptWithPassword(Convert.FromBase64String(node.InnerText), oldPassword); node.InnerText = Convert.ToBase64String(Cryptographer.EncryptWithPassword(plaintext, newPassword)); document.Save(filename); document.Save(str2); } return(true); }
//创建key bool CreateKey(int userId, out string errorMsg) { bool flag = false; try { byte[] plaintext = KeyManager.GenerateSymmetricKey(typeof(RijndaelManaged)); string filename = Request.MapPath(Globals.ApplicationPath + "/config/key.config"); byte[] inArray = Cryptographer.EncryptWithPassword(plaintext, password); XmlDocument document = new XmlDocument(); document.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine + "<Settings><Token></Token><Key></Key></Settings>"); document.SelectSingleNode("Settings/Token").InnerText = userId.ToString(CultureInfo.InvariantCulture); document.SelectSingleNode("Settings/Key").InnerText = Convert.ToBase64String(inArray); //保存文件 document.Save(filename); document.Save(Request.MapPath(Globals.ApplicationPath + "/config/key.config.bak")); CryptographyUtility.ZeroOutBytes(inArray); byte[] encryptedKey = System.Security.Cryptography.ProtectedData.Protect(plaintext, null, System.Security.Cryptography.DataProtectionScope.LocalMachine); using (Stream stream = new FileStream(Request.MapPath(Globals.ApplicationPath + "/config/Hishop.key"), FileMode.Create)) { KeyManager.Write(stream, encryptedKey, DataProtectionScope.LocalMachine); } CryptographyUtility.ZeroOutBytes(encryptedKey); CryptographyUtility.ZeroOutBytes(plaintext); errorMsg = ""; flag = true; } catch (Exception exception) { errorMsg = exception.Message; } return(flag); }