本文整理汇总了C#中System.Security.Cryptography.X509Certificates.X509Certificate2.GetSerialNumber方法的典型用法代码示例。如果您正苦于以下问题:C# X509Certificate2.GetSerialNumber方法的具体用法?C# X509Certificate2.GetSerialNumber怎么用?C# X509Certificate2.GetSerialNumber使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.X509Certificates.X509Certificate2
的用法示例。
在下文中一共展示了X509Certificate2.GetSerialNumber方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Client
public Client()
{
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var storeCertificates = store.Certificates.Cast<X509Certificate2>()
.Where(x => CertSubject.Parse(x.Subject).Get(CertSubject.KnownField.CanonicalName) == "www.teamlab.com")
.Where(x => x.HasPrivateKey)
.Where(x => x.NotAfter > DateTime.UtcNow)
.Where(x => x.NotBefore < DateTime.UtcNow)
.OrderByDescending(x=>x.NotBefore)
.ThenByDescending(x=>x.NotAfter);
_clientCertificate = storeCertificates.FirstOrDefault(x=>x.Verify());
if (_clientCertificate == null)
throw new LicenseCertificateException("Can't find valid TM cert");
if (!_clientCertificate.HasPrivateKey)
throw new LicenseCertificateException("Client certificate should conaint PK");
_export = _clientCertificate.Export(X509ContentType.Cert);
//Check
var test = new X509Certificate2(_export);
if (test.HasPrivateKey)
throw new LicenseCertificateException("Exported certificate shouldn't conaint PK");
_clientId = _clientCertificate.GetSerialNumber();
}
示例2: Matches
public bool Matches(X509Certificate2 certificate)
{
if (certificate == null)
return false;
return Matches(certificate.Issuer, Asn1IntegerConverter.Asn1IntegerToDecimalString(certificate.GetSerialNumber()));
}
示例3: X509IssuerSerialKeyIdentifierClause
public X509IssuerSerialKeyIdentifierClause(X509Certificate2 certificate)
: base(null)
{
if (certificate == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate");
this.issuerName = certificate.Issuer;
this.issuerSerialNumber = Asn1IntegerConverter.Asn1IntegerToDecimalString(certificate.GetSerialNumber());
}
示例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: Main
public static void Main(string[] args)
{
string sn = string.Empty;
X509Certificate2 cert = new X509Certificate2();
cert.Import("CSD01_AAA010101AAA.cer");
foreach (var b in cert.GetSerialNumber()) {
sn = (char)b + sn;
}
Console.WriteLine (cert.Subject);
Console.WriteLine (cert.Version);
Console.WriteLine (cert.SignatureAlgorithm.Value.Replace("1.2.840.113549.1.1.5", "RSA_SHA1RSA"));
Console.WriteLine (cert.NotBefore);
Console.WriteLine (cert.NotAfter);
Console.WriteLine (cert.SerialNumber);
Console.WriteLine (sn);
}
示例6: Validate
public override void Validate(X509Certificate2 certificate)
{
Debugger.Launch();
if (!certificate.GetSerialNumber().SequenceEqual(new byte[] { 1, 2, 3 }))
{
throw new SecurityTokenValidationException("Serial number not in Allowed List");
}
// Check that there is a certificate.
if (certificate == null)
{
throw new ArgumentNullException("certificate");
}
// Check that the certificate issuer matches the configured issuer.
if (this.allowedIssuerName != certificate.IssuerName.Name)
{
throw new SecurityTokenValidationException
("Certificate was not issued by a trusted issuer");
}
}
示例7: GetCertificateSerialNumber
private string GetCertificateSerialNumber() {
string certificatePath = Bill.BillCertificatesFolder + this.IssuerData.CertificateFileName;
X509Certificate2 certificate = new X509Certificate2(certificatePath, this.IssuerData.GetCertificatePassword());
byte[] array = certificate.GetSerialNumber();
Array.Reverse(array);
return ASCIIEncoding.ASCII.GetString(array);
}
示例8: TryGetMatchingX509Certificate
private bool TryGetMatchingX509Certificate(IntPtr certContext, X509FindType findType, uint dwFindType, object findValue, bool validOnly, out X509Certificate2 cert)
{
cert = new X509Certificate2(certContext);
if (dwFindType == 0)
{
switch (findType)
{
case X509FindType.FindBySubjectDistinguishedName:
if (string.Compare((string) findValue, cert.SubjectName.Name, StringComparison.OrdinalIgnoreCase) == 0)
{
break;
}
cert.Reset();
cert = null;
return false;
case X509FindType.FindByIssuerDistinguishedName:
if (string.Compare((string) findValue, cert.IssuerName.Name, StringComparison.OrdinalIgnoreCase) == 0)
{
break;
}
cert.Reset();
cert = null;
return false;
case X509FindType.FindBySerialNumber:
if (this.BinaryMatches((byte[]) findValue, cert.GetSerialNumber()))
{
break;
}
cert.Reset();
cert = null;
return false;
case X509FindType.FindBySubjectKeyIdentifier:
{
X509SubjectKeyIdentifierExtension extension = cert.Extensions["2.5.29.14"] as X509SubjectKeyIdentifierExtension;
if ((extension == null) || !this.BinaryMatches((byte[]) findValue, extension.RawData))
{
cert.Reset();
cert = null;
return false;
}
break;
}
}
}
if (validOnly && !new X509Chain(false) { ChainPolicy = { RevocationMode = X509RevocationMode.NoCheck, RevocationFlag = X509RevocationFlag.ExcludeRoot } }.Build(cert))
{
cert.Reset();
cert = null;
return false;
}
return (cert != null);
}
示例9: getInfoCertificate
///<summary>
///Obtiene el numero de certificado y certificado codificado en base 64.
///</summary>
///<return>
///Devueve true, cuando es exitoso, false cuando ocurre algun error, la información la almacena en las variables
///privadas certificadeNumber y certificate, las cuales son accedidas por los metodos get
///</return>
///<param name="certificate">
///Ruta del archivo .cer en disco a leer.
///</param>
public Boolean getInfoCertificate(string certificate)
{
try
{
X509Certificate2 cert = new X509Certificate2(certificate);
string ncert = ReverseString(Encoding.Default.GetString(cert.GetSerialNumber()));
string str_cert = Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks);
str_cert = str_cert.Replace("\r\n", "");
this.code = "CERT-0001";
this.message = "Número de certificado obtenido con éxito";
this.certificateNumber = ncert;
this.certificate = str_cert;
}
catch (Exception e)
{
this.code = "EX-001";
this.message = "Error: " + e.Message;
return false;
}
return true;
}
示例10: TryGetMatchingX509Certificate
bool TryGetMatchingX509Certificate(IntPtr certContext, X509FindType findType,
uint dwFindType, object findValue, bool validOnly, out X509Certificate2 cert)
{
cert = new X509Certificate2(certContext);
if (dwFindType == CAPI.CERT_FIND_ANY)
{
switch (findType)
{
case X509FindType.FindBySubjectDistinguishedName:
if (0 != String.Compare((string)findValue, cert.SubjectName.Name, StringComparison.OrdinalIgnoreCase))
{
cert.Reset();
cert = null;
return false;
}
break;
case X509FindType.FindByIssuerDistinguishedName:
if (0 != String.Compare((string)findValue, cert.IssuerName.Name, StringComparison.OrdinalIgnoreCase))
{
cert.Reset();
cert = null;
return false;
}
break;
case X509FindType.FindBySerialNumber:
if (!BinaryMatches((byte[])findValue, cert.GetSerialNumber()))
{
cert.Reset();
cert = null;
return false;
}
break;
case X509FindType.FindBySubjectKeyIdentifier:
X509SubjectKeyIdentifierExtension skiExtension =
cert.Extensions[CAPI.SubjectKeyIdentifierOid] as X509SubjectKeyIdentifierExtension;
if (skiExtension == null || !BinaryMatches((byte[])findValue, skiExtension.RawData))
{
cert.Reset();
cert = null;
return false;
}
break;
default:
DiagnosticUtility.DebugAssert(findType + " is not supported!");
break;
}
}
if (validOnly)
{
X509Chain chain = new X509Chain(false);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
if (!chain.Build(cert))
{
cert.Reset();
cert = null;
return false;
}
}
return cert != null;
}
示例11: ESSCertIDv2
public ESSCertIDv2(X509Certificate2 cert)
{
// ASNTree root = new ASNTree(AsnTag.SEQUENCE);
ASNNode root = new ASNNode(AsnTag.SEQUENCE);
ASNNode node;
ASNNode node2;
ASNNode node3;
root.AppendChild(node = new ASNNode(AsnTag.SEQUENCE));
node.AppendChild(node = new ASNNode(AsnTag.SEQUENCE));
node2 = new ASNNode(cert.GetCertHash());
node2.Type = AsnTag.OCTET_STRING;
node.AppendChild(node2);
node3 = new ASNNode(cert.GetSerialNumber());
node3.Type = AsnTag.INTEGER;
node3.ReverseData();
node.AppendChild(node = new ASNNode(AsnTag.SEQUENCE));
node.AppendChild(node2 = new ASNNode(AsnTag.SEQUENCE));
node.AppendChild(node3);
node2.AppendChild(node = new ASNNode(AsnTag.CONTEXT_SPECIFIC));
node.AppendChild(new ASNNode(cert.IssuerName.RawData, AsnTag.RAW_DATA));
ret = root.get();
return;
}
示例12: AddCertificate
public ActionResult AddCertificate(TaxpayerCertificate item, IEnumerable<HttpPostedFileBase> files)
{
if (!ModelState.IsValid)
return View (item);
foreach (var file in files) {
if (file != null && file.ContentLength > 0) {
var name = file.FileName.ToLower ();
if (name.EndsWith (".cer")) {
item.CertificateData = FileToBytes (file);
} else if (name.EndsWith (".key")) {
item.KeyData = FileToBytes (file);
item.KeyPassword = Encoding.UTF8.GetBytes (item.KeyPassword2);
}
}
}
if (!CFDHelpers.PrivateKeyTest (item.KeyData, item.KeyPassword)) {
ModelState.AddModelError ("KeyPassword", Resources.Validation_InvalidPassword);
return View (item);
}
string sn = string.Empty;
var cert = new X509Certificate2 ();
cert.Import (item.CertificateData);
foreach (var b in cert.GetSerialNumber ()) {
sn = (char) b + sn;
}
item.Id = sn.PadLeft (20, '0');
var entity = TaxpayerCertificate.Queryable.SingleOrDefault (x => x.Id == item.Id);
if (entity == null) {
entity = new TaxpayerCertificate ();
}
entity.Id = item.Id;
entity.CertificateData = item.CertificateData;
entity.KeyData = item.KeyData;
entity.KeyPassword = item.KeyPassword;
entity.NotBefore = cert.NotBefore;
entity.NotAfter = cert.NotAfter;
entity.Taxpayer = TaxpayerIssuer.Find (item.TaxpayerId);
using (var scope = new TransactionScope ()) {
foreach (var x in entity.Taxpayer.Certificates) {
x.IsActive = false;
x.Update ();
}
entity.IsActive = true;
entity.SaveAndFlush ();
}
return RedirectToAction ("Details", new { id = item.TaxpayerId });
}
示例13: CreateCert
/// <summary>
/// Create a new certificate
/// </summary>
/// <param name="issuer">Issuer certificate, if null then self-sign</param>
/// <param name="subjectName">Subject name</param>
/// <param name="serialNumber">Serial number of certificate, if null then will generate a new one</param>
/// <param name="signature">If true create an AT_SIGNATURE key, otherwise AT_EXCHANGE</param>
/// <param name="keySize">Size of RSA key</param>
/// <param name="notBefore">Start date of certificate</param>
/// <param name="notAfter">End date of certificate</param>
/// <param name="extensions">Array of extensions, if null then no extensions</param>
/// <param name="hashAlgorithm">Specify the signature hash algorithm</param>
/// <returns>The created X509 certificate</returns>
public X509Certificate2 CreateCert(X509Certificate2 issuer, X500DistinguishedName subjectName, byte[] serialNumber, bool signature, int keySize, CertificateHashAlgorithm hashAlgorithm, DateTime notBefore, DateTime notAfter, X509ExtensionCollection extensions)
{
CryptoApiMethods.CERT_INFO certInfo = new CryptoApiMethods.CERT_INFO();
RSACryptoServiceProvider key = CreateRSAKey(keySize, signature);
IntPtr publicKeyInfoPtr = IntPtr.Zero;
X509Certificate2 cert = null;
List<X509Extension> newExts = null;
if (extensions != null)
{
foreach (X509Extension ext in extensions)
{
if (ext.RawData == null)
{
throw new ArgumentException(Properties.Resources.CreateCert_NeedEncodedData);
}
}
}
try
{
if (serialNumber == null)
{
serialNumber = Guid.NewGuid().ToByteArray();
}
certInfo.dwVersion = (uint)CryptoApiMethods.CertVersion.CERT_V3;
certInfo.SerialNumber = new CryptoApiMethods.CRYPTOAPI_BLOB(serialNumber);
certInfo.Subject = new CryptoApiMethods.CRYPTOAPI_BLOB(subjectName.RawData);
if (issuer == null)
{
// Self-signed
certInfo.Issuer = new CryptoApiMethods.CRYPTOAPI_BLOB(subjectName.RawData);
}
else
{
certInfo.Issuer = new CryptoApiMethods.CRYPTOAPI_BLOB(issuer.SubjectName.RawData);
}
// Never seems to need these set to anything valid?
certInfo.SubjectUniqueId = new CryptoApiMethods.CRYPT_BIT_BLOB();
certInfo.IssuerUniqueId = new CryptoApiMethods.CRYPT_BIT_BLOB();
certInfo.NotBefore = DateTimeToFileTime(notBefore);
certInfo.NotAfter = DateTimeToFileTime(notAfter);
certInfo.SignatureAlgorithm = new CryptoApiMethods.CRYPT_ALGORITHM_IDENTIFIER();
// Doesn't seem to work properly with standard szOID_RSA_SHA1RSA
//certInfo.SignatureAlgorithm.pszObjId = CryptoApiMethods.szOID_OIWSEC_sha1RSASign;
//certInfo.SignatureAlgorithm.pszObjId = CryptoApiMethods.szOID_RSA_SHA1RSA;
//certInfo.SignatureAlgorithm.pszObjId = CryptoApiMethods.szOID_RSA_SHA512RSA;
certInfo.SignatureAlgorithm.pszObjId = HashAlgorithmToOID(hashAlgorithm);
// Add extension fields
publicKeyInfoPtr = ExportPublicKeyInfo(key);
certInfo.SubjectPublicKeyInfo = (CryptoApiMethods.CERT_PUBLIC_KEY_INFO)Marshal.PtrToStructure(publicKeyInfoPtr, typeof(CryptoApiMethods.CERT_PUBLIC_KEY_INFO));
newExts = new List<X509Extension>();
if (extensions != null)
{
// Filter out some extensions we don't want
newExts.AddRange(
extensions.Cast<X509Extension>().Where(
x =>
!x.Oid.Value.Equals(CryptoApiMethods.szOID_AUTHORITY_KEY_IDENTIFIER)
&& !x.Oid.Value.Equals(CryptoApiMethods.szOID_SUBJECT_KEY_IDENTIFIER)
&& !x.Oid.Value.Equals(CryptoApiMethods.szOID_AUTHORITY_KEY_IDENTIFIER2)));
}
if (issuer != null)
{
newExts.Add(CreateAuthorityKeyInfo2(issuer.GetSerialNumber(), issuer.SubjectName, (RSACryptoServiceProvider)issuer.PrivateKey));
}
else
{
newExts.Add(CreateAuthorityKeyInfo2(serialNumber, subjectName, key));
}
newExts.Add(new X509SubjectKeyIdentifierExtension(HashPublicKeyInfo(key), false));
certInfo.rgExtension = MarshalExtensions(newExts.ToArray());
certInfo.cExtension = (uint)newExts.Count;
byte[] certData = EncodeAndSignCertInfo(issuer != null ? issuer.PrivateKey as RSACryptoServiceProvider : key, certInfo, hashAlgorithm);
//.........这里部分代码省略.........
示例14: CloneAndSignCertificate
/// <summary>
/// Take an existing certificate, clone its details and resign with a new root CA
/// </summary>
/// <param name="toClone">The certificate to clone</param>
/// <param name="rootCert">The root CA certificate to sign with</param>
/// <param name="newSerial">True to generate a new serial for this certificate</param>
/// <param name="rsaKeySize">The size of the RSA key to generate</param>
/// <param name="hashAlgorithm">Specify the signature hash algorithm</param>
/// <returns></returns>
public static X509Certificate2 CloneAndSignCertificate(X509Certificate toClone, X509Certificate2 rootCert, bool newSerial, int rsaKeySize, CertificateHashAlgorithm hashAlgorithm)
{
X509Certificate2 cert2 = new X509Certificate2(toClone);
X509ExtensionCollection extensions = new X509ExtensionCollection();
foreach (var ext in cert2.Extensions)
{
// Remove CRL distribution locations and authority information, they tend to break SSL negotiation
if ((ext.Oid.Value != szOID_CRL_DISTRIBUTION) && (ext.Oid.Value != szOID_AUTHORITY_INFO))
{
extensions.Add(ext);
}
}
return builder.CreateCert(rootCert, cert2.SubjectName, newSerial ? null : cert2.GetSerialNumber(),
false, rsaKeySize, hashAlgorithm, cert2.NotBefore, cert2.NotAfter, extensions);
}