static X509Certificate2 GenerateCertificate(DateTime?notBefore = null, DateTime?notAfter = null, bool addServerAuthentication = true, bool addClientAuthentication = true) { var name = Guid.NewGuid().ToString("N"); var builder = new SubjectAlternativeNameBuilder(); builder.AddDnsName(name); var dn = new X500DistinguishedName($"CN={name}"); using (var rsa = RSA.Create(2048)) { var request = new CertificateRequest(dn, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); var usage = new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyAgreement, true); request.CertificateExtensions.Add(usage); var oids = new OidCollection(); if (addServerAuthentication) { oids.Add(new Oid("1.3.6.1.5.5.7.3.1")); } if (addClientAuthentication) { oids.Add(new Oid("1.3.6.1.5.5.7.3.2")); } request.CertificateExtensions.Add( new X509EnhancedKeyUsageExtension(oids, false)); request.CertificateExtensions.Add(builder.Build()); return(request.CreateSelfSigned(new DateTimeOffset(notBefore ?? DateTime.UtcNow.AddMinutes(-5)), new DateTimeOffset(notAfter ?? DateTime.UtcNow.AddMinutes(5)))); } }
public void ConstructorOidCollection() { OidCollection oc = new OidCollection(); X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension(oc, true); Assert.AreEqual("30-00", BitConverter.ToString(eku.RawData), "RawData"); Assert.AreEqual(0, eku.EnhancedKeyUsages.Count, "Count 0"); // FIXME: Don't expect that FriendlyName is English. This test fails under non-English Windows. //Assert.AreEqual ("Information Not Available", eku.Format (true), "Format(true)"); //Assert.AreEqual ("Information Not Available", eku.Format (false), "Format(false)"); oc.Add(new Oid("1.2.3.4")); Assert.AreEqual(0, eku.EnhancedKeyUsages.Count, "Count still 0"); int n = eku.EnhancedKeyUsages.Add(new Oid("1.2.3")); Assert.AreEqual(0, n, "Add"); Assert.AreEqual(0, eku.EnhancedKeyUsages.Count, "Count again 0"); // readonly! Assert.AreEqual(1, oc.Count, "Count 1 - oc"); Assert.AreEqual("1.2.3.4", oc [0].Value, "Value - oc"); oc.Add(new Oid("1.3.6.1.5.5.7.3.1")); eku = new X509EnhancedKeyUsageExtension(oc, true); Assert.AreEqual(2, eku.EnhancedKeyUsages.Count, "Count 2"); Assert.AreEqual("1.2.3.4", eku.EnhancedKeyUsages[0].Value, "Value - 1"); Assert.AreEqual("1.3.6.1.5.5.7.3.1", eku.EnhancedKeyUsages[1].Value, "Value - 2"); // FIXME: Don't expect that FriendlyName is English. This test fails under non-English Windows. //Assert.AreEqual ("Unknown Key Usage (1.2.3.4)" + Environment.NewLine + "Server Authentication (1.3.6.1.5.5.7.3.1)" + Environment.NewLine, // eku.Format (true), "Format(true)"); //Assert.AreEqual ("Unknown Key Usage (1.2.3.4), Server Authentication (1.3.6.1.5.5.7.3.1)", eku.Format (false), "Format(false)"); }
private OidEnumerator GetEnumerator() { OidCollection oc = new OidCollection(); oc.Add(new Oid("1.0")); oc.Add(new Oid("1.1")); oc.Add(new Oid("1.2")); return(oc.GetEnumerator()); }
public static void EncodeDecode_2Oids() { Oid oid1 = new Oid("1.3.6.1.5.5.7.3.1"); Oid oid2 = new Oid("1.3.6.1.4.1.311.10.3.1"); OidCollection usages = new OidCollection(); usages.Add(oid1); usages.Add(oid2); EncodeDecode(usages, false, "301606082b06010505070301060a2b0601040182370a0301".HexToByteArray()); }
public static void EnhancedKeyUsageExtension_2Oids() { Oid oid1 = Oid.FromOidValue("1.3.6.1.5.5.7.3.1", OidGroup.EnhancedKeyUsage); Oid oid2 = Oid.FromOidValue("1.3.6.1.4.1.311.10.3.1", OidGroup.EnhancedKeyUsage); OidCollection usages = new OidCollection(); usages.Add(oid1); usages.Add(oid2); TestEnhancedKeyUsageExtension(usages, false, "301606082b06010505070301060a2b0601040182370a0301".HexToByteArray()); }
public static void Main() { // Assign values to strings. string Value1 = "1.2.840.113549.1.1.1"; string Name1 = "3DES"; string Value2 = "1.3.6.1.4.1.311.20.2"; string InvalidName = "This name is not a valid name"; string InvalidValue = "1.1.1.1.1.1.1.1"; // Create new Oid objects using the specified values. // Note that the corresponding Value or Friendly Name property is automatically added to the object. Oid o1 = new Oid(Value1); Oid o2 = new Oid(Name1); // Create a new Oid object using the specified Value and Friendly Name properties. // Note that the two are not compared to determine if the Value is associated // with the Friendly Name. Oid o3 = new Oid(Value2, InvalidName); //Create a new Oid object using the specified Value. Note that if the value // is invalid or not known, no value is assigned to the Friendly Name property. Oid o4 = new Oid(InvalidValue); //Write out the property information of the Oid objects. Console.WriteLine("Oid1: Automatically assigned Friendly Name: {0}, {1}", o1.FriendlyName, o1.Value); Console.WriteLine("Oid2: Automatically assigned Value: {0}, {1}", o2.FriendlyName, o2.Value); Console.WriteLine("Oid3: Name and Value not compared: {0}, {1}", o3.FriendlyName, o3.Value); Console.WriteLine("Oid4: Invalid Value used: {0}, {1} {2}", o4.FriendlyName, o4.Value, Environment.NewLine); //Create an Oid collection and add several Oid objects. OidCollection oc = new OidCollection(); oc.Add(o1); oc.Add(o2); oc.Add(o3); Console.WriteLine("Number of Oids in the collection: {0}", oc.Count); Console.WriteLine("Is synchronized: {0} {1}", oc.IsSynchronized, Environment.NewLine); //Create an enumerator for moving through the collection. OidEnumerator oe = oc.GetEnumerator(); //You must execute a MoveNext() to get to the first item in the collection. oe.MoveNext(); // Write out Oids in the collection. Console.WriteLine("First Oid in collection: {0},{1}", oe.Current.FriendlyName, oe.Current.Value); oe.MoveNext(); Console.WriteLine("Second Oid in collection: {0},{1}", oe.Current.FriendlyName, oe.Current.Value); //Return index in the collection to the beginning. oe.Reset(); }
// internal internal AsnDecodeStatus Decode(byte[] extension) { if ((extension == null) || (extension.Length == 0)) { return(AsnDecodeStatus.BadAsn); } if (extension [0] != 0x30) { return(AsnDecodeStatus.BadTag); } if (_enhKeyUsage == null) { _enhKeyUsage = new OidCollection(); } try { ASN1 ex = new ASN1(extension); if (ex.Tag != 0x30) { throw new CryptographicException(Locale.GetText("Invalid ASN.1 Tag")); } for (int i = 0; i < ex.Count; i++) { _enhKeyUsage.Add(new Oid(ASN1Convert.ToOid(ex [i]))); } } catch { return(AsnDecodeStatus.BadAsn); } return(AsnDecodeStatus.Ok); }
public unsafe void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { OidCollection oids = new OidCollection(); using (SafeEkuExtensionHandle eku = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_EXTENDED_KEY_USAGE, encoded)) { Interop.libcrypto.CheckValidOpenSslHandle(eku); int count = Interop.Crypto.GetX509EkuFieldCount(eku); for (int i = 0; i < count; i++) { IntPtr oidPtr = Interop.Crypto.GetX509EkuField(eku, i); if (oidPtr == IntPtr.Zero) { throw Interop.libcrypto.CreateOpenSslCryptographicException(); } string oidValue = Interop.libcrypto.OBJ_obj2txt_helper(oidPtr); oids.Add(new Oid(oidValue)); } } usages = oids; }
void get_eku() { try { Object[] EkuObject = (Object[])_entry.Properties["pKIExtendedKeyUsage"].Value; if (EkuObject != null) { foreach (Object item in EkuObject) { _ekus.Add(new Oid(item.ToString())); } } } catch { String EkuString = (String)_entry.Properties["pKIExtendedKeyUsage"].Value; _ekus.Add(new Oid(EkuString)); } }
public static X509Certificate2 CreateSelfSignedCertificate(string subjectName, string[] extendedKeyUsageOids = null) { using var rsa = RSA.Create(2048); var request = new CertificateRequest($"CN={subjectName}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add( new X509BasicConstraintsExtension(false, false, 0, true)); request.CertificateExtensions.Add( new X509SubjectKeyIdentifierExtension(request.PublicKey, false)); request.CertificateExtensions.Add(new X509KeyUsageExtension(KeyUsageFlags, false)); var extendedKeyUsages = new OidCollection(); foreach (var oid in extendedKeyUsageOids ?? Array.Empty <string>()) { extendedKeyUsages.Add(new Oid(oid)); } var extension = new X509EnhancedKeyUsageExtension(extendedKeyUsages, false); request.CertificateExtensions.Add(extension); var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(10)), DateTimeOffset.UtcNow.AddYears(5)); return(certificate); }
public static X509Certificate2 CreateSelfSignedCertificate(string subject) { var oids = new OidCollection(); oids.Add(new Oid("1.3.6.1.5.5.7.3.2")); // client auth var extensions = new X509ExtensionCollection(); extensions.Add(new X509EnhancedKeyUsageExtension(oids, true)); var cgr = new CertificateGenerationRequest() { Subject = subject, Extensions = extensions, ExpirationLength = TimeSpan.FromDays(365 * 5), KeySize = 2048 }; var cert = CertificateGenerator.CreateSelfSignedCertificate(cgr); X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); try { store.Open(OpenFlags.ReadWrite); store.Add(cert); } finally { store.Close(); } return(cert); }
void get_eku() { try { Object[] EkuObject = (Object[])_entry[ActiveDirectory.PropCertTemplateEKU]; if (EkuObject != null) { foreach (Object item in EkuObject) { _ekus.Add(new Oid(item.ToString())); } } } catch { String EkuString = (String)_entry[ActiveDirectory.PropCertTemplateEKU]; _ekus.Add(new Oid(EkuString)); } }
public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { unsafe { usages = encoded.DecodeObject( CryptDecodeObjectStructType.X509_ENHANCED_KEY_USAGE, static delegate(void *pvDecoded, int cbDecoded) { var localUsages = new OidCollection(); Debug.Assert(cbDecoded >= sizeof(CERT_ENHKEY_USAGE)); CERT_ENHKEY_USAGE *pEnhKeyUsage = (CERT_ENHKEY_USAGE *)pvDecoded; int count = pEnhKeyUsage->cUsageIdentifier; for (int i = 0; i < count; i++) { IntPtr oidValuePointer = pEnhKeyUsage->rgpszUsageIdentifier[i]; string oidValue = Marshal.PtrToStringAnsi(oidValuePointer) !; Oid oid = new Oid(oidValue); localUsages.Add(oid); } return(localUsages); }); } }
private void DecodeExtension() { uint cbDecoded = 0; SafeLocalAllocHandle decoded = null; bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_ENHANCED_KEY_USAGE), m_rawData, out decoded, out cbDecoded); if (result == false) { throw new CryptographicException(Marshal.GetLastWin32Error()); } CAPI.CERT_ENHKEY_USAGE pEnhKeyUsage = (CAPI.CERT_ENHKEY_USAGE)Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CERT_ENHKEY_USAGE)); m_enhancedKeyUsages = new OidCollection(); for (int index = 0; index < pEnhKeyUsage.cUsageIdentifier; index++) { IntPtr pszOid = Marshal.ReadIntPtr(new IntPtr((long)pEnhKeyUsage.rgpszUsageIdentifier + index * Marshal.SizeOf(typeof(IntPtr)))); string oidValue = Marshal.PtrToStringAnsi(pszOid); Oid oid = new Oid(oidValue, OidGroup.ExtensionOrAttribute, false); m_enhancedKeyUsages.Add(oid); } m_decoded = true; decoded.Dispose(); }
public override void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { OidCollection oids = new OidCollection(); using (SafeEkuExtensionHandle eku = Interop.Crypto.DecodeExtendedKeyUsage(encoded, encoded.Length)) { Interop.Crypto.CheckValidOpenSslHandle(eku); int count = Interop.Crypto.GetX509EkuFieldCount(eku); for (int i = 0; i < count; i++) { IntPtr oidPtr = Interop.Crypto.GetX509EkuField(eku, i); if (oidPtr == IntPtr.Zero) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } string oidValue = Interop.Crypto.GetOidValue(oidPtr); oids.Add(new Oid(oidValue)); } } usages = oids; }
public virtual void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { // https://tools.ietf.org/html/rfc5924#section-4.1 // // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId // // KeyPurposeId ::= OBJECT IDENTIFIER try { AsnReader reader = new AsnReader(encoded, AsnEncodingRules.BER); AsnReader sequenceReader = reader.ReadSequence(); reader.ThrowIfNotEmpty(); usages = new OidCollection(); while (sequenceReader.HasData) { usages.Add(new Oid(sequenceReader.ReadObjectIdentifier(), null)); } } catch (AsnContentException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } }
public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { OidCollection localUsages = new OidCollection(); unsafe { encoded.DecodeObject( CryptDecodeObjectStructType.X509_ENHANCED_KEY_USAGE, delegate(void *pvDecoded) { CERT_ENHKEY_USAGE *pEnhKeyUsage = (CERT_ENHKEY_USAGE *)pvDecoded; int count = pEnhKeyUsage->cUsageIdentifier; for (int i = 0; i < count; i++) { IntPtr oidValuePointer = pEnhKeyUsage->rgpszUsageIdentifier[i]; String oidValue = Marshal.PtrToStringAnsi(oidValuePointer); Oid oid = new Oid(oidValue); localUsages.Add(oid); } } ); } usages = localUsages; return; }
/// <summary> /// Method to generate a self signed certificate /// </summary> /// <param name="validForHours">number of hours for which the certificate is valid.</param> /// <param name="subscriptionId">subscriptionId in question</param> /// <param name="certificateNamePrefix">prefix for the certificate name</param> /// <param name="issuer">issuer for the certificate</param> /// <param name="password">certificate password</param> /// <returns>certificate as an object</returns> public static X509Certificate2 CreateSelfSignedCertificate( int validForHours, string subscriptionId, string certificateNamePrefix, string issuer = DefaultIssuer, string password = DefaultPassword) { var friendlyName = GenerateCertFriendlyName( subscriptionId, certificateNamePrefix); var startTime = DateTime.UtcNow.AddMinutes(-10); var endTime = DateTime.UtcNow.AddHours(validForHours); var key = Create2048RsaKey(); var creationParams = new X509CertificateCreationParameters(new X500DistinguishedName(issuer)) { TakeOwnershipOfKey = true, StartTime = startTime, EndTime = endTime }; //// adding client authentication, -eku = 1.3.6.1.5.5.7.3.2, //// This is mandatory for the upload to be successful var oidCollection = new OidCollection(); oidCollection.Add( new Oid( OIDClientAuthValue, OIDClientAuthFriendlyName)); creationParams.Extensions.Add( new X509EnhancedKeyUsageExtension( oidCollection, false)); // Documentation of CreateSelfSignedCertificate states: // If creationParameters have TakeOwnershipOfKey set to true, the certificate // generated will own the key and the input CngKey will be disposed to ensure // that the caller doesn't accidentally use it beyond its lifetime (which is // now controlled by the certificate object). // We don't dispose it ourselves in this case. var cert = key.CreateSelfSignedCertificate(creationParams); key = null; cert.FriendlyName = friendlyName; // X509 certificate needs PersistKeySet flag set. // Reload a new X509Certificate2 instance from exported bytes in order to set the PersistKeySet flag. var bytes = cert.Export( X509ContentType.Pfx, password); // PfxValidation is not done here because these are newly created certs and assumed valid. return(NewX509Certificate2( bytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable, false)); }
public void CopyToOidNull() { OidCollection oc = new OidCollection(); oc.Add(new Oid("1.0")); Oid[] array = null; oc.CopyTo(array, 0); }
//BUG [ExpectedException (typeof (ArgumentNullException))] public void AddNull() { OidCollection oc = new OidCollection(); oc.Add(null); Assert.AreEqual(1, oc.Count, "Count"); // Assert.IsNull (oc, "[0]"); throw NullReferenceException }
void get_certpolicies() { CertificatePolicies = new OidCollection(); try { Object[] oids = (Object[])_entry[ActiveDirectory.PropPkiCertPolicy]; if (oids == null) { return; } foreach (Object oid in oids) { CertificatePolicies.Add(new Oid((String)oid)); } } catch { CertificatePolicies.Add(new Oid((String)_entry[ActiveDirectory.PropPkiCertPolicy])); } }
void get_certpolicies() { CertificatePolicies = new OidCollection(); try { Object[] oids = (Object[])_entry.Properties["msPKI-Certificate-Policy"].Value; if (oids == null) { return; } foreach (Object oid in oids) { CertificatePolicies.Add(new Oid((String)oid)); } } catch { CertificatePolicies.Add(new Oid((String)_entry.Properties["msPKI-Certificate-Policy"].Value)); } }
public void CopyToOid() { OidCollection oc = new OidCollection(); oc.Add(new Oid("1.0")); Oid[] array = new Oid [1]; oc.CopyTo(array, 0); Assert.AreEqual("1.0", array [0].Value, "CopyTo(Oid)"); }
public void Add() { OidCollection oc = new OidCollection(); oc.Add(new Oid("1.0")); Assert.AreEqual(1, oc.Count, "Count"); Assert.AreEqual("1.0", oc [0].Value, "[0]"); Assert.AreEqual("1.0", oc ["1.0"].Value, "['1.0']"); }
internal static bool GetExtendedKeyUsagesCallback(IntPtr pInfo, ref OidCollection pvParam) { CRYPT_OID_INFO oInfo = (CRYPT_OID_INFO)Marshal.PtrToStructure(pInfo, typeof(CRYPT_OID_INFO)); OidCollection ExtendedKeyUsages = (OidCollection)pvParam; ExtendedKeyUsages.Add(new Oid(oInfo.pszOID, oInfo.pwszName)); return(true); }
public OidCollection ToOoid() { var result = new OidCollection(); if (ClientAuth) { result.Add(ObjectId.kpClientAuth); } return(result); }
void get_rapolicies() { OidCollection oids = new OidCollection(); try { Object[] RaObject = (Object[])entry.Properties["msPKI-RA-Policies"].Value; if (RaObject != null) { foreach (Object obj in RaObject) { oids.Add(new Oid(obj.ToString())); } } } catch { String RaString = (String)entry.Properties["msPKI-RA-Policies"].Value; oids.Add(new Oid(RaString)); } CertificatePolicies = oids; }
/// <inheritdoc /> public OidCollection GetSubjectTemplateOIDs() { var retValue = new OidCollection(); getStringProperty(AdcsCAPropertyName.SubjectTemplateOIDs) ?.TrimEnd() .Split('\n') .ToList().ForEach(x => retValue.Add(new Oid(x))); return(retValue); }
void get_rapolicies() { OidCollection oids = new OidCollection(); try { Object[] RaObject = (Object[])_entry[DsUtils.PropPkiRaCertPolicy]; if (RaObject != null) { foreach (Object obj in RaObject) { oids.Add(new Oid(obj.ToString())); } } } catch { String RaString = (String)_entry[DsUtils.PropPkiRaCertPolicy]; oids.Add(new Oid(RaString)); } CertificatePolicies = oids; }
/// <summary> /// Adds an enumeration of <see cref="Oid"/> instances to this collection. /// </summary> /// <param name="oids">The collection to which to add values</param> /// <param name="newOids">The enumeration to add from</param> public static void Add(this OidCollection oids, IEnumerable <Oid> newOids) { if (newOids == null) { throw new ArgumentNullException("newOids"); } foreach (Oid oid in oids) { oids.Add(oid); } }
public X509EnhancedKeyUsageExtension (OidCollection enhancedKeyUsages, bool critical) { if (enhancedKeyUsages == null) throw new ArgumentNullException ("enhancedKeyUsages"); _oid = new Oid (oid, friendlyName); base.Critical = critical; _enhKeyUsage = new OidCollection(); foreach (Oid o in enhancedKeyUsages) { _enhKeyUsage.Add(o); } RawData = Encode (); }
public static void TestOidCollection() { int i; OidCollection c = new OidCollection(); Assert.Equal(0, c.Count); Oid o0 = new Oid(SHA1_Oid, SHA1_Name); i = c.Add(o0); Assert.Equal(0, i); Oid o1 = new Oid(SHA256_Oid, SHA256_Name); i = c.Add(o1); Assert.Equal(1, i); Assert.Equal(2, c.Count); Assert.Same(o0, c[0]); Assert.Same(o1, c[1]); Assert.Throws<ArgumentOutOfRangeException>(() => GC.KeepAlive(c[-1])); Assert.Throws<ArgumentOutOfRangeException>(() => GC.KeepAlive(c[c.Count])); Oid o2 = new Oid(SHA1_Oid, SHA1_Name); i = c.Add(o2); Assert.Equal(2, i); // If there multiple matches, the one with the lowest index wins. Assert.Same(o0, c[SHA1_Name]); Assert.Same(o0, c[SHA1_Oid]); Assert.Same(o1, c[SHA256_Name]); Assert.Same(o1, c[SHA256_Oid]); Oid o3 = new Oid(null, null); i = c.Add(o3); Assert.Equal(3, i); Assert.Throws<ArgumentNullException>(() => GC.KeepAlive(c[null])); Object o = c["BOGUSBOGUS"]; Assert.Null(c["BOGUSBOGUS"]); Oid[] a = new Oid[10]; for (int j = 0; j < a.Length; j++) { a[j] = new Oid(null, null); } Oid[] a2 = (Oid[])(a.Clone()); c.CopyTo(a2, 3); Assert.Equal(a[0], a2[0]); Assert.Equal(a[1], a2[1]); Assert.Equal(a[2], a2[2]); Assert.Equal(o0, a2[3]); Assert.Equal(o1, a2[4]); Assert.Equal(o2, a2[5]); Assert.Equal(o3, a2[6]); Assert.Equal(a[7], a2[7]); Assert.Equal(a[8], a2[8]); Assert.Equal(a[9], a2[9]); Assert.Throws<ArgumentNullException>(() => c.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => c.CopyTo(null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(a, -1)); Assert.Throws<ArgumentException>(() => c.CopyTo(a, 7)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(a, 1000)); ICollection ic = c; Assert.Throws<ArgumentException>(() => ic.CopyTo(new Oid[4, 3], 0)); Assert.Throws<InvalidCastException>(() => ic.CopyTo(new string[100], 0)); return; }