问题描述
我正在使用 C# 和 .NET Framework 开发一个加密应用程序。它的功能之一是让用户在 Windows KSP 中存储一个(或多个)RSA 非对称密钥对,将公钥导出到 BLOB 并解密消息(实际上,它只会使用 RSA 加密/解密对称密钥) 用那个特定的密钥加密。我在 System.Security.Cryptography
命名空间中使用 CNG 实现。
为了测试它的功能,我创建了一个密钥对并为其命名。之后,我使用以下函数导出了密钥:
public static byte[] GetPublicKeyBlob(string keyContainerName)
{
try
{
if (!CngKey.Exists(keyContainerName))
throw new CryptographicException($"The Key Service Provider does not contain a key with the name: '{keyContainerName}'");
cngKey = CngKey.Open(keyContainerName);
rsa = new RSACng(cngKey) { KeySize = keySize };
return rsa.Key.Export(CngKeyBlobFormat.GenericpublicBlob);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
return null;
}
{
(静态)字段如下:
public static RSACng rsa;
public static CngKey cngKey;
public static int keySize = 2048; // used
public static RSAEncryptionPadding rSAEncryptionPadding = RSAEncryptionPadding.OaepSHA512; // later
接下来,我使用以下函数来加密一些示例数据:
public static byte[] Encrypt(byte[] input,byte[] key)
{
byte[] output = null;
try
{
cngKey = CngKey.Import(key,CngKeyBlobFormat.GenericpublicBlob);
rsa = new RSACng(cngKey) { KeySize = keySize };
if (input != null)
output = rsa.Encrypt(input,rSAEncryptionPadding);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message,MessageBoxIcon.Error);
}
return output;
}
我将输出(看起来像加密函数的正常输出)并将其用作 Decrypt
函数的输入:
public static byte[] Decrypt(byte[] input,string keyContainerName)
{
byte[] output = null;
try
{
if (!CngKey.Exists(keyContainerName))
throw new CryptographicException($"The Key Service Provider does not contain a key with the name '{keyContainerName}'");
cngKey = CngKey.Open(keyContainerName);
rsa = new RSACng(cngKey) { KeySize = keySize };
if(input != null)
output = rsa.Decrypt(input,MessageBoxIcon.Error);
}
return output;
}
此处,rsa.Decrypt(input,rSAEncryptionPadding)
抛出异常并显示消息:“参数不正确。”。
我使用保存的密钥本身编写了另一个 Encrypt
函数,如下所示:
public static byte[] Encrypt(byte[] input,string publicKeyContainerName,bool setCngKey = true)
{
byte[] output = null;
try
{
if (setCngKey)
{
if (!CngKey.Exists(publicKeyContainerName))
throw new CryptographicException($"The Key Service Provider does not contain a key with the name: '{publicKeyContainerName}'");
cngKey = CngKey.Open(publicKeyContainerName);
}
rsa = new RSACng(cngKey) { KeySize = keySize };
if (input != null)
output = rsa.Encrypt(input,MessageBoxIcon.Error);
}
return output;
}
使用相同的解密函数,结果相同。
此刻我被卡住了,我不知道该怎么做才能解决这个问题。我做错了什么?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)