继续Error occurred while decoding OAEP padding
虽然我已经阅读了以前所有的问题/帖子,但我找不到解决方案。
我将加密的密钥保存在文件中。后来我正在通过Windows服务对其进行解密。这两个进程都在同一台机器上运行,并调用相同的程序集(核心)来加密和解密
我被困了,因为我无法理解为什么它会抛出异常。
我的代码
class CryptographyKeyProvider : ICryptographyKeyProvider, ICryptographySaver
{
private readonly ICryptographyFilesProvider _provider;
public CryptographyKeyProvider(ICryptographyFilesProvider provider)
{
_provider = provider;
}
#region Util
private static readonly CryptoKeyAccessRule Rule =
new CryptoKeyAccessRule(WindowsIdentity.GetCurrent().Name.ToLower().Split('\\').Last(),
CryptoKeyRights.FullControl,
AccessControlType.Allow);
private static CspParameters CspProvider(string keyContainerName, CspProviderFlags flags = CspProviderFlags.NoFlags)
{
var cp = new CspParameters
{
KeyContainerName = keyContainerName,
Flags = CspProviderFlags.NoPrompt | CspProviderFlags.UseMachineKeyStore | flags,
CryptoKeySecurity = new CryptoKeySecurity()
};
cp.CryptoKeySecurity.SetAccessRule(Rule);
return cp;
}
private static void SaveFile(string keyFile, string encryptedPw)
{
try
{
File.WriteAllText(keyFile, encryptedPw);
}
catch (Exception ex)
{
throw new Exception("Error saving file. " + ex.Message);
}
}
private static string Encrypt(string text, CspParameters cp)
{
string encryptedPw;
try
{
using (var rsa = new RSACryptoServiceProvider(cp))
encryptedPw = Convert.ToBase64String(rsa.Encrypt(Encoding.Unicode.GetBytes(text), true));
}
catch (Exception ex)
{
throw new Exception("Errror encrypting data. " + ex.Message);
}
return encryptedPw;
}
private static void ClearContainer(CspParameters cp)
{
try
{
using (var rsa = new RSACryptoServiceProvider(cp) { PersistKeyInCsp = false })
rsa.Clear();
}
catch (CryptographicException ex)
{ }
catch (Exception ex)
{
throw new Exception("Error cleaning encrypt key. " + ex.Message);
}
}
private static byte[] Decrypt(string containerName, string encriptedData)
{
RSACryptoServiceProvider rsa;
try
{
var cp = CspProvider(containerName, CspProviderFlags.UseExistingKey);
rsa = new RSACryptoServiceProvider(cp);
}
catch (Exception ex)
{
throw new Exception("Error accessing container. " + ex.Message);
}
return rsa.Decrypt(Convert.FromBase64String(encriptedData), true);
}
#endregion
public byte[] Key1
{
get
{
var encriptedData = File.ReadAllText(_provider.Key1File);
return Decrypt(_provider.Key1ContainerName, encriptedData);
}
}
public void SaveKeyOwner(string text)
{
if (File.Exists(_provider.Key1File))
{
throw new Exception("File already exists");
}
var cp = CspProvider(_provider.Key1ContainerName);
ClearContainer(cp);
SaveFile(_provider.Key1File, Encrypt(text, cp));
}
}
异常
System.Security.Cryptography.CryptographicException: Error occurred while decoding OAEP padding.