Mar*_*roš 0 .net exception-handling certificate x509certificate2
我想验证证书密码。此时我有基于处理 CryptographicException 和检查异常消息的代码。但这种方法取决于英语文化信息。
public bool VerifyPassword(byte[] fileContent, string password)
{
try
{
var certificate = new X509Certificate2(fileContent, password);
}
catch (CryptographicException ex)
{
if (ex.Message.StartsWith("The specified network password is not correct."))
{
return false;
}
throw;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
我一直在寻找如何验证证书密码的其他解决方案,但没有成功。
如何验证证书密码的正确方法是什么?
我很感激任何想法......
几个月后,我找到了更好的解决方案(也许是最好的)。它基于 CryptograhpicExcaption 的 HResult 值。
static bool VerifyPassword(byte[] fileContent, string password)
{
try
{
// ReSharper disable once UnusedVariable
var certificate = new X509Certificate2(fileContent, password);
}
catch (CryptographicException ex)
{
if ((ex.HResult & 0xFFFF) == 0x56)
{
return false;
};
throw;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
所有 HResults(系统错误代码)文档均可在以下网址获得:https ://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx