C#中将注册表存储的加密密钥转换为可用字符串求助
问题:注册表中读取的密钥无法转换为可用字符串用于加密操作
问题描述
我正在为自己的加密库开发一款CLI测试程序,后续会推出GUI版本。目前我将加密密钥存储在注册表中,已实现密钥写入功能,但无法将注册表中的密钥数据转换为可用字符串用于加密操作。我对注册表操作较为陌生,近期才开始将其用作程序数据存储,当前使用.NET 6开发。
相关代码
加密方法代码
internal String Encrypt() { Console.Clear(); Console.Write("Encryption\nPlease enter the path to the file you want to encrypt: "); String FileInPath = Console.ReadLine(); String FileOutPath = ""; String FileData = ""; while (FileInPath == "") { FileInPath = RetryPathIn(); } String RetryPathIn() { Console.WriteLine(".>>"); String PathInStr = Console.ReadLine(); return PathInStr; } Console.Write("\nPlease enter the path of the file you want to decrypt: "); FileOutPath = Console.ReadLine(); while (FileOutPath == "") { FileOutPath = RetryEncrypt(); } String RetryEncrypt() { Console.WriteLine(".>>"); String FileOutPathStr = Console.ReadLine(); return FileOutPathStr; } object Key = Registry.CurrentUser.OpenSubKey(@"Software\NikkieDev Software").GetValue("Key"); String KeyStr = Key.ToString(); String FileOutData = ""; if (Key!=null) { FileOutData = Crypt.Encrypt(FileData, KeyStr); } var file = File.Create(FileOutPath); file.Close(); File.WriteAllText(FileOutPath, FileOutData); return $"Data has been encrypted and saved in {FileOutPath}"; }
注册表写入密钥代码
internal void Initialize() { String SettingsFile = File.ReadAllText(CoreObject.DataFile); dynamic _JsonObj = JsonConvert.DeserializeObject(SettingsFile); if (_JsonObj["KeyGenerated"] == 0) { RegistryKey RegData = Registry.CurrentUser.CreateSubKey(@"Software\NikkieDev Software"); String NewKey = Key.CreateKey(); RegData.SetValue("Key", NewKey); _JsonObj["KeyGenerated"] = 1; dynamic NewData = JsonConvert.SerializeObject(_JsonObj, Formatting.Indented); File.WriteAllText(CoreObject.DataFile, NewData); RegData.Close(); } }
补充说明
我使用的加密库为bungocrypt_cs,其中CreateKey()返回字符串类型的密钥,Crypt.Encrypt()接收密钥和数据并进行字符置换加密。
内容的提问来源于stack exchange,提问作者NikkieDev
相关产品推荐
相关产品推荐

