使用web.config文件中的machinekey加密和解密.net核心中的字符串



我有一段旧代码,它使用AES和存储在web.config文件中的机器密钥对字符串进行加密和解密。这是一个框架4应用程序。以下是进行加密和解密的类的一些代码:

private static readonly MachineKeySection MachineKeyConfig =
(MachineKeySection)ConfigurationManager
.GetSection("system.web/machineKey");
private readonly byte[] _key;
private readonly byte[] _iv;

public AESEncryption()
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(MachineKeyConfig.DecryptionKey, new byte[] { byte values removed });
_key = pdb.GetBytes(32);
_iv = pdb.GetBytes(16);
}
public AESEncryption(string key)
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, new byte[] { byte value removed });
_key = pdb.GetBytes(32);
_iv = pdb.GetBytes(16);
}

public string Encrypt(string value)
{

if (string.IsNullOrWhiteSpace(value))
{
return value;
}
byte[] clearBytes = Encoding.Unicode.GetBytes(value);
using (Aes encryptor = Aes.Create())
{
if (encryptor != null)
{
encryptor.Padding = PaddingMode.PKCS7;
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(_key, _iv), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.FlushFinalBlock();
value = Convert.ToBase64String(ms.ToArray());
}
}
}
return value;
}
public string Decrypt(string value)
{

if (string.IsNullOrWhiteSpace(value))
{
return value;
}
byte[] cipherBytes = Convert.FromBase64String(value);
using (Aes encryptor = Aes.Create())
{
if (encryptor != null)
{
encryptor.Padding = PaddingMode.PKCS7;
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(_key, _iv), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.FlushFinalBlock();
value = Encoding.Unicode.GetString(ms.ToArray());
}
}
}

return value;
}

加密非常直接。我需要使用在.net core 3.1控制台应用程序中用于加密/解密的相同机器密钥,将一些数据输入使用相同机器密钥加密的系统。我添加了一个App.config文件,并将machinekey从Framework应用程序复制到.net核心应用程序。这是配置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<machineKey decryption="AES" decryptionKey="[decryptionkey]" validation="AES" validationKey="[validation key]" />
</configuration>

从app.config文件中提取此密钥时遇到问题。我试过这个:

private static readonly MachineKeySection MachineKeyConfig =
(MachineKeySection)ConfigurationManager
.GetSection("system.web/machineKey");

它不起作用。我需要在.net核心应用程序上使用相同的machinekey,以便从该应用程序流到系统的信息能够在旧的Framework应用程序中读取,反之亦然。

我从旧的web.config文件中移动了machinekey值,并将它们作为单独的键值添加到app.config的appSettings部分。完成后,我导入了System.Configuration,并使用配置管理器提取了所需的值。

private readonly string decryptionKey = ConfigurationManager.AppSettings.Get("decryptionKey");

然后,我可以像以前一样使用这个值,并验证解密和加密值确实相同。我以前遇到的问题是,如果我在应用程序配置中包含machineKey,我会得到一个错误,即这是一个无法识别的部分:

ConfigurationErrorsException:无法识别的配置节machineKey

所以我把这些值移到Appsettings中,并把它们拉到那里。

最新更新