【发布时间】:2021-02-17 20:25:57
【问题描述】:
我有一段旧代码使用 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 文件并将机器密钥从框架应用程序复制到 .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 核心应用程序上使用相同的机器密钥,以便从该应用程序流入系统的信息能够在较旧的框架应用程序中读取,反之亦然。
【问题讨论】:
-
所以您的问题根本不是关于加密/解密,而是如何访问 app.config?另外,请更具体; “它不起作用”太含糊了。
-
值得注意的是,虽然.Net使用了app.config/web.config; .Net Core 使用 appsettings.json:docs.microsoft.com/en-us/aspnet/core/migration/…
-
我怎样才能更具体?我在问如何在涉及加密/解密的 .net 核心应用程序中使用 web.config 文件中的机器密钥。 @KlausGütter 你会建议一个更合适的标题吗?
-
我指的是“它不起作用”。你得到一个异常,一个空值,一个错误的值,......?
标签: c# .net-core cryptography