本文整理汇总了C#中System.Security.Cryptography.X509Certificates.X509Certificate2.Verify方法的典型用法代码示例。如果您正苦于以下问题:C# X509Certificate2.Verify方法的具体用法?C# X509Certificate2.Verify怎么用?C# X509Certificate2.Verify使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.X509Certificates.X509Certificate2
的用法示例。
在下文中一共展示了X509Certificate2.Verify方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SubTest
public void SubTest()
{
X509Certificate2 x509 = new X509Certificate2(@"C:\Users\bxu.CHINA\Desktop\HYD-801\1234\cert\ABCFR_ABCFRALMMACC1.crt");
//X509Certificate2 x509 = new X509Certificate2(@"..\..\..\ApacheQpidClient\certificates\LiquidCapital\LCMLO_ABCFRALMMACC1.crt");
byte[] rawdata = x509.RawData;
Console.WriteLine("Content Type: {0}{1}", X509Certificate2.GetCertContentType(rawdata), Environment.NewLine);
Console.WriteLine("Friendly Name: {0}{1}", x509.FriendlyName, Environment.NewLine);
Console.WriteLine("Certificate Verified?: {0}{1}", x509.Verify(), Environment.NewLine);
Console.WriteLine("Simple Name: {0}{1}", x509.GetNameInfo(X509NameType.SimpleName, true), Environment.NewLine);
Console.WriteLine("Signature Algorithm: {0}{1}", x509.SignatureAlgorithm.FriendlyName, Environment.NewLine);
// Console.WriteLine("Private Key: {0}{1}", x509.PrivateKey.ToXmlString(false), Environment.NewLine); // cer里面并没有私钥信息
Console.WriteLine("Public Key: {0}{1}", x509.PublicKey.Key.ToXmlString(false), Environment.NewLine);
Console.WriteLine("Certificate Archived?: {0}{1}", x509.Archived, Environment.NewLine);
Console.WriteLine("Length of Raw Data: {0}{1}", x509.RawData.Length, Environment.NewLine);
Console.WriteLine("SubjectName: {0}{1}", x509.SubjectName, Environment.NewLine);
Console.WriteLine("Subject: {0}{1}", x509.Subject, Environment.NewLine);
}
示例2: Test
static int Test (string site)
{
#if NET_2_0
string certFile = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
"www.microsoft.com.crt");
SSCX.X509Certificate2 cer = new SSCX.X509Certificate2 (certFile);
Assert.IsTrue (cer.Verify (), "#1");
SSCX.X509Chain chain = new SSCX.X509Chain ();
Assert.IsTrue (chain.Build (cer), "#2");
#endif
HttpWebRequest request = (HttpWebRequest) WebRequest.Create (site);
request.Method = "GET";
try {
HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
using (StreamReader sr = new StreamReader (response.GetResponseStream (), Encoding.UTF8, true)) {
string result = sr.ReadToEnd ();
if (result.IndexOf ("<title>Microsoft Corporation</title>") == -1) {
Console.WriteLine (result);
return 1;
}
}
response.Close ();
} catch (WebException ex) {
if (ex.Response != null) {
StreamReader sr = new StreamReader (ex.Response.GetResponseStream ());
Console.WriteLine (sr.ReadToEnd ());
} else {
Console.WriteLine (ex.ToString ());
}
return 2;
}
return 0;
}
示例3: VerifyCertificate
private void VerifyCertificate(Domain domain)
{
try
{
_Certificate = HttpGet.GetCertificate(domain.Server);
BtnCertificateStatus.Cursor = Cursors.Hand;
if (_Certificate.Verify() == true)
{
_CertificateStatus = Resources.CertificateStatusValid;
BtnCertificateStatus.BackgroundImage = Resources.certificate_valid;
}
else
{
throw new Exception(Resources.CertificateStatusInvalid);
}
}
catch (Exception ex)
{
_CertificateStatus = ex.Message;
BtnCertificateStatus.BackgroundImage = Resources.certificate_invalid;
}
}
示例4: GetSignatureInformation
public static void GetSignatureInformation(string filename) {
if (HasValidSignature(filename)) {
var cert = new X509Certificate2(filename);
Console.WriteLine("Cert: {0}", cert.Subject);
var ch = new X509Chain();
ch.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
ch.ChainPolicy.RevocationMode = X509RevocationMode.Online;
ch.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
ch.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
ch.Build(cert);
ch.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
ch.ChainPolicy.RevocationMode = X509RevocationMode.Online;
Console.WriteLine("Chain Information");
Console.WriteLine("Chain revocation flag: {0}", ch.ChainPolicy.RevocationFlag);
Console.WriteLine("Chain revocation mode: {0}", ch.ChainPolicy.RevocationMode);
Console.WriteLine("Chain verification flag: {0}", ch.ChainPolicy.VerificationFlags);
Console.WriteLine("Chain verification time: {0}", ch.ChainPolicy.VerificationTime);
Console.WriteLine("Chain status length: {0}", ch.ChainStatus.Length);
Console.WriteLine("Chain application policy count: {0}", ch.ChainPolicy.ApplicationPolicy.Count);
Console.WriteLine("Chain certificate policy count: {0} {1}", ch.ChainPolicy.CertificatePolicy.Count, Environment.NewLine);
//Output chain element information.
Console.WriteLine("Chain Element Information");
Console.WriteLine("Number of chain elements: {0}", ch.ChainElements.Count);
foreach (var element in ch.ChainElements) {
Console.WriteLine("Element issuer name: {0}", element.Certificate.Issuer);
Console.WriteLine("Element certificate valid until: {0}", element.Certificate.NotAfter);
Console.WriteLine("Element certificate is valid: {0}", element.Certificate.Verify());
Console.WriteLine("Element error status length: {0}", element.ChainElementStatus.Length);
Console.WriteLine("Element information: {0}", element.Information);
Console.WriteLine("Number of element extensions: {0}{1}", element.Certificate.Extensions.Count, Environment.NewLine);
}
if (ch.ChainStatus.Length > 0) {
for (int index = 0; index < ch.ChainStatus.Length; index++) {
Console.WriteLine(ch.ChainStatus[index].Status);
Console.WriteLine(ch.ChainStatus[index].StatusInformation);
}
}
Console.WriteLine("Cert Valid?: {0}", cert.Verify());
}
}
示例5: VerifySignature
public bool VerifySignature(string msiFileName)
{
try
{
X509Certificate basicSigner = X509Certificate.CreateFromSignedFile(msiFileName);
X509Certificate2 cert = new X509Certificate2(basicSigner);
System.Console.WriteLine("issuer:" + cert.Issuer);
System.Console.WriteLine("serial:" + cert.SerialNumber);
System.Console.WriteLine("expiration date:" + cert.NotAfter.ToString());
System.Console.WriteLine("subject:" + cert.Subject);
System.Console.WriteLine("verified:" + (cert.Verify() ? "true" : "false"));
if (DateTime.Now > cert.NotAfter)
{
System.Console.WriteLine("cert has expired: " + cert.NotAfter.ToString());
return false;
}
if (DateTime.Now < cert.NotBefore)
{
System.Console.WriteLine("cert not yet active: " + cert.NotBefore.ToString());
return false;
}
string serial = cert.SerialNumber;
string issuer = cert.Issuer;
string company = cert.Subject;
foreach (CertStrings o in mCertStrings)
{
if (o.Matches(serial, issuer, company))
{
return true;
}
}
System.Console.WriteLine("creds not found >> serial: " + serial + " issuer: " + issuer + " company: " + company);
}
catch (SystemException e)
{
System.Console.WriteLine("could not extract cert from file: " + msiFileName + " (" + e + ")");
}
return false;
}
示例6: GetCertificatesFromUrl
/// <summary>
/// Gets the certificate corresponding to the specified URL from the cache of certificates. If the cache doesn't contain the certificate, it is downloaded and verified.
/// </summary>
/// <param name="certUrl">The URL pointing to the certificate.</param>
/// <returns>An <see cref="System.Security.Cryptography.X509Certificates.X509Certificate2"/> object containing the details of the certificate.</returns>
/// <exception cref="PayPal.PayPalException">Thrown if the downloaded certificate cannot be verified.</exception>
public X509Certificate2Collection GetCertificatesFromUrl(string certUrl)
{
// If we haven't already cached this URL, then download, verify, and cache it.
if(!certificates.ContainsKey(certUrl))
{
// Download the certificate.
string certData;
using (var webClient = new WebClient())
{
certData = webClient.DownloadString(certUrl);
}
// Load all the certificates.
// NOTE: The X509Certificate2Collection.Import() method only
// imports the first certifcate, even if a stream contains
// multiple certificates. For this reason, we'll load the
// certificates one-by-one, verifying as we go.
var results = certData.Split(new string[] { "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----" }, StringSplitOptions.RemoveEmptyEntries);
var collection = new X509Certificate2Collection();
foreach (var result in results)
{
var trimmed = result.Trim();
if (!string.IsNullOrEmpty(trimmed))
{
var certificate = new X509Certificate2(System.Text.Encoding.UTF8.GetBytes(trimmed));
// Verify the certificate before adding it to the collection.
if(certificate.Verify())
{
collection.Add(certificate);
}
else
{
throw new PayPalException("Unable to verify the certificate(s) found at " + certUrl);
}
}
}
certificates[certUrl] = collection;
}
return certificates[certUrl];
}
示例7: generateValidIV
/// <summary>
/// Generate a random init value.
/// </summary>
/// <param name="internetSource">Use random.org for random source</param>
/// <returns>Byte array IV</returns>
private byte[] generateValidIV(bool internetSource)
{
byte[] result = new byte[16];
if (!internetSource)
{
RandomNumberGenerator rng = new RNGCryptoServiceProvider();
rng.GetBytes(result);
}
else
{
if (checkRandomORGQuota())
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.random.org/integers/?num=16&min=0&max=255&col=1&base=10&format=plain&rnd=new");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(receiveStream, encode);
string[] randomNumbers = (readStream.ReadToEnd()).Trim().Split('\n');
for (int i = 0; i < 16; i++)
{
result[i] = Convert.ToByte(randomNumbers[i]);
}
response.Close();
X509Certificate cert = request.ServicePoint.Certificate;
X509Certificate2 cert2 = new X509Certificate2(cert);
if (isConsole)
{
util.writeFullWidth("Random.org Certificate Information:", ConsoleColor.White, ConsoleColor.DarkBlue);
Console.WriteLine("\n" + cert2.SubjectName.Decode(X500DistinguishedNameFlags.UseNewLines) + "\n");
}
if (cert2.Verify())
{
if (isConsole)
Console.WriteLine("OK!");
}
else
throw new Exception("Certificate Chain Cannot Be Verified!");
}
else
throw new Exception("Exceeded Random.Org Quota");
}
return result;
}
示例8: LoadCertificate
private static X509Certificate2 LoadCertificate(string certificateType, string certifcateLocation, string certKeyPassword)
{
try
{
if (certificateType == "file")
{
X509Certificate2 serverCertificate = new X509Certificate2(certifcateLocation, certKeyPassword);
//DisplayCertificateChain(m_serverCertificate);
bool verifyCert = serverCertificate.Verify();
logger.Debug("Server Certificate loaded from file, Subject=" + serverCertificate.Subject + ", valid=" + verifyCert + ".");
return serverCertificate;
}
else
{
StoreLocation store = (certificateType == "machinestore") ? StoreLocation.LocalMachine : StoreLocation.CurrentUser;
return AppState.LoadCertificate(store, certifcateLocation, true);
}
}
catch (Exception excp)
{
logger.Error("Exception LoadCertificate. " + excp.Message);
return null;
}
}
示例9: IsAuthenticated
public bool IsAuthenticated(HttpClientCertificate httpClientCertificate)
{
var certificate = new X509Certificate2(httpClientCertificate.Certificate);
return !certificate.Archived && certificate.Verify();
}
示例10: VerifyInAllStores
private bool VerifyInAllStores(X509Certificate2 certificate2)
{
try
{
X509Chain chain = new X509Chain(true);
return chain.Build(certificate2) || certificate2.Verify();
}
catch (CryptographicException)
{
return false;
}
}
示例11: Main
//.........这里部分代码省略.........
"(&(objectClass=*))",
SearchScope.Base,
"defaultNamingContext"))).Entries[0];
searchbase = e.Attributes["defaultNamingContext"][0].ToString();
}
var srch = new SearchRequest(searchbase, filter, SearchScope.Subtree, "userCertificate");
var pager = new PageResultRequestControl();
srch.Controls.Add(pager);
int count = 0;
while (true)
{
var resp = (SearchResponse)conn.SendRequest(srch);
foreach (SearchResultEntry se in resp.Entries)
{
if (!se.Attributes.Contains("userCertificate"))
{
continue;
}
Console.WriteLine("# {0}", ++count);
Console.WriteLine("dn: {0}", se.DistinguishedName);
foreach (var o in se.Attributes["userCertificate"].GetValues(typeof(byte[])))
{
byte[] bytes = (byte[])o;
try
{
X509Certificate2 cert = new X509Certificate2(bytes);
Console.WriteLine("subject: {0}", string.IsNullOrEmpty(cert.Subject) ? cert.SubjectName.Name : cert.Subject);
Console.WriteLine("issuer: {0}", cert.Issuer);
Console.WriteLine("thumbprint: {0}", cert.Thumbprint);
Console.WriteLine("serial: {0}", cert.SerialNumber);
var estr = cert.GetExpirationDateString();
var expired = false;
if (!string.IsNullOrEmpty(estr))
{
Console.WriteLine("exp: {0}", estr);
DateTime dt;
if (DateTime.TryParse(estr, out dt) && dt < DateTime.Now)
{
Console.WriteLine("expired: TRUE");
expired = true;
}
}
if (validate && !expired)
{
Console.WriteLine("valid: {0}", cert.Verify().ToString().ToUpperInvariant());
}
}
catch (Exception e)
{
Console.WriteLine("exception: {0}, {1}", e.GetType(), e.Message);
}
if (raw)
{
var s = Convert.ToBase64String(bytes);
Console.WriteLine("-----BEGIN CERTIFICATE-----");
for (int i = 0; i < s.Length; i += 78)
{
Console.WriteLine(s.Substring(i, Math.Min(78, s.Length - i)));
}
Console.WriteLine("-----END CERTIFICATE-----");
}
Console.WriteLine("-");
}
Console.WriteLine("");
}
var rc = resp.Controls.SingleOrDefault(t => t is PageResultResponseControl) as PageResultResponseControl;
if (rc == null || rc.Cookie == null || rc.Cookie.Length == 0)
break;
pager.Cookie = rc.Cookie;
}
}
}
catch (Exception e)
{
Console.Error.WriteLine("Error type = {0}, message = {1}, stack = {2}", e.GetType(), e.Message, e.StackTrace);
System.Environment.ExitCode = 2;
}
}
示例12: OutputCertificate
private void OutputCertificate(X509Certificate2 x509Certificate)
{
System.Diagnostics.Debug.WriteLine("");
System.Diagnostics.Debug.WriteLine("Certificate Data: ******************************************************************");
System.Diagnostics.Debug.WriteLine("");
System.Diagnostics.Debug.WriteLine("Basic Certificate Information");
//System.Diagnostics.Debug.WriteLine("\t Content Type: " + X509Certificate2.GetCertContentType(x509Certificate.RawData));
System.Diagnostics.Debug.WriteLine("\t Format: " + x509Certificate.GetFormat());
System.Diagnostics.Debug.WriteLine("\t Version: " + x509Certificate.Version.ToString());
System.Diagnostics.Debug.WriteLine("\t Hash String: " + x509Certificate.GetCertHashString());
System.Diagnostics.Debug.WriteLine("\t Issuer Name: " + x509Certificate.IssuerName.Name);
System.Diagnostics.Debug.WriteLine("\t Issuer Name OID: " + x509Certificate.IssuerName.Oid.Value);
System.Diagnostics.Debug.WriteLine("\t Subject Name: " + x509Certificate.SubjectName.Name);
System.Diagnostics.Debug.WriteLine("\t Serial Number: " + x509Certificate.GetSerialNumberString());
System.Diagnostics.Debug.WriteLine("\t Thumb Print: " + x509Certificate.Thumbprint);
System.Diagnostics.Debug.WriteLine("\t Friendly Name: " + x509Certificate.FriendlyName);
System.Diagnostics.Debug.WriteLine("\t Signature Algorithm: " + x509Certificate.SignatureAlgorithm.FriendlyName);
if (null != x509Certificate.PrivateKey)
System.Diagnostics.Debug.WriteLine("\t Signature Key Exchange Algorithm: " + x509Certificate.PrivateKey.KeyExchangeAlgorithm);
else
System.Diagnostics.Debug.WriteLine("\t Signature Key Exchange Algorithm: ");
System.Diagnostics.Debug.WriteLine("\t Key Algorithm Parameters: " + x509Certificate.GetKeyAlgorithmParametersString());
System.Diagnostics.Debug.WriteLine("\t Not Valid Before: " + x509Certificate.NotBefore.ToString());
System.Diagnostics.Debug.WriteLine("\t Not Valid After: " + x509Certificate.NotAfter.ToString());
System.Diagnostics.Debug.WriteLine("\t Can Be Verified: " + x509Certificate.Verify());
System.Diagnostics.Debug.WriteLine("\t Is Archived: " + x509Certificate.Archived);
System.Diagnostics.Debug.WriteLine("");
System.Diagnostics.Debug.WriteLine("X509 Name Elements");
System.Diagnostics.Debug.WriteLine("\t X509 Simple Name: " + x509Certificate.GetNameInfo(X509NameType.SimpleName, false));
System.Diagnostics.Debug.WriteLine("\t X509 DNS From Alternative Name: " + x509Certificate.GetNameInfo(X509NameType.DnsFromAlternativeName, false));
System.Diagnostics.Debug.WriteLine("\t X509 DNS Name: " + x509Certificate.GetNameInfo(X509NameType.DnsName, false));
System.Diagnostics.Debug.WriteLine("\t X509 Email Name: " + x509Certificate.GetNameInfo(X509NameType.EmailName, false));
System.Diagnostics.Debug.WriteLine("\t X509 UPN Name: " + x509Certificate.GetNameInfo(X509NameType.UpnName, false));
System.Diagnostics.Debug.WriteLine("\t X509 URL Name: " + x509Certificate.GetNameInfo(X509NameType.UrlName, false));
System.Diagnostics.Debug.WriteLine("");
System.Diagnostics.Debug.WriteLine("X509 Name Elements for Issuer");
System.Diagnostics.Debug.WriteLine("\t X509 Simple Name: " + x509Certificate.GetNameInfo(X509NameType.SimpleName, true));
System.Diagnostics.Debug.WriteLine("\t X509 DNS From Alternative Name: " + x509Certificate.GetNameInfo(X509NameType.DnsFromAlternativeName, true));
System.Diagnostics.Debug.WriteLine("\t X509 DNS Name: " + x509Certificate.GetNameInfo(X509NameType.DnsName, true));
System.Diagnostics.Debug.WriteLine("\t X509 Email Name: " + x509Certificate.GetNameInfo(X509NameType.EmailName, true));
System.Diagnostics.Debug.WriteLine("\t X509 UPN Name: " + x509Certificate.GetNameInfo(X509NameType.UpnName, true));
System.Diagnostics.Debug.WriteLine("\t X509 URL Name: " + x509Certificate.GetNameInfo(X509NameType.UrlName, true));
System.Diagnostics.Debug.WriteLine("");
System.Diagnostics.Debug.WriteLine("Keys");
System.Diagnostics.Debug.WriteLine("\t Public Key: " + x509Certificate.PublicKey.Key.ToXmlString(false));
if (null != x509Certificate.PrivateKey)
System.Diagnostics.Debug.WriteLine("\t Private Key: " + x509Certificate.PrivateKey.ToXmlString(false));
else
System.Diagnostics.Debug.WriteLine("\t Private Key: ");
System.Diagnostics.Debug.WriteLine("");
System.Diagnostics.Debug.WriteLine("Raw Cert");
System.Diagnostics.Debug.WriteLine("\t " + x509Certificate.GetRawCertDataString());
System.Diagnostics.Debug.WriteLine("");
System.Diagnostics.Debug.WriteLine("************************************************************************************");
System.Diagnostics.Debug.WriteLine("");
}
示例13: RootTest
public void RootTest()
{
// 验证根证书签名
X509Certificate2 x509Root = new X509Certificate2(@"..\..\..\ApacheQpidClient\certificates\LiquidCapital\LCMLO_LIQSPALBB.crt");
Console.WriteLine("Root Certificate Verified?: {0}{1}", x509Root.Verify(), Environment.NewLine); // 根证书是自签名,所以可以通过。
}