本文整理匯總了C#中System.Security.Cryptography.X509Certificates.X509Store.Close方法的典型用法代碼示例。如果您正苦於以下問題:C# X509Store.Close方法的具體用法?C# X509Store.Close怎麽用?C# X509Store.Close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Security.Cryptography.X509Certificates.X509Store
的用法示例。
在下文中一共展示了X509Store.Close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: AddCertificate
/// <summary>
/// Adds a certificate to a cert store in the local machine.
/// </summary>
/// <param name="certificate">The file path to find the certificate file.</param>
/// <param name="storeName">Name of the certificate store.</param>
/// <param name="storeLocation">Location of the certificate store.</param>
public static void AddCertificate(X509Certificate2 certificate, StoreName storeName, StoreLocation storeLocation)
{
X509Store store = null;
try
{
store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly | OpenFlags.ReadWrite);
var certificates = from cert in store.Certificates.OfType<X509Certificate2>()
where cert.Thumbprint == certificate.Thumbprint
select cert;
if (certificates.FirstOrDefault() == null)
{
store.Add(certificate);
Console.WriteLine(string.Format("Added certificate with thumbprint {0} to store '{1}', has private key: {2}.", certificate.Thumbprint, storeName.ToString(), certificate.HasPrivateKey));
store.Close();
store = null;
}
}
catch (Exception ex)
{
throw new Exception(String.Format("AddCert exception storeName={0} storeLocation={1}", storeName.ToString(), storeLocation.ToString()), ex);
}
finally
{
if (store != null)
{
store.Close();
}
}
}
示例2: Main
private static void Main(string[] args)
{
Task.Run(async () =>
{
Console.WriteLine("Enter PIN: ");
string pin = Console.ReadLine();
WebRequestHandler handler = new WebRequestHandler();
handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
using (HttpClient client = new HttpClient(handler, true))
{
client.BaseAddress = new Uri(string.Format(@"https://{0}:{1}", MachineName, RemotePort));
X509Store store = null;
try
{
var response = await client.GetAsync("certs/" + pin);
response.EnsureSuccessStatusCode();
byte[] rawCert = await response.Content.ReadAsByteArrayAsync();
X509Certificate2Collection certs = new X509Certificate2Collection();
certs.Import(rawCert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.UserKeySet);
store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
X509Certificate2Collection oldCerts = new X509Certificate2Collection();
foreach (var cert in certs)
{
oldCerts.AddRange(store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false));
}
store.RemoveRange(certs);
store.AddRange(certs);
store.Close();
Console.WriteLine("Success");
}
catch (HttpRequestException e)
{
Console.WriteLine("Error communicating with vcremote. Make sure that vcremote is running in secure mode and that a new client cert has been generated.");
}
finally
{
if (store != null)
{
store.Close();
}
}
}
}).Wait();
}
示例3: SetUp
public void SetUp()
{
X509Certificate2 testCA = new X509Certificate2("../../imports/CA.cer");
X509Certificate2 testCA2 = new X509Certificate2("../../imports/CA2.cer");
X509Certificate2 testCA3 = new X509Certificate2("../../imports/specimenCa.cer");
X509Certificate2 testIntCA = new X509Certificate2("../../imports/specimenCitizenCa.cer");
X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly);
try
{
if (!store.Certificates.Contains(testCA))
{
store.Add(testCA);
}
if (!store.Certificates.Contains(testCA2))
{
store.Add(testCA2);
}
if (!store.Certificates.Contains(testCA3))
{
store.Add(testCA3);
}
}
finally
{
store.Close();
}
}
示例4: GetCertificate
static X509Certificate2 GetCertificate(string certFindValue)
{
StoreLocation[] locations = new StoreLocation[] { StoreLocation.LocalMachine, StoreLocation.CurrentUser };
foreach (StoreLocation location in locations)
{
X509Store store = new X509Store(StoreName.My, location);
store.Open(OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = store.Certificates.Find(
X509FindType.FindBySubjectName,
certFindValue,
false);
if (collection.Count == 0)
{
collection = store.Certificates.Find(
X509FindType.FindByThumbprint,
certFindValue,
false);
}
store.Close();
if (collection.Count > 0)
{
return collection[0];
}
}
throw new ArgumentException("No certificate can be found using the find value " + certFindValue);
}
示例5: Initialize
internal static X509Certificate Initialize(ICertificateConfig cerConfig)
{
if (!string.IsNullOrEmpty(cerConfig.FilePath))
{
//To keep compatible with website hosting
string filePath;
if (Path.IsPathRooted(cerConfig.FilePath))
filePath = cerConfig.FilePath;
else
{
filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, cerConfig.FilePath);
}
return new X509Certificate2(filePath, cerConfig.Password);
}
else
{
var storeName = cerConfig.StoreName;
if (string.IsNullOrEmpty(storeName))
storeName = "Root";
var store = new X509Store(storeName);
store.Open(OpenFlags.ReadOnly);
var cert = store.Certificates.OfType<X509Certificate2>().Where(c =>
c.Thumbprint.Equals(cerConfig.Thumbprint, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
store.Close();
return cert;
}
}
示例6: CertificateFromFriendlyName
public static X509Certificate2 CertificateFromFriendlyName(StoreName name, StoreLocation location, string friendlyName)
{
X509Store store = null;
try
{
store = new X509Store(name, location);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection foundCertificates = store.Certificates.Find(X509FindType.FindByIssuerName, "DO_NOT_TRUST_WcfBridgeRootCA", false);
foreach (X509Certificate2 cert in foundCertificates)
{
if (cert.FriendlyName == friendlyName)
{
return cert;
}
}
return null;
}
finally
{
if (store != null)
{
store.Close();
}
}
}
示例7: GetCertificate
/// <summary>
/// Gets a X509 specific certificate from windows store withoit asking the user.
/// </summary>
/// <returns></returns>
public static X509Certificate2 GetCertificate(StoreLocation location, string subjectName)
{
X509Certificate2 cert = null;
var store = new X509Store(StoreName.My, location);
store.Open(OpenFlags.ReadOnly);
try
{
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName,
false);
if (certs.Count == 1)
{
cert = certs[0];
}
else
{
cert = null;
}
}
finally
{
if (store != null)
{
store.Close();
}
}
return cert;
}
示例8: CertificadoDigital
public CertificadoDigital()
{
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
var collection = store.Certificates;
var fcollection = collection.Find(X509FindType.FindByTimeValid, DateTime.Now, true);
var scollection = X509Certificate2UI.SelectFromCollection(fcollection, "Certificados válidos:", "Selecione o certificado que deseja usar",
X509SelectionFlag.SingleSelection);
if (scollection.Count == 0)
{
throw new Exception("Nenhum certificado foi selecionado!");
}
foreach (var x509 in scollection)
{
try
{
Serial = x509.SerialNumber;
Validade = Convert.ToDateTime(x509.GetExpirationDateString());
x509.Reset();
}
catch (CryptographicException)
{
Console.WriteLine("Não foi possível obter as informações do certificado selecionado!");
}
}
store.Close();
}
示例9: Install
public bool Install()
{
try
{
var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store.Open(OpenFlags.MaxAllowed);
var names = GetCommonNames(store.Certificates);
foreach (var cert in Certificates)
{
if (names.Contains(GetCommonName(cert)))
continue;
store.Add(cert);
}
store.Close();
return true;
}
catch (SecurityException se)
{
StaticLogger.Warning(se);
}
catch (Exception e)
{
StaticLogger.Error("Failed to install " + e);
}
return false;
}
示例10: GetCertificateNames
public static string[] GetCertificateNames()
{
List<string> certNames = new List<string>();
X509Store store = null;
try
{
store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly);
if (store.StoreHandle != IntPtr.Zero)
{
foreach (var item in store.Certificates)
{
certNames.Add(item.Subject);
item.Reset();
}
}
return certNames.ToArray();
}
catch (Exception ex)
{
throw new ApplicationException("Can't open cert store locally - make sure you have permissions", ex);
}
finally
{
if (store != null) store.Close();
}
}
示例11: Run
public void Run()
{
//get certificate
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Find(X509FindType.FindByThumbprint, "453990941c1cf508fb02196b474059c3c80a3678", false);
store.Close();
var cert = certs[0];
//encrypt with certificates public key
var rsa = (RSACryptoServiceProvider)cert.PublicKey.Key;
byte[] valueBytes = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
byte[] encBytes = rsa.Encrypt(valueBytes, true);
//decrypt with certificates private key
var rsa2 = (RSACryptoServiceProvider)cert.PrivateKey;
var unencrypted = rsa2.Decrypt(encBytes, true);
//Console.WriteLine(Encoding.UTF8.GetString(unencrypted));
var originalEncryptedKey =
"KjTapgZ3NMSy8Yu5+f3guhUFmtSnPjMyYbltZ9xaFQurygU/JvX50Kty3Jkgpv0nkl9SRKlivUuai3RKVGj8DLh4Mm4ntswEB2soJ/ikWIQQXeVMABKWou8vFa+OLBFwBmkD1jURV9BzlG354Zn8qqUurw5Vh2SQP3aYLK9823ZAZXjtYOOYDB6pebiexZ9UpinmVKmgVEywxMR90272DZpPTeYYDWmMRNbiiU1C8WEHa+NNGPwjuWv5sWwLL1OHkVqoi3KSI73LIx/zw9lDDkaCkne7LcSUPN0m2tsdSrQCS9uQs5B4ti0KozJfFb+OSz6Vy3013KH+vmkXsbWL8g==";
var decryptedOriginalKey = rsa2.Decrypt(Encoding.UTF8.GetBytes(originalEncryptedKey), true);
Console.WriteLine("Original decrypted key: " + Convert.ToBase64String(decryptedOriginalKey));
// This decryptedOriginalKey can then be encrypted with the new certificate to get a new Encrypted key, IV remains the same as the old one
// Create new IV and Key from the certificate
var aes = new AesManaged();
var iv = Convert.ToBase64String(aes.IV);
Console.WriteLine("IV: " + iv);
var key = Convert.ToBase64String(aes.Key);
var encryptedKey = rsa.Encrypt(Encoding.UTF8.GetBytes(key), true);
Console.WriteLine("Encrypted Key: " + Convert.ToBase64String(encryptedKey));
}
示例12: GetCertificate
public static X509Certificate2 GetCertificate()
{
var storeLocationString = ConfigurationManager.AppSettings["storeLocation"];
StoreLocation storeLocation;
if (! Enum.TryParse(storeLocationString, out storeLocation))
{
throw new ArgumentException("Invalid store location.");
}
var storeName = ConfigurationManager.AppSettings["storeName"];
var thumbprint = ConfigurationManager.AppSettings["thumbprint"];
var store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly);
try
{
var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
if (certificate.Count == 0)
{
throw new Exception("No certificate found.");
}
return certificate[0];
}
finally
{
store.Close();
}
}
示例13: GetHbInfo
/// <summary>
/// 獲取微信現金紅包信息接口
/// 是否需要證書:需要。
/// http://pay.weixin.qq.com/wiki/doc/api/cash_coupon.php?chapter=13_6
/// 使用說明
/// 用於商戶對已發放的紅包進行查詢紅包的具體信息,可支持普通紅包和裂變包。
/// </summary>
/// <param name="nonce_str">(必填) String(32) 隨機字符串,不長於32位</param>
/// <param name="mch_billno">(必填) String(28) 商戶發放紅包的商戶訂單號</param>
/// <param name="mch_id">(必填) String(32) 微信支付分配的商戶號</param>
/// <param name="appid">(必填) String(32) 微信分配的公眾賬號ID</param>
/// <param name="bill_type">(必填) String(32) 訂單類型 例子:MCHT ,通過商戶訂單號獲取紅包信息。</param>
/// <param name="partnerKey">API密鑰</param>
/// <param name="cert_path">秘鑰路徑</param>
/// <param name="cert_password">秘鑰密碼</param>
/// <returns>返回xml字符串,格式參見:http://pay.weixin.qq.com/wiki/doc/api/cash_coupon.php?chapter=13_6 </returns>
public static string GetHbInfo(string nonce_str, string mch_billno, string mch_id, string appid,
string bill_type, string partnerKey, string cert_path, string cert_password)
{
try
{
var stringADict = new Dictionary<string, string>();
stringADict.Add("nonce_str", nonce_str);
stringADict.Add("mch_billno", mch_billno);
stringADict.Add("mch_id", mch_id);
stringADict.Add("appid", appid);
stringADict.Add("bill_type", bill_type);
var sign = WxPayAPI.Sign(stringADict, partnerKey);//生成簽名字符串
var postdata = PayUtil.GeneralPostdata(stringADict, sign);
var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";
// 要注意的這是這個編碼方式,還有內容的Xml內容的編碼方式
Encoding encoding = Encoding.GetEncoding("UTF-8");
byte[] data = encoding.GetBytes(postdata);
//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
//X509Certificate cer = new X509Certificate(cert_path, cert_password);
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
X509Certificate cer = new X509Certificate(cert_path, cert_password);
#region 該部分是關鍵,若沒有該部分則在IIS下會報 CA證書出錯
X509Certificate2 certificate = new X509Certificate2(cert_path, cert_password);
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
store.Remove(certificate); //可省略
store.Add(certificate);
store.Close();
#endregion
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
webrequest.ClientCertificates.Add(cer);
webrequest.Method = "post";
webrequest.ContentLength = data.Length;
Stream outstream = webrequest.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Flush();
outstream.Close();
HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse();
Stream instream = webreponse.GetResponseStream();
string resp = string.Empty;
using (StreamReader reader = new StreamReader(instream))
{
resp = reader.ReadToEnd();
}
return resp;
}
catch (Exception ex)
{
throw ex;
}
}
示例14: Find
/// <summary>
/// Checks for the certificate in the certificate store. Loads it from a resource if it does not exist.
/// </summary>
public static X509Certificate2 Find(StoreName storeName, StoreLocation storeLocation, string subjectName)
{
X509Certificate2 certificate = null;
// look for the the private key in the personal store.
X509Store store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadWrite);
try
{
X509Certificate2Collection hits = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, false);
if (hits.Count == 0)
{
return null;
}
certificate = hits[0];
}
finally
{
store.Close();
}
return certificate;
}
示例15: FindCertificateBy
public static X509Certificate2 FindCertificateBy(string thumbprint, StoreName storeName, StoreLocation storeLocation, PhysicalServer server, DeploymentResult result)
{
if (string.IsNullOrEmpty(thumbprint)) return null;
var certstore = new X509Store(storeName, storeLocation);
try
{
certstore.Open(OpenFlags.ReadOnly);
thumbprint = thumbprint.Trim();
thumbprint = thumbprint.Replace(" ", "");
foreach (var cert in certstore.Certificates)
{
if (string.Equals(cert.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.Thumbprint, thumbprint, StringComparison.InvariantCultureIgnoreCase))
{
return cert;
}
}
result.AddError("Could not find a certificate with thumbprint '{0}' on '{1}'".FormatWith(thumbprint, server.Name));
return null;
}
finally
{
certstore.Close();
}
}