本文整理汇总了C#中System.Security.Cryptography.X509Certificates.X509Certificate2.GetEffectiveDateString方法的典型用法代码示例。如果您正苦于以下问题:C# X509Certificate2.GetEffectiveDateString方法的具体用法?C# X509Certificate2.GetEffectiveDateString怎么用?C# X509Certificate2.GetEffectiveDateString使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.X509Certificates.X509Certificate2
的用法示例。
在下文中一共展示了X509Certificate2.GetEffectiveDateString方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: 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;
}
示例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: ValidateCert
private int ValidateCert(uint dwType, IntPtr pvArg, uint dwChainLen, IntPtr pCertChain, uint dwFlags)
{
//According to http://msdn.microsoft.com/en-us/library/ms940451.aspx:
//
//- dwChainLen is always 1
//- Windows CE performs the cert chain validation
//- pvArg is the context data we passed into the SO_SSL_SET_VALIDATE_CERT_HOOK call so in our
//- case is the host name
//
//So here we are responsible for validating the dates on the certificate and the CN
if (dwType != SSL_CERT_X59)
return SSL_ERR_BAD_TYPE;
//When in debug mode let self-signed certificates through ...
#if !DEBUG
if ((dwFlags & SSL_CERT_FLAG_ISSUER_UNKNOWN) != 0)
return SSL_ERR_CERT_UNKNOWN;
#endif
Debug.Assert(dwChainLen == 1);
//Note about the note: an unmanaged long is 32 bits, unlike a managed long which is 64. I was missing
//this fact when I wrote the comment. So the docs are accurate.
//NOTE: The documentation says pCertChain is a pointer to a LPBLOB struct:
//
// {ulong size, byte* data}
//
//in reality the size is a 32 bit integer (not 64).
int certSize = Marshal.ReadInt32(pCertChain);
IntPtr pData = Marshal.ReadIntPtr(new IntPtr(pCertChain.ToInt32() + sizeof(int)));
byte[] certData = new byte[certSize];
for (int i = 0; i < certSize; i++)
certData[i] = Marshal.ReadByte(pData, (int)i);
X509Certificate2 cert;
try
{
cert = new X509Certificate2(certData);
}
catch (ArgumentException) { return SSL_ERR_BAD_DATA; }
catch (CryptographicException) { return SSL_ERR_BAD_DATA; }
//Validate the expiration date
if (DateTime.Now > DateTime.Parse(cert.GetExpirationDateString(), CultureInfo.CurrentCulture))
return SSL_ERR_CERT_EXPIRED;
//Validate the effective date
if (DateTime.Now < DateTime.Parse(cert.GetEffectiveDateString(), CultureInfo.CurrentCulture))
return SSL_ERR_FAILED;
string certName = cert.GetName();
Debug.WriteLine(certName);
//Validate the CN
string host = ReadAnsiString(pvArg);
if (!certName.Contains("CN=" + host))
return SSL_ERR_FAILED;
return SSL_ERR_OKAY;
}
示例6: 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;
}
示例7: 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());
}
}
示例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: 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;
}
示例10: AssignSession
public override void AssignSession(Session oS)
{
base.AssignSession(oS);
var dataItems = new List<DataItem>();
dataItems.Add(new DataItem("Is Https", oS.isHTTPS));
if (oS.isHTTPS && oS.oFlags.ContainsKey(CertificateStorage.CeritificateRequestPropertyName))
{
try
{
var thumbprint = oS.oFlags[CertificateStorage.CeritificateRequestPropertyName];
FiddlerApplication.Log.LogString(thumbprint);
if (CertificateStorage.Certificates.ContainsKey(thumbprint))
{
var certificate = CertificateStorage.Certificates[thumbprint];
var cert = new X509Certificate2(certificate);
_informationTab.Certificate = cert;
//most commonly desired information up top.
dataItems.InsertRange(0, new[] { new DataItem("FriendlyName", cert.FriendlyName),
new DataItem("Subject", cert.Subject),
new DataItem("Issuer", cert.Issuer),
new DataItem("Effective Date", cert.GetEffectiveDateString()),
new DataItem("Expiration Date", cert.GetExpirationDateString()),
new DataItem("Thumbprint", cert.Thumbprint),
new DataItem("------------------------", "------------------------")});
//alphabatized data properties below
dataItems.Add(new DataItem("Archived", cert.Archived));
dataItems.Add(new DataItem("FriendlyName", cert.FriendlyName));
dataItems.Add(new DataItem("Certficate Hash", cert.GetCertHashString()));
dataItems.Add(new DataItem("Certificate Format", cert.GetFormat()));
dataItems.Add(new DataItem("Effective Date", cert.GetEffectiveDateString()));
dataItems.Add(new DataItem("Expiration Date", cert.GetExpirationDateString()));
dataItems.Add(new DataItem("Full Issuer Name", cert.IssuerName.Format(true)));
dataItems.Add(new DataItem("Full Subject Name", cert.SubjectName.Format(true)));
dataItems.Add(new DataItem("Has Private Key", cert.HasPrivateKey));
dataItems.Add(new DataItem("Issuer", cert.Issuer));
dataItems.Add(new DataItem("Key Algorithm", cert.GetKeyAlgorithm()));
dataItems.Add(new DataItem("Key Algorithm Parameters", cert.GetKeyAlgorithmParametersString()));
dataItems.Add(new DataItem("Public Key", cert.GetPublicKeyString()));
dataItems.Add(new DataItem("Raw Certificate Data", cert.GetRawCertDataString()));
dataItems.Add(new DataItem("SerialNumberString", cert.GetSerialNumberString()));
dataItems.Add(new DataItem("Subject", cert.Subject));
dataItems.Add(new DataItem("Thumbprint", cert.Thumbprint));
dataItems.Add(new DataItem("Version", cert.Version));
dataItems.Add(new DataItem("------------------------", "------------------------"));
dataItems.Add(new DataItem("Extensions", string.Empty));
dataItems.Add(new DataItem("------------------------", "------------------------"));
foreach (var extension in cert.Extensions)
{
dataItems.Add(new DataItem(extension.Oid.FriendlyName, extension.Format(true)));
}
}
}
catch (Exception ex)
{
FiddlerApplication.Log.LogString("Unexpected error loading the assigned certificate." + ex.Message);
}
}
_informationTab.DataGrid.DataSource = dataItems;
}
示例11: SignPackage
public static void SignPackage(Stream input, X509Certificate2 certificate, Stream output, bool signWholeFile)
{
JarFile inputJar = null;
ZipOutputStream outputJar = null;
// Assume the certificate is valid for at least an hour.
DateTime timestamp = DateTime.Parse(certificate.GetEffectiveDateString()).AddHours(1);
inputJar = new JarFile(input); // Don't verify.
Stream outputStream = null;
if (signWholeFile)
{
outputStream = new MemoryStream();
}
else
{
outputStream = output;
}
outputJar = new ZipOutputStream(outputStream);
outputJar.SetComment(null);
outputJar.SetLevel(9);
JarEntry je;
Manifest manifest = addDigestsToManifest(inputJar);
// Everything else
copyFiles(manifest, inputJar, outputJar, timestamp);
// otacert
if (signWholeFile)
{
addOtacert(outputJar, certificate, timestamp, manifest);
}
var buffer = new MemoryStream();
// MANIFEST.MF
je = new JarEntry(JarFile.MANIFEST_NAME);
je.DateTime = timestamp;
manifest.Write(buffer);
je.Size = buffer.Length;
outputJar.PutNextEntry(je);
buffer.WriteTo(outputJar);
// CERT.SF
var signature = new MemoryStream();
je = new JarEntry(CERT_SF_NAME);
je.DateTime = timestamp;
buffer.SetLength(0);
writeSignatureFile(manifest, signature);
signature.WriteTo(buffer);
je.Size = buffer.Length;
outputJar.PutNextEntry(je);
buffer.WriteTo(outputJar);
// CERT.RSA
je = new JarEntry(CERT_RSA_NAME);
je.DateTime = timestamp;
buffer.SetLength(0);
writeSignatureBlock(signature, certificate, buffer);
je.Size = buffer.Length;
outputJar.PutNextEntry(je);
buffer.WriteTo(outputJar);
outputJar.Close();
outputJar = null;
if (signWholeFile)
{
signWholeOutputFile(((MemoryStream)outputStream).ToArray(),
output, certificate);
}
}
示例12: 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)
//.........这里部分代码省略.........
示例13: 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);
}
}
示例14: button1_Click
private void button1_Click(object sender, EventArgs e)
{
string fileName = textBox1.Text;
string fileExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (textBox1.TextLength < 1)
{
MessageBox.Show("Укажите путь к файлу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else {
if (CheckFile(textBox1.Text))
{
MessageBox.Show("Модуль PE32 имеет подпись", "CheckPE32", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
X509Certificate theSigner = X509Certificate.CreateFromSignedFile(textBox1.Text);
X509Certificate2 theCertificate = new X509Certificate2(theSigner);
System.IO.StreamWriter textFile = new System.IO.StreamWriter("SertificateInfo.txt");
textFile.WriteLine("Проверяемый файл: " + textBox1.Text);
textFile.WriteLine("Серийный номер сертификата: " + theCertificate.SerialNumber);
textFile.WriteLine("Информация о владельце: " + theCertificate.SubjectName.Name);
textFile.WriteLine("Действителен с: " + theCertificate.GetEffectiveDateString());
textFile.WriteLine("Истекает: " + theCertificate.GetExpirationDateString());
textFile.WriteLine("Центр сертификации, выдавший сертификат: " + theCertificate.Issuer);
textFile.Close();
System.Diagnostics.Process.Start("notepad.exe", "SertificateInfo.txt");
}
else
{
MessageBox.Show("Модуль PE32 не подписан!", "CheckPE32", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}