本文整理汇总了C#中System.Security.Cryptography.X509Certificates.X509Certificate2.GetExpirationDateString方法的典型用法代码示例。如果您正苦于以下问题:C# X509Certificate2.GetExpirationDateString方法的具体用法?C# X509Certificate2.GetExpirationDateString怎么用?C# X509Certificate2.GetExpirationDateString使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.X509Certificates.X509Certificate2
的用法示例。
在下文中一共展示了X509Certificate2.GetExpirationDateString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
// Assembly assembly = Assembly.LoadFrom(@"C:\IXCad.dll");
// Version ver = assembly.GetName().Version;
var program = new Program();
program.CreateExcelFile();
String filepath1 = @"D:\Learning\TestDLL\pdfshell.dll";
String filepath2 = @"D:\Learning\TestDLL\AcroPDF.dll";
String[] strarray = new String[] { filepath1, filepath2 };
foreach (var item in strarray)
{
//FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(item);
//// Print the file name and version number.
//Console.WriteLine("Copyright: " + myFileVersionInfo.LegalCopyright + '\n' +
// "Version number: " + myFileVersionInfo.FileVersion + "Language:" + myFileVersionInfo.Language +
// myFileVersionInfo.ProductName + myFileVersionInfo.ProductVersion);
//Console.WriteLine("@@@@@@@@@@");
//Console.WriteLine("The certificate details are-------");
X509Certificate2 theCertificate;
try
{
X509Certificate thesigner = X509Certificate.CreateFromSignedFile(item);
theCertificate = new X509Certificate2(thesigner);
Console.WriteLine("Publisher Information : " + theCertificate.SubjectName.Name);
Console.WriteLine("Valid From: " + theCertificate.GetEffectiveDateString());
Console.WriteLine("Valid To: " + theCertificate.GetExpirationDateString());
Console.WriteLine("Issued By: " + theCertificate.Issuer);
}
catch (Exception ex)
{
Console.WriteLine("No signatures found:::" + ex.Message);
return;
}
Console.ReadLine();
}
Console.ReadLine();
}
示例2: Validate
public override void Validate(X509Certificate2 certificate)
{
//Tools.Instance.Logger.LogInfo("performing Client certificate validation into ServerCertificateValidator");
// Check that there is a certificate.
if (certificate == null)
{
Tools.Instance.Logger.LogError("missing client certificate");
throw new ArgumentNullException("missing client certificate");
}
//Stopwatch stopwatch = new Stopwatch();
//stopwatch.Start();
//// the client certificate must be in your trusted certificates store
//bool validCertificate = new X509Chain().Build(certificate);
//stopwatch.Stop();
//Tools.Instance.Logger.LogInfo("Client certificate validation: " + validCertificate.ToString()
// + " took " + stopwatch.Elapsed.TotalSeconds + " sec");
//if (validCertificate)
//{
// Check that the certificate issuer matches the configured issuer.
if (_allowedIssuerName != certificate.IssuerName.Name)
{
Tools.Instance.Logger.LogError("client Certificate was not issued by a trusted issuer");
throw new SecurityTokenValidationException
("client Certificate was not issued by a trusted issuer");
}
if (DateTime.Parse(certificate.GetExpirationDateString()) < DateTime.Now)
{
Tools.Instance.Logger.LogError("client Certificate Expired");
throw new IdentityValidationException("client Certificate Expired");
}
if (_clientCertificate.Equals(certificate) == false)
{
Tools.Instance.Logger.LogError("Untrusted client Certificate");
throw new SecurityTokenValidationException
("Untrusted client Certificate");
}
//}
//else
//{
// Tools.Instance.Logger.LogError("Client certificate validation X509 Validation failure. Invalid or Untrusted X509 Client Certificate");
// throw new SecurityTokenValidationException("Client certificate validation X509 Validation failure. Invalid or Untrusted X509 Client Certificate");
//}
//Tools.Instance.Logger.LogInfo("Client certificate validation ended without exceptions");
}
示例3: eVRCardReader
public eVRCardReader(X509Certificate2 CSCA, CardRemovedEvent removedEvent, CardInsertedEvent insertedEvent)
{
TS.TraceI("Constructing MTVCardReader object.");
TS.TraceI("eVRCApplicatie = {0}", Helper.ByteArrayToString(eVRCApplicatie));
if (CSCA != null)
{
this.CSCA = CSCA;
TS.TraceV("CSCA Subject : \"{0}\".", CSCA.Subject);
TS.TraceV("CSCA Effective date : \"{0}\".", CSCA.GetEffectiveDateString());
TS.TraceV("CSCA Expiration date : \"{0}\".", CSCA.GetExpirationDateString());
}
this.cardReader = new CardReader(removedEvent, insertedEvent);
TS.TraceI("MTVCardReader constructed.");
}
示例4: CertTest_Test
public MFTestResults CertTest_Test()
{
bool bRes = true;
try
{
//string filename = "microsoft.cer";
using (Session session = new Session("", MechanismType.RSA_PKCS))
{
X509Certificate2 cert = new X509Certificate2(session, Properties.Resources.GetBytes(Properties.Resources.BinaryResources.microsoft));
Log.Comment(cert.Subject);
Log.Comment(cert.Issuer);
byte[] serialNumber = new byte[cert.GetSerialNumber().Length];
Array.Copy(cert.GetSerialNumber(), 0,
serialNumber, 0,
cert.GetSerialNumber().Length);
PrintByteArray(serialNumber);
Log.Comment(cert.GetKeyAlgorithm());
byte[] publicKey = new byte[cert.GetPublicKey().Length];
Array.Copy(cert.GetPublicKey(), 0,
publicKey, 0,
cert.GetPublicKey().Length);
PrintByteArray(publicKey);
Log.Comment(cert.GetEffectiveDateString());
Log.Comment(cert.GetExpirationDateString());
}
}
catch
{
bRes = false;
}
return bRes ? MFTestResults.Pass : MFTestResults.Fail;
}
示例5: ValidateCertificate
private bool ValidateCertificate(X509Certificate2 certificate, out string validationFailedMsg)
{
validationFailedMsg = null;
if (certificate == null || string.IsNullOrEmpty(certificate.Subject) || string.IsNullOrEmpty(certificate.SerialNumber))
{
validationFailedMsg = "Invalid Certificate.";
return false;
}
// Check the issuer
if (string.Compare(validCertificate.Issuer, certificate.Issuer) != 0)
{
validationFailedMsg = "Invalid Certificate.";
return false;
}
// Check the expiry date of the certificate
string certExpiryDate = certificate.GetExpirationDateString();
int? certExpiredDays = null;
if (!string.IsNullOrEmpty(certExpiryDate))
certExpiredDays = DateTime.Compare(DateTime.Now, DateTime.Parse(certExpiryDate));
if (!certExpiredDays.HasValue)
{
validationFailedMsg = "Invalid Certificate.";
return false;
}
else if (certExpiredDays.Value > 0)
{
validationFailedMsg = "Certificate has expired.";
return false;
}
return true;
}
示例6: PrepareForSigning
/// <summary>
/// Prepares this signer to sign an application
/// Modifies the following files:
/// embedded.mobileprovision
/// </summary>
public void PrepareForSigning()
{
// Load Info.plist, which guides nearly everything else
Info = LoadInfoPList();
// Get the name of the bundle
string CFBundleIdentifier;
if (!Info.GetString("CFBundleIdentifier", out CFBundleIdentifier))
{
throw new InvalidDataException("Info.plist must contain the key CFBundleIdentifier");
}
// Load the mobile provision, which provides entitlements and a partial cert which can be used to find an installed certificate
LoadMobileProvision(CFBundleIdentifier);
if (Provision == null)
{
return;
}
// Install the Apple trust chain certs (required to do a CMS signature with full chain embedded)
List<string> TrustChainCertFilenames = new List<string>();
string CertPath = Path.GetFullPath(Config.EngineBuildDirectory);
TrustChainCertFilenames.Add(Path.Combine(CertPath, "AppleWorldwideDeveloperRelationsCA.pem"));
TrustChainCertFilenames.Add(Path.Combine(CertPath, "AppleRootCA.pem"));
InstallCertificates(TrustChainCertFilenames);
// Find and load the signing cert
SigningCert = LoadSigningCertificate();
if (SigningCert == null)
{
// Failed to find a cert already installed or to install, cannot proceed any futher
Program.Error("... Failed to find a certificate that matches the mobile provision to be used for code signing");
Program.ReturnCode = (int)ErrorCodes.Error_CertificateNotFound;
throw new InvalidDataException("Certificate not found!");
}
else
{
Program.Log("... Found matching certificate '{0}' (valid from {1} to {2})", SigningCert.FriendlyName, SigningCert.GetEffectiveDateString(), SigningCert.GetExpirationDateString());
}
}
示例7: CreateFromCertificate
public static ClaimsIdentity CreateFromCertificate(X509Certificate2 certificate, string authenticationType = "X.509", bool includeAllClaims = false)
{
var claims = new List<Claim>();
var issuer = certificate.Issuer;
claims.Add(new Claim("issuer", issuer));
var thumbprint = certificate.Thumbprint;
claims.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, ClaimValueTypes.Base64Binary, issuer));
string name = certificate.SubjectName.Name;
if (!string.IsNullOrEmpty(name))
{
claims.Add(new Claim(ClaimTypes.X500DistinguishedName, name, ClaimValueTypes.String, issuer));
}
if (includeAllClaims)
{
name = certificate.SerialNumber;
if (!string.IsNullOrEmpty(name))
{
claims.Add(new Claim(ClaimTypes.SerialNumber, name, "http://www.w3.org/2001/XMLSchema#string", issuer));
}
name = certificate.GetNameInfo(X509NameType.DnsName, false);
if (!string.IsNullOrEmpty(name))
{
claims.Add(new Claim(ClaimTypes.Dns, name, ClaimValueTypes.String, issuer));
}
name = certificate.GetNameInfo(X509NameType.SimpleName, false);
if (!string.IsNullOrEmpty(name))
{
claims.Add(new Claim(ClaimTypes.Name, name, ClaimValueTypes.String, issuer));
}
name = certificate.GetNameInfo(X509NameType.EmailName, false);
if (!string.IsNullOrEmpty(name))
{
claims.Add(new Claim(ClaimTypes.Email, name, ClaimValueTypes.String, issuer));
}
name = certificate.GetNameInfo(X509NameType.UpnName, false);
if (!string.IsNullOrEmpty(name))
{
claims.Add(new Claim(ClaimTypes.Upn, name, ClaimValueTypes.String, issuer));
}
name = certificate.GetNameInfo(X509NameType.UrlName, false);
if (!string.IsNullOrEmpty(name))
{
claims.Add(new Claim(ClaimTypes.Uri, name, ClaimValueTypes.String, issuer));
}
RSA key = certificate.PublicKey.Key as RSA;
if (key != null)
{
claims.Add(new Claim(ClaimTypes.Rsa, key.ToXmlString(false), ClaimValueTypes.RsaKeyValue, issuer));
}
DSA dsa = certificate.PublicKey.Key as DSA;
if (dsa != null)
{
claims.Add(new Claim(ClaimTypes.Dsa, dsa.ToXmlString(false), ClaimValueTypes.DsaKeyValue, issuer));
}
var expiration = certificate.GetExpirationDateString();
if (!string.IsNullOrEmpty(expiration))
{
claims.Add(new Claim(ClaimTypes.Expiration, expiration, ClaimValueTypes.DateTime, issuer));
}
}
return new ClaimsIdentity(claims, authenticationType);
}
示例8: richTextBox1_TextChanged
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
contextMenuStrip1.Enabled = false;
StreamWriter file = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\inc\\certificate.cer");
X509Certificate2 theCertificate;
try
{
// Write the string to a file.
file.WriteLine(richTextBox1.Text);
file.Close();
}
catch (Exception ex)
{
richTextBox2.Text = ex.Message;
}
try
{
X509Certificate theSigner = X509Certificate.CreateFromCertFile(AppDomain.CurrentDomain.BaseDirectory + "\\inc\\certificate.cer");
//X509Certificate theSigner = X509Certificate.CreateFromSignedFile("https://niyazialpay.com");
theCertificate = new X509Certificate2(theSigner);
}
catch
{
richTextBox2.Text = "No digital signature found";
return;
}
bool chainIsValid = false;
/*
*
* This section will check that the certificate is from a trusted authority IE
* not self-signed.
*
*/
var theCertificateChain = new X509Chain();
theCertificateChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
/*
*
* Using .Online here means that the validation WILL CALL OUT TO THE INTERNET
* to check the revocation status of the certificate. Change to .Offline if you
* don't want that to happen.
*/
theCertificateChain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
theCertificateChain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
theCertificateChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
chainIsValid = theCertificateChain.Build(theCertificate);
try
{
if (chainIsValid)
{
Font boldfont = new Font("Arial", 10, FontStyle.Bold);
Font boldfont2 = new Font("Arial", 11, FontStyle.Bold);
Font normalfont = new Font("Arial", 10, FontStyle.Regular);
richTextBox2.Clear();
string[] certArray = Functions.explode(",", theCertificate.SubjectName.Name);
richTextBox2.SelectionFont = boldfont2;
richTextBox2.AppendText("Publisher Information : \n\n");
int certCount = certArray.Count();
for (int i = 0; i < certCount; i++)
{
string[] certeElements = Functions.explode("=", certArray[i]);
richTextBox2.SelectionFont = boldfont;
richTextBox2.AppendText(certeElements[0].Trim() + ": ");
richTextBox2.SelectionFont = normalfont;
richTextBox2.AppendText(certeElements[1].Trim() + "\n");
}
richTextBox2.SelectionFont = boldfont;
richTextBox2.AppendText("\nValid From: ");
richTextBox2.SelectionFont = normalfont;
richTextBox2.AppendText(theCertificate.GetEffectiveDateString());
richTextBox2.SelectionFont = boldfont;
richTextBox2.AppendText("\nValid To: ");
richTextBox2.SelectionFont = normalfont;
richTextBox2.AppendText(theCertificate.GetExpirationDateString());
string[] iusserArray = Functions.explode(",", theCertificate.Issuer);
int iusserCount = iusserArray.Count();
richTextBox2.SelectionFont = boldfont2;
richTextBox2.AppendText("\n\nIssued By: \n\n");
//.........这里部分代码省略.........
示例9: VerifySign
public static bool VerifySign(string plaintext, string publicKey, string signature)
{
byte[] bInput;
bInput = Convert.FromBase64String(publicKey);
X509Certificate2 x509 = new X509Certificate2();
x509.Import(bInput);
# region 1. Check Chữ ký còn hạn hay không?
// 1. Check Chữ ký còn hạn hay không?
DateTime expirationDate = DateTime.Parse(x509.GetExpirationDateString());
if (expirationDate.CompareTo(DateTime.Now) <= 0)
throw new Exception("Chữ ký không còn hạn sử dụng");
# endregion
# region 2. Check chữ ký có bị thu hồi hay không?
// 2. Check chữ ký có bị thu hồi hay không?
//check ở tầng trên
// Đoạn này trở lên con web service của em: số serial number lấy bằng số: x509.SerialNumber
# endregion
# region 3. Check Root
// 3. Check Root
//error if (!x509.Verify()) throw new VerifySignatureHQException("Lỗi check root publickey");
bool valid = false;
X509Certificate2 crt2 = FindIssuer(x509);
if (crt2 == null) valid = FindRoot(x509);
else valid = FindRoot(crt2);
//if (!valid) throw new VerifySignatureHQException("Khóa là sai root");
# endregion
# region 4. Xác thực chữ ký có đúng không? (Check Signature)
// 4. Xác thực chữ ký có đúng không? (Check Signature)
RSACryptoServiceProvider CSP = (RSACryptoServiceProvider)(x509.PublicKey.Key);
byte[] data = UnicodeEncoding.UTF8.GetBytes(plaintext);
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] hash = sha.ComputeHash(data);
byte[] signatureByte = System.Convert.FromBase64String(signature);
//VerifyHash
if (!CSP.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signatureByte)) throw new Exception("Xác minh chữ ký không thành công");
# endregion
return true;
}
示例10: GetSSLCertificateFromX509Certificate2
private static SSLCertificate GetSSLCertificateFromX509Certificate2(X509Certificate2 cert)
{
var certificate = new SSLCertificate
{
Hostname = cert.GetNameInfo(X509NameType.SimpleName, false),
FriendlyName = cert.FriendlyName,
CSRLength = Convert.ToInt32(cert.PublicKey.Key.KeySize.ToString(CultureInfo.InvariantCulture)),
Installed = true,
DistinguishedName = cert.Subject,
Hash = cert.GetCertHash(),
SerialNumber = cert.SerialNumber,
ExpiryDate = DateTime.Parse(cert.GetExpirationDateString()),
ValidFrom = DateTime.Parse(cert.GetEffectiveDateString()),
Success = true
};
return certificate;
}
示例11: MerrNenshkrimInfo
private Nenshkrim MerrNenshkrimInfo(AcroFields af, string name)
{
PdfPKCS7 pkcs7 = af.VerifySignature(name);
var certificate = new X509Certificate2();
var cert = (Org.BouncyCastle.X509.X509Certificate)pkcs7.Certificates[0];
certificate.Import(cert.GetEncoded());
Nenshkrim nenshkruesi = new Nenshkrim();
nenshkruesi.Nenshkruesi = CertificateInfo.GetSubjectFields(cert).GetField("CN");
string issuer = certificate.Issuer;
nenshkruesi.IssuerCN = GetIssuer(issuer, "CN=");
nenshkruesi.IssuerOU = GetIssuer(issuer, "OU=");
nenshkruesi.IssuerO = GetIssuer(issuer, "O=");
nenshkruesi.IssuerC = GetIssuer(issuer, "C=");
if (nenshkruesi.IssuerC == "KS")
{
//largimi i [EMAIL] prej cn
nenshkruesi.Nenshkruesi = nenshkruesi.Nenshkruesi.Substring(8);
}
nenshkruesi.Emri = CertificateInfo.GetSubjectFields(cert).GetField("GIVENNAME");
nenshkruesi.Mbiemri = CertificateInfo.GetSubjectFields(cert).GetField("SURNAME");
//algoritmi hash
nenshkruesi.AlgoritmiHash = pkcs7.GetHashAlgorithm();
//algoritmi hash
nenshkruesi.AlgoritmiEnkriptimit = pkcs7.GetEncryptionAlgorithm();
//data e nenshrimit
nenshkruesi.DataNenshkrimit = pkcs7.SignDate;
//certifikata valide prej, deri
nenshkruesi.CertifikataValidePrej = certificate.GetEffectiveDateString();
nenshkruesi.CertifikataValideDeri = certificate.GetExpirationDateString();
nenshkruesi.SerialNumber = certificate.SerialNumber;
//verifikimi
if (pkcs7.Verify())
{
nenshkruesi.Valid = true;
}
else
{
nenshkruesi.Valid = false;
}
return nenshkruesi;
}
示例12: 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;
}
}
示例13: InstallPfx
public SSLCertificate InstallPfx(byte[] certificate, string password, WebSite website)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
//
SSLCertificate newcert = null, oldcert = null;
// Ensure we perform operations safely and preserve the original state during all manipulations
if (CheckCertificate(website))
oldcert = GetCurrentSiteCertificate(website);
//
X509Certificate2 x509Cert = new X509Certificate2(certificate, password);
#region Step 1: Register X.509 certificate in the store
// Trying to keep X.509 store open as less as possible
try
{
store.Open(OpenFlags.ReadWrite);
//
store.Add(x509Cert);
}
catch (Exception ex)
{
Log.WriteError(String.Format("SSLModuleService could not import PFX into X509Store('{0}', '{1}')", store.Name, store.Location), ex);
// Re-throw error
throw;
}
finally
{
store.Close();
}
#endregion
#region Step 2: Instantiate a copy of new X.509 certificate
try
{
//
store.Open(OpenFlags.ReadWrite);
//
newcert = new SSLCertificate
{
Hostname = x509Cert.GetNameInfo(X509NameType.SimpleName, false),
FriendlyName = x509Cert.FriendlyName,
CSRLength = Convert.ToInt32(x509Cert.PublicKey.Key.KeySize.ToString()),
Installed = true,
DistinguishedName = x509Cert.Subject,
Hash = x509Cert.GetCertHash(),
SerialNumber = x509Cert.SerialNumber,
ExpiryDate = DateTime.Parse(x509Cert.GetExpirationDateString()),
ValidFrom = DateTime.Parse(x509Cert.GetEffectiveDateString()),
};
}
catch (Exception ex)
{
// Rollback X.509 store changes
store.Remove(x509Cert);
// Log error
Log.WriteError("SSLModuleService could not instantiate a copy of new X.509 certificate. All previous changes have been rolled back.", ex);
// Re-throw
throw;
}
finally
{
store.Close();
}
#endregion
#region Step 3: Remove old certificate from the web site if any
try
{
store.Open(OpenFlags.ReadWrite);
// Check if certificate already exists, remove it.
if (oldcert != null)
DeleteCertificate(oldcert, website);
}
catch (Exception ex)
{
// Rollback X.509 store changes
store.Remove(x509Cert);
// Log the error
Log.WriteError(
String.Format("SSLModuleService could not remove existing certificate from '{0}' web site. All changes have been rolled back.", website.Name), ex);
// Re-throw
throw;
}
finally
{
store.Close();
}
#endregion
#region Step 4: Register new certificate with HTTPS binding on the web site
try
{
store.Open(OpenFlags.ReadWrite);
//
AddBinding(newcert, website);
}
catch (Exception ex)
{
// Install old certificate back if any
if (oldcert != null)
//.........这里部分代码省略.........
示例14: VerifyItem
public static void VerifyItem(X509Certificate2 certificate)
{
try
{
if (certificate == null)
{
throw new Exception("Certificate is null.");
}
DateTime effectiveDate;
if (!DateTime.TryParse(certificate.GetEffectiveDateString(), out effectiveDate))
{
throw new Exception("Could not parse client certificate effective date.");
}
if (effectiveDate > DateTime.Now)
{
throw new Exception("The client certificate is not yet effective.");
}
DateTime expirationDate;
if (!DateTime.TryParse(certificate.GetExpirationDateString(), out expirationDate))
{
throw new Exception("Could not parse client certificate expiration date.");
}
if (expirationDate <= DateTime.Now)
{
throw new Exception("The client certificate has expired.");
}
}
catch (Exception exception)
{
Log.Error(exception);
}
}
示例15: ValidateCertificateInternal
/// <summary>
/// Validate certificate method as callback to the socket
/// </summary>
/// <param name="dwType">Data type pointed to by pCertChain (SSL_CERT_X.509 if X509 certs chain)</param>
/// <param name="pvArg">Pointer to application-defined context (passed by the SSLVALIDATECERTHOOK structure)</param>
/// <param name="dwChainLen">Number of certificates pointed to by pCertChain (It will always be equal to one)</param>
/// <param name="pCertChain">Pointer to the root certificate</param>
/// <param name="dwFlags">Will contain SSL_CERT_FLAG_ISSUER_UNKNOWN if the root issuer of the certificate could not be found in the CA database</param>
/// <param name="certificate">X509 certificate</param>
/// <returns>Result</returns>
private int ValidateCertificateInternal(uint dwType, IntPtr pvArg, uint dwChainLen, IntPtr pCertChain, uint dwFlags, out X509Certificate2 certificate)
{
certificate = null;
// check if it is a valid X509 certificate
if (dwType != SSL_CERT_X509)
return SSL_ERR_BAD_TYPE;
// in debug mode accept self-signed certificates
#if !DEBUG
// check if issuer is unknown
if ((dwFlags & SSL_CERT_FLAG_ISSUER_UNKNOWN) != 0)
return SSL_ERR_CERT_UNKNOWN;
#endif
// sslsock.h : pCertChain is a pointer to BLOB structure
// - first 4 bytes are the certificate size
// - following bytes are the certificate itself
// read certificate size
int certSize = Marshal.ReadInt32(pCertChain);
// pointer to start of certificate data
IntPtr pCertData = Marshal.ReadIntPtr(new IntPtr(pCertChain.ToInt32() + sizeof(int)));
byte[] certData = new byte[certSize];
// read certificate data bytes
for (int i = 0; i < certSize; i++)
certData[i] = Marshal.ReadByte(pCertData, (int)i);
// create X509 certificate from raw bytes
try
{
certificate = new X509Certificate2(certData);
}
catch (ArgumentException) { return SSL_ERR_BAD_DATA; }
catch (CryptographicException) { return SSL_ERR_BAD_DATA; }
// check expiration date
if (DateTime.Now > DateTime.Parse(certificate.GetExpirationDateString(), CultureInfo.CurrentCulture))
return SSL_ERR_CERT_EXPIRED;
// check the effective date
if (DateTime.Now < DateTime.Parse(certificate.GetEffectiveDateString(), CultureInfo.CurrentCulture))
return SSL_ERR_FAILED;
// validate the certificate CN with provided host name
string host = Marshal.PtrToStringBSTR(pvArg);
if (!certificate.GetName().Contains("CN=" + host))
return SSL_ERR_FAILED;
return SSL_ERR_OKAY;
}