本文整理汇总了C#中X509Certificate2类的典型用法代码示例。如果您正苦于以下问题:C# X509Certificate2类的具体用法?C# X509Certificate2怎么用?C# X509Certificate2使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
X509Certificate2类属于命名空间,在下文中一共展示了X509Certificate2类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestNullConstructorArguments
public static void TestNullConstructorArguments()
{
Assert.Throws<ArgumentException>(() => new X509Certificate2((byte[])null, (String)null));
Assert.Throws<ArgumentException>(() => new X509Certificate2(new byte[0], (String)null));
Assert.Throws<ArgumentException>(() => new X509Certificate2((byte[])null, (String)null, X509KeyStorageFlags.DefaultKeySet));
Assert.Throws<ArgumentException>(() => new X509Certificate2(new byte[0], (String)null, X509KeyStorageFlags.DefaultKeySet));
// For compat reasons, the (byte[]) constructor (and only that constructor) treats a null or 0-length array as the same
// as calling the default constructor.
{
using (X509Certificate2 c = new X509Certificate2((byte[])null))
{
IntPtr h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.Throws<CryptographicException>(() => c.GetCertHash());
}
}
{
using (X509Certificate2 c = new X509Certificate2(new byte[0]))
{
IntPtr h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.Throws<CryptographicException>(() => c.GetCertHash());
}
}
}
示例2: X509Cert2Test
public static void X509Cert2Test()
{
string certName = TestData.NormalizeX500String(
@"[email protected], CN=ABA.ECOM Root CA, O=""ABA.ECOM, INC."", L=Washington, S=DC, C=US");
DateTime notBefore = new DateTime(1999, 7, 12, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
DateTime notAfter = new DateTime(2009, 7, 9, 17, 33, 53, DateTimeKind.Utc).ToLocalTime();
using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.cer")))
{
Assert.Equal(certName, cert2.IssuerName.Name);
Assert.Equal(certName, cert2.SubjectName.Name);
Assert.Equal("ABA.ECOM Root CA", cert2.GetNameInfo(X509NameType.DnsName, true));
PublicKey pubKey = cert2.PublicKey;
Assert.Equal("RSA", pubKey.Oid.FriendlyName);
Assert.Equal(notAfter, cert2.NotAfter);
Assert.Equal(notBefore, cert2.NotBefore);
Assert.Equal("00D01E4090000046520000000100000004", cert2.SerialNumber);
Assert.Equal("1.2.840.113549.1.1.5", cert2.SignatureAlgorithm.Value);
Assert.Equal("7A74410FB0CD5C972A364B71BF031D88A6510E9E", cert2.Thumbprint);
Assert.Equal(3, cert2.Version);
}
}
示例3: GetHashForChannelBinding
internal static HashAlgorithm GetHashForChannelBinding(X509Certificate2 cert)
{
Oid signatureAlgorithm = cert.SignatureAlgorithm;
switch (signatureAlgorithm.Value)
{
// RFC 5929 4.1 says that MD5 and SHA1 both upgrade to EvpSha256 for cbt calculation
case "1.2.840.113549.2.5": // MD5
case "1.2.840.113549.1.1.4": // MD5RSA
case "1.3.14.3.2.26": // SHA1
case "1.2.840.10040.4.3": // SHA1DSA
case "1.2.840.10045.4.1": // SHA1ECDSA
case "1.2.840.113549.1.1.5": // SHA1RSA
case "2.16.840.1.101.3.4.2.1": // SHA256
case "1.2.840.10045.4.3.2": // SHA256ECDSA
case "1.2.840.113549.1.1.11": // SHA256RSA
return SHA256.Create();
case "2.16.840.1.101.3.4.2.2": // SHA384
case "1.2.840.10045.4.3.3": // SHA384ECDSA
case "1.2.840.113549.1.1.12": // SHA384RSA
return SHA384.Create();
case "2.16.840.1.101.3.4.2.3": // SHA512
case "1.2.840.10045.4.3.4": // SHA512ECDSA
case "1.2.840.113549.1.1.13": // SHA512RSA
return SHA512.Create();
default:
throw new ArgumentException(signatureAlgorithm.Value);
}
}
示例4: Main
static void Main(string[] args) {
if (args.Length != 4) {
Console.WriteLine("Usage: cra.exe cert-file cert-password input-path output-path");
return;
}
String certFile = args[0];
String password = args[1];
String input = args[2];
String output = args[3];
X509Certificate2 cert = new X509Certificate2(certFile, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(input);
var XmlToSign = new XmlDocument();
XmlToSign.LoadXml(xmlDoc.DocumentElement["Body"].OuterXml);
SignedXml signedXml = new SignedXml(XmlToSign);
signedXml.SigningKey = cert.PrivateKey;
Reference reference = new Reference();
reference.Uri = "";
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
signedXml.AddReference(reference);
signedXml.ComputeSignature();
XmlElement xmlDigitalSignature = signedXml.GetXml();
xmlDoc.DocumentElement["Body"].AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
xmlDoc.Save(output);
}
示例5: ImportedCollection
public ImportedCollection(X509Certificate2Collection collection)
{
// Make an independent copy of the certs to dispose (in case the test mutates the collection after we return.)
_certs = new X509Certificate2[collection.Count];
collection.CopyTo(_certs, 0);
Collection = collection;
}
示例6: TestImportNotSupported_X509Certificate2
public static void TestImportNotSupported_X509Certificate2()
{
using (var c = new X509Certificate2())
{
VerifyImportNotSupported(c);
}
}
示例7: CreateInstances
void CreateInstances()
{
bool res = false ;
string cd = Environment.CurrentDirectory + "\\" ;
X509Certificate2 real = null , fuzzed = null ;
string test = String.Empty ;
Result r = (Result) 0;
string[] realFiles = GetFiles( cd , allCerts ) ;
for( int i = 0 ; i < realFiles.Length ; i++ )
{
string fileName = realFiles[i].ToUpper().Replace( cd.ToUpper() , String.Empty ) ;
string[] fuzzFiles = GetFiles( dir , fileName.Substring( 0 , fileName.IndexOf(".") ) + "-*.c*r*" ) ;
try
{
real = new X509Certificate2( realFiles[i] ) ;
}
catch(Exception)
{
Console.WriteLine( realFiles[i] ) ;
break ;
}
Console.WriteLine( "Going to test {0}" , realFiles[i] ) ;
for( int j = 0 ; j < fuzzFiles.Length ; j++ )
{
res= false ;
if( fuzzFiles[j].ToLower().IndexOf(".tmp" ) > 0 )
{
j++ ;
if( j == fuzzFiles.Length )
break ;
}
Console.WriteLine( " with {0}" , fuzzFiles[j] ) ;
try
{
fuzzed = new X509Certificate2( fuzzFiles[j] ) ;
fuzzed.Verify() ;
res = fuzzed.ToString(true).Equals(real.ToString(true)) ;
r = res ? Result.Equals : Result.NotEquals ;
test = fuzzFiles[i] + " \n" ;
test += String.Format( "{0}\n\n!=\n\n{1}" , fuzzed.ToString(true),real.ToString(true) ) ;
}
catch(CryptographicException)
{
res = true ;
r = Result.CryptographicException ;
}
catch(Exception e)
{
Console.WriteLine(e) ;
r = Result.Exception ;
}
finally
{
Console.WriteLine( r ) ;
Eval( r!=Result.Exception , test ) ;
}
}
}
}
示例8: TestDefaultConstructor
public static void TestDefaultConstructor()
{
using (X509Certificate2 c = new X509Certificate2())
{
VerifyDefaultConstructor(c);
}
}
示例9: TestECDsa224PublicKey
public static void TestECDsa224PublicKey()
{
using (var cert = new X509Certificate2(TestData.ECDsa224Certificate))
{
// It is an Elliptic Curve Cryptography public key.
Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value);
ECDsa ecdsa;
try
{
ecdsa = cert.GetECDsaPublicKey();
}
catch (CryptographicException)
{
// Windows 7, Windows 8, CentOS.
return;
}
// Other Unix
using (ecdsa)
{
byte[] data = ByteUtils.AsciiBytes("Hello");
byte[] signature = (
// r
"8ede5053d546d35c1aba829bca3ecf493eb7a73f751548bd4cf2ad10" +
// s
"5e3da9d359001a6be18e2b4e49205e5219f30a9daeb026159f41b9de").HexToByteArray();
Assert.True(ecdsa.VerifyData(data, signature, HashAlgorithmName.SHA1));
}
}
}
示例10: TestByteArrayConstructor
public static void TestByteArrayConstructor()
{
byte[] expectedThumbPrint = new byte[]
{
0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
0xc3, 0x13, 0x87, 0xfe,
};
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
IntPtr h = c.Handle;
object ignored;
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = c.GetCertHash();
Assert.Equal(expectedThumbPrint, actualThumbprint);
c.Dispose();
// For compat reasons, Dispose() acts like the now-defunct Reset() method rather than causing ObjectDisposedExceptions.
h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.Throws<CryptographicException>(() => c.GetCertHash());
Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithm());
Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithmParameters());
Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
Assert.Throws<CryptographicException>(() => c.GetPublicKey());
Assert.Throws<CryptographicException>(() => c.GetSerialNumber());
Assert.Throws<CryptographicException>(() => ignored = c.Issuer);
Assert.Throws<CryptographicException>(() => ignored = c.Subject);
}
}
示例11: TestDefaultConstructor
public static void TestDefaultConstructor()
{
using (X509Certificate2 c = new X509Certificate2())
{
IntPtr h = c.Handle;
object ignored;
Assert.Equal(IntPtr.Zero, h);
Assert.Throws<CryptographicException>(() => c.GetCertHash());
Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithm());
Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithmParameters());
Assert.Throws<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
Assert.Throws<CryptographicException>(() => c.GetPublicKey());
Assert.Throws<CryptographicException>(() => c.GetSerialNumber());
Assert.Throws<CryptographicException>(() => ignored = c.Issuer);
Assert.Throws<CryptographicException>(() => ignored = c.Subject);
Assert.Throws<CryptographicException>(() => ignored = c.RawData);
Assert.Throws<CryptographicException>(() => ignored = c.Thumbprint);
Assert.Throws<CryptographicException>(() => ignored = c.SignatureAlgorithm);
Assert.Throws<CryptographicException>(() => ignored = c.HasPrivateKey);
Assert.Throws<CryptographicException>(() => ignored = c.Version);
Assert.Throws<CryptographicException>(() => ignored = c.Archived);
Assert.Throws<CryptographicException>(() => c.Archived = false);
Assert.Throws<CryptographicException>(() => c.FriendlyName = "Hi");
Assert.Throws<CryptographicException>(() => ignored = c.SubjectName);
Assert.Throws<CryptographicException>(() => ignored = c.IssuerName);
Assert.Throws<CryptographicException>(() => ignored = c.PrivateKey);
}
}
示例12: X509CertificateCollectionEnumerator
public static void X509CertificateCollectionEnumerator()
{
using (X509Certificate2 c1 = new X509Certificate2())
using (X509Certificate2 c2 = new X509Certificate2())
using (X509Certificate2 c3 = new X509Certificate2())
{
X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 });
X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator();
object ignored;
// Not started
Assert.Throws<InvalidOperationException>(() => ignored = e.Current);
Assert.True(e.MoveNext());
Assert.Same(c1, e.Current);
Assert.True(e.MoveNext());
Assert.Same(c2, e.Current);
Assert.True(e.MoveNext());
Assert.Same(c3, e.Current);
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
Assert.False(e.MoveNext());
// ended.
Assert.Throws<InvalidOperationException>(() => ignored = e.Current);
}
}
示例13: TestCert
public static bool TestCert(CertificateInfo ci)
{
bool bRes = true;
try {
X509Certificate2 cert;
if (ci.Password != null)
cert = new X509Certificate2(ci.FileName, ci.Password);
else
cert = new X509Certificate2(ci.FileName);
if (!ci.Matches(cert)) bRes = false;
// Console.WriteLine("ToString: " + cert.ToString());
// Console.WriteLine("ToString(true): " + cert.ToString(true));
X509Certificate2 certImp = new X509Certificate2();
if (ci.Password != null)
certImp.Import(ci.FileName, ci.Password, X509KeyStorageFlags.DefaultKeySet);
else
certImp.Import(ci.FileName);
if (!ci.Matches(certImp)) bRes = false;
}
catch(Exception e)
{
bRes = false;
Console.WriteLine("Exception is caught:" + Environment.NewLine + e.ToString());
}
return bRes;
}
示例14: ValidateCertificate
private static void ValidateCertificate(X509Certificate2 certificate, StoreName storeName, StoreLocation storeLocation)
{
Assert.True(certificate != null, "Certificate is null");
DateTime now = DateTime.Now;
Assert.True(now > certificate.NotBefore,
String.Format("The current date {{0}} is earlier than NotBefore ({1})",
now,
certificate.NotBefore));
Assert.True(now < certificate.NotAfter,
String.Format("The current date {{0}} is later than NotAfter ({1})",
now,
certificate.NotAfter));
using (X509Store store = new X509Store(storeName, storeLocation))
{
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, validOnly: true);
Assert.True(certificates.Count == 1,
String.Format("Did not find valid certificate with thumbprint {0} in StoreName '{1}', StoreLocation '{2}'",
certificate.Thumbprint,
storeName,
storeLocation));
}
using (X509Store store = new X509Store(StoreName.Disallowed, storeLocation))
{
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, validOnly: false);
Assert.True(certificates.Count == 0, "Certificate was found in Disallowed store.");
}
}
示例15: TestConstructor_DER
public static void TestConstructor_DER()
{
byte[] expectedThumbPrint = new byte[]
{
0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
0xc3, 0x13, 0x87, 0xfe,
};
Action<X509Certificate2> assert = (c) =>
{
IntPtr h = c.Handle;
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = c.GetCertHash();
Assert.Equal(expectedThumbPrint, actualThumbprint);
};
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
assert(c);
#if netstandard17
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
#endif
}
}