nun*_*mel 81 c# wcf certificate ssl-certificate x509certificate
我使用这个方法时遇到了问题 X509Store.Certificates.Find
public static X509Certificate2 FromStore(StoreName storeName,
StoreLocation storeLocation, X509FindType findType, string findValue)
{
X509Store store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly);
try
{
//findValue = "7a6fa503ab57b81d6318a51ca265e739a51ce660"
var results = store.Certificates.Find(findType, findValue, true);
return results[0];
}
finally
{
store.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,Find方法返回0 results(results.Count == 0),但如果我将findValue作为常量,则该方法会找到证书.
public static X509Certificate2 FromStore(StoreName storeName,
StoreLocation storeLocation, X509FindType findType, string findValue)
{
X509Store store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly);
try
{
//findValue= "7a6fa503ab57b81d6318a51ca265e739a51ce660"
var results = store.Certificates.Find(findType,
"7a6fa503ab57b81d6318a51ca265e739a51ce660", true);
return results[0];
}
finally
{
store.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
Aas*_*set 130
我想您已将指纹从Windows证书信息对话框复制粘贴到您的代码中(如果这是一个简化示例,则复制粘贴到配置文件中).令人讨厌的是,指纹文本框中的第一个字符是不可见的Unicode"从左到右标记"控制字符.尝试选择开始字符串引用和指纹的第一个字符,删除它们(这也将删除不可见的字符),并手动重新输入.
我今天自己遭受了这种奇怪的行为,我花了一个多小时来弄明白这一点.我终于看到它的方式是通过使用调试器来检查的长度和哈希码findValue和的Thumbprint证书对象.
jhi*_*den 45
我在这里得到了一些答案并将它们组合成一个静态方法,该方法负责删除特殊字符和大写字母.希望其他人可以使用它.
public static X509Certificate2 GetCertificate(string thumbprint)
{
// strip any non-hexadecimal values and make uppercase
thumbprint = Regex.Replace(thumbprint, @"[^\da-fA-F]", string.Empty).ToUpper();
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
store.Open(OpenFlags.ReadOnly);
var certCollection = store.Certificates;
var signingCert = certCollection.Find(X509FindType.FindByThumbprint, thumbprint, false);
if (signingCert.Count == 0)
{
throw new FileNotFoundException(string.Format("Cert with thumbprint: '{0}' not found in local machine cert store.", thumbprint));
}
return signingCert[0];
}
finally
{
store.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 22
我有同样的问题并解决了它:
我将指纹从mmc直接复制到了VS. 我比较了字符串并没有发现任何差异.
用hash.length检查长度,有一个区别,41对40.
通过将其复制出mmc,在字符串中添加了一个不可见的字符.
解决:
它正在发挥作用.
我成了这个受害者.不仅在指纹的Windows控制台管理单元中显示Unicode"从左到右"字符,而且它还具有小写十六进制字符,每两个字符之间有空格.CertUtil的输出也有小写字符和空格.为了获得匹配,我必须将findValue指定为已转换为的字符串
这也使我绊倒了,我写了这个函数来清理从MMC复制和粘贴时的指纹:
public string CleanThumbprint(string mmcThumbprint)
{
//replace spaces, non word chars and convert to uppercase
return Regex.Replace(mmcThumbprint, @"\s|\W", "").ToUpper();
}
...
var myThumbprint = CleanThumbprint("?b3 ab 84 e5 1e e5 e4 75 e7 a5 3e 27 8c 87 9d 2f 05 02 27 56");
var myCertificate = certificates.Find(X509FindType.FindByThumbprint, myThumbprint, true)[0];
Run Code Online (Sandbox Code Playgroud)
var results = store.Certificates.Find(findType, findType, true);
Run Code Online (Sandbox Code Playgroud)
我认为你的意思是第二个参数是“findValue”。