Наследование: ICollection, IEnumerable
Пример #1
0
        void m_initialize(Byte[] rawData)
        {
            Asn1Reader asn = new Asn1Reader(rawData);

            if (asn.Tag != 48)
            {
                throw new Asn1InvalidTagException(asn.Offset);
            }
            asn.MoveNext();
            SerialNumber = Asn1Utils.DecodeInteger(asn.GetTagRawData(), true);
            asn.MoveNext();
            if (asn.Tag != (Byte)Asn1Type.UTCTime && asn.Tag != (Byte)Asn1Type.GeneralizedTime)
            {
                throw new Asn1InvalidTagException(asn.Offset);
            }
            if (asn.Tag == (Byte)Asn1Type.UTCTime)
            {
                RevocationDate = new Asn1UtcTime(asn.GetTagRawData()).Value;
            }
            if (asn.Tag == (Byte)Asn1Type.GeneralizedTime)
            {
                RevocationDate = Asn1Utils.DecodeGeneralizedTime(asn.GetTagRawData());
            }
            if (asn.MoveNext())
            {
                var extensions = new X509ExtensionCollection();
                extensions.Decode(asn.GetTagRawData());
                X509Extension crlReason = extensions[X509CertExtensions.X509CRLReasonCode];
                if (crlReason != null)
                {
                    ReasonCode = crlReason.RawData[2];
                }
            }
            RawData = rawData;
        }
Пример #2
0
 /// <summary>
 /// Initializes a new version of the CertificateSettings class.
 /// </summary>
 public CertificateSettings()
 {
     _startDate = DateTime.Now;
     _endDate = DateTime.Now.AddYears(1);
     _signCertificate = true;
     _referenceKey = true;
     _extensions = new X509ExtensionCollection();
 }
Пример #3
0
 void SetExtensions(X509ExtensionCollection extensions)
 {
     if (_isGeneric)
     {
         throw new InvalidOperationException();
     }
     if (extensions == null)
     {
         throw new ArgumentNullException(nameof(extensions));
     }
 }
Пример #4
0
 public override void Reset()
 {
     _cert               = null;
     _archived           = false;
     _extensions         = null;
     _serial             = null;
     _publicKey          = null;
     issuer_name         = null;
     subject_name        = null;
     signature_algorithm = null;
 }
Пример #5
0
 /// <summary>Resets the state of an <see cref="T:System.Security.Cryptography.X509Certificates.X509Certificate2" /> object.</summary>
 public override void Reset()
 {
     this._cert               = null;
     this._archived           = false;
     this._extensions         = null;
     this._name               = string.Empty;
     this._serial             = null;
     this._publicKey          = null;
     this.issuer_name         = null;
     this.subject_name        = null;
     this.signature_algorithm = null;
     base.Reset();
 }
Пример #6
0
        public override void Reset()
        {
            _lazyRawData            = null;
            _lazySignatureAlgorithm = null;
            _lazyVersion            = 0;
            _lazySubjectName        = null;
            _lazyIssuerName         = null;
            _lazyPublicKey          = null;
            _lazyPrivateKey         = null;
            _lazyExtensions         = null;

            base.Reset();
        }
Пример #7
0
 /// <summary>
 /// Resets the state of an X509CRL2.
 /// </summary>
 /// <remarks>This method can be used to reset the state of the CRL. It also frees any resources associated with the CRL.</remarks>
 public void Reset()
 {
     Dispose();
     Extensions = new X509ExtensionCollection();
     RevokedCertificates.Clear();
     Version            = 0;
     Type               = X509CrlType.BaseCrl;
     IssuerName         = null;
     ThisUpdate         = new DateTime();
     NextUpdate         = null;
     SignatureAlgorithm = null;
     RawData            = null;
 }
Пример #8
0
        public override void Reset()
        {
            _lazyRawData = null;
            _lazySignatureAlgorithm = null;
            _lazyVersion = 0;
            _lazySubjectName = null;
            _lazyIssuerName = null;
            _lazyPublicKey = null;
            _lazyPrivateKey = null;
            _lazyExtensions = null;

            base.Reset();
        }
Пример #9
0
 public override void Reset()
 {
     _cert               = null;
     _archived           = false;
     _extensions         = null;
     _publicKey          = null;
     issuer_name         = null;
     subject_name        = null;
     signature_algorithm = null;
     if (intermediateCerts != null)
     {
         intermediateCerts.Dispose();
         intermediateCerts = null;
     }
 }
 public override void Reset()
 {
     this.m_version            = 0;
     this.m_notBefore          = DateTime.MinValue;
     this.m_notAfter           = DateTime.MinValue;
     this.m_privateKey         = null;
     this.m_publicKey          = null;
     this.m_extensions         = null;
     this.m_signatureAlgorithm = null;
     this.m_subjectName        = null;
     this.m_issuerName         = null;
     if (!this.m_safeCertContext.IsInvalid)
     {
         this.m_safeCertContext.Dispose();
         this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     }
     base.Reset();
 }
Пример #11
0
        /// <summary>
        /// Encodes revocation entry to a ASN.1-encoded byte array.
        /// </summary>
        /// <returns>ASN.1-encoded byte array</returns>
        public Byte[] Encode()
        {
            if (String.IsNullOrEmpty(SerialNumber))
            {
                throw new UninitializedObjectException();
            }
            List <Byte> rawData = new List <Byte>(AsnFormatter.StringToBinary(SerialNumber, EncodingType.HexAny));

            rawData = new List <Byte>(Asn1Utils.Encode(rawData.ToArray(), (Byte)Asn1Type.INTEGER));
            rawData.AddRange(Asn1Utils.EncodeDateTime(RevocationDate));
            if (ReasonCode != 0)
            {
                Byte[] reasonEnum                     = new Byte[] { 10, 1, (Byte)ReasonCode };
                X509ExtensionCollection exts          = new X509ExtensionCollection();
                X509Extension           CRlReasonCode = new X509Extension("2.5.29.21", reasonEnum, false);
                exts.Add(CRlReasonCode);
                rawData.AddRange(Crypt32Managed.EncodeX509Extensions(exts));
            }
            return(Asn1Utils.Encode(rawData.ToArray(), 48));
        }
        public override string ToString(bool verbose)
        {
            if (!verbose || this.m_safeCertContext.IsInvalid)
            {
                return(this.ToString());
            }
            StringBuilder sb = new StringBuilder();

            sb.Append("[Version]" + Environment.NewLine + "  ");
            sb.Append("V" + this.Version);
            sb.Append(Environment.NewLine + Environment.NewLine + "[Subject]" + Environment.NewLine + "  ");
            sb.Append(this.SubjectName.Name);
            string nameInfo = this.GetNameInfo(X509NameType.SimpleName, false);

            if (nameInfo.Length > 0)
            {
                sb.Append(Environment.NewLine + "  Simple Name: ");
                sb.Append(nameInfo);
            }
            string str2 = this.GetNameInfo(X509NameType.EmailName, false);

            if (str2.Length > 0)
            {
                sb.Append(Environment.NewLine + "  Email Name: ");
                sb.Append(str2);
            }
            string str3 = this.GetNameInfo(X509NameType.UpnName, false);

            if (str3.Length > 0)
            {
                sb.Append(Environment.NewLine + "  UPN Name: ");
                sb.Append(str3);
            }
            string str4 = this.GetNameInfo(X509NameType.DnsName, false);

            if (str4.Length > 0)
            {
                sb.Append(Environment.NewLine + "  DNS Name: ");
                sb.Append(str4);
            }
            sb.Append(Environment.NewLine + Environment.NewLine + "[Issuer]" + Environment.NewLine + "  ");
            sb.Append(this.IssuerName.Name);
            nameInfo = this.GetNameInfo(X509NameType.SimpleName, true);
            if (nameInfo.Length > 0)
            {
                sb.Append(Environment.NewLine + "  Simple Name: ");
                sb.Append(nameInfo);
            }
            str2 = this.GetNameInfo(X509NameType.EmailName, true);
            if (str2.Length > 0)
            {
                sb.Append(Environment.NewLine + "  Email Name: ");
                sb.Append(str2);
            }
            str3 = this.GetNameInfo(X509NameType.UpnName, true);
            if (str3.Length > 0)
            {
                sb.Append(Environment.NewLine + "  UPN Name: ");
                sb.Append(str3);
            }
            str4 = this.GetNameInfo(X509NameType.DnsName, true);
            if (str4.Length > 0)
            {
                sb.Append(Environment.NewLine + "  DNS Name: ");
                sb.Append(str4);
            }
            sb.Append(Environment.NewLine + Environment.NewLine + "[Serial Number]" + Environment.NewLine + "  ");
            sb.Append(this.SerialNumber);
            sb.Append(Environment.NewLine + Environment.NewLine + "[Not Before]" + Environment.NewLine + "  ");
            sb.Append(X509Certificate.FormatDate(this.NotBefore));
            sb.Append(Environment.NewLine + Environment.NewLine + "[Not After]" + Environment.NewLine + "  ");
            sb.Append(X509Certificate.FormatDate(this.NotAfter));
            sb.Append(Environment.NewLine + Environment.NewLine + "[Thumbprint]" + Environment.NewLine + "  ");
            sb.Append(this.Thumbprint);
            sb.Append(Environment.NewLine + Environment.NewLine + "[Signature Algorithm]" + Environment.NewLine + "  ");
            sb.Append(this.SignatureAlgorithm.FriendlyName + "(" + this.SignatureAlgorithm.Value + ")");
            System.Security.Cryptography.X509Certificates.PublicKey publicKey = this.PublicKey;
            sb.Append(Environment.NewLine + Environment.NewLine + "[Public Key]" + Environment.NewLine + "  Algorithm: ");
            sb.Append(publicKey.Oid.FriendlyName);
            sb.Append(Environment.NewLine + "  Length: ");
            sb.Append(publicKey.Key.KeySize);
            sb.Append(Environment.NewLine + "  Key Blob: ");
            sb.Append(publicKey.EncodedKeyValue.Format(true));
            sb.Append(Environment.NewLine + "  Parameters: ");
            sb.Append(publicKey.EncodedParameters.Format(true));
            this.AppendPrivateKeyInfo(sb);
            X509ExtensionCollection extensions = this.Extensions;

            if (extensions.Count > 0)
            {
                sb.Append(Environment.NewLine + Environment.NewLine + "[Extensions]");
                X509ExtensionEnumerator enumerator = extensions.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    X509Extension current = enumerator.Current;
                    sb.Append(Environment.NewLine + "* " + current.Oid.FriendlyName + "(" + current.Oid.Value + "):" + Environment.NewLine + "  " + current.Format(true));
                }
            }
            sb.Append(Environment.NewLine);
            return(sb.ToString());
        }
Пример #13
0
        /// <summary>
        /// Generate a self-signed CA certificate
        /// </summary>
        /// <param name="subject">The X500 subject string</param>
        /// <param name="rsaKeySize">The size of the RSA key to generate</param>
        /// <param name="hashAlgorithm">Specify the signature hash algorithm</param>
        /// <returns>An X509Certificate2 object containing the full certificate</returns>
        public static X509Certificate2 GenerateCACert(string subject, int rsaKeySize, CertificateHashAlgorithm hashAlgorithm)
        {
            X509ExtensionCollection exts = new X509ExtensionCollection();
            DateTime dt = DateTime.Now.AddYears(-1);

            exts.Add(new X509BasicConstraintsExtension(true, false, 0, false));

            return builder.CreateCert(null, new X500DistinguishedName(subject), null, false, rsaKeySize, hashAlgorithm, dt, dt.AddYears(10), exts);
        }
Пример #14
0
        /// <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 SystemX509.X509Certificate2 CreateCert(SystemX509.X509Certificate2 issuer, SystemX509.X500DistinguishedName subjectName,
                                                      byte[] serialNumber, bool signature, int keySize, CertificateHashAlgorithm hashAlgorithm, DateTime notBefore,
                                                      DateTime notAfter, SystemX509.X509ExtensionCollection extensions)
        {
            X509V3CertificateGenerator builder    = new X509V3CertificateGenerator();
            AsymmetricAlgorithm        subjectKey = CreateRSAKey(keySize, signature);
            AsymmetricAlgorithm        signKey    = issuer == null ? subjectKey : issuer.PrivateKey;

            if (signKey == null)
            {
                throw new ArgumentException(Properties.Resources.CreateCert_NoPrivateKey);
            }

            AsymmetricCipherKeyPair bcSubjectKey = GetRsaKeyPair((RSACryptoServiceProvider)subjectKey);
            AsymmetricCipherKeyPair bcSignKey    = GetRsaKeyPair((RSACryptoServiceProvider)signKey);

            X509Name issuerNameObj = issuer == null?X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData))
                                         : X509Name.GetInstance(Asn1Object.FromByteArray(issuer.SubjectName.RawData));

            X509Name subjectNameObj = X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData));

            BigInteger subjectSerial = new BigInteger(1, serialNumber != null ? serialNumber : Guid.NewGuid().ToByteArray());
            BigInteger issuerSerial  = issuer == null ? subjectSerial : new BigInteger(1, issuer.GetSerialNumber());

            builder.SetIssuerDN(issuerNameObj);
            builder.SetSubjectDN(subjectNameObj);
            builder.SetSerialNumber(subjectSerial);
            builder.SetSignatureAlgorithm(HashAlgorithmToName(hashAlgorithm));
            builder.SetNotBefore(notBefore.ToUniversalTime());
            builder.SetNotAfter(notAfter.ToUniversalTime());
            builder.SetPublicKey(bcSubjectKey.Public);

            SubjectPublicKeyInfo   info         = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSignKey.Public);
            AuthorityKeyIdentifier authKeyId    = new AuthorityKeyIdentifier(info, new GeneralNames(new GeneralName(issuerNameObj)), issuerSerial);
            SubjectKeyIdentifier   subjectKeyid = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSubjectKey.Public));

            builder.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authKeyId);
            builder.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, true, subjectKeyid);

            if (extensions != null)
            {
                foreach (SystemX509.X509Extension ext in extensions)
                {
                    if (!ext.Oid.Value.Equals(X509Extensions.AuthorityKeyIdentifier.Id) &&
                        !ext.Oid.Value.Equals(X509Extensions.SubjectKeyIdentifier.Id) &&
                        !ext.Oid.Value.Equals(szOID_AUTHORITY_KEY_IDENTIFIER2))
                    {
                        Asn1InputStream istm = new Org.BouncyCastle.Asn1.Asn1InputStream(ext.RawData);
                        Asn1Object      obj  = istm.ReadObject();
                        builder.AddExtension(ext.Oid.Value, ext.Critical, obj);
                    }
                }
            }

            X509Certificate cert = builder.Generate(bcSignKey.Private);

            SystemX509.X509Certificate2 ret = new SystemX509.X509Certificate2(cert.GetEncoded(), (string)null, SystemX509.X509KeyStorageFlags.Exportable);

            ret.PrivateKey = subjectKey;

            return(ret);
        }
Пример #15
0
 internal X509ExtensionEnumerator(X509ExtensionCollection extensions)
 {
     m_extensions = extensions;
     m_current    = -1;
 }
Пример #16
0
 public override void Reset () {
     m_version = 0; 
     m_notBefore = DateTime.MinValue;
     m_notAfter = DateTime.MinValue;
     m_privateKey = null;
     m_publicKey = null;
     m_extensions = null;
     m_signatureAlgorithm = null;
     m_subjectName = null;
     m_issuerName = null;
     if (!m_safeCertContext.IsInvalid) {
         // Free the current certificate handle
         m_safeCertContext.Dispose();
         m_safeCertContext = SafeCertContextHandle.InvalidHandle;
     }
     base.Reset();
 }
Пример #17
0
        /// <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);
        }
 public override void Reset()
 {
     this.m_version = 0;
     this.m_notBefore = DateTime.MinValue;
     this.m_notAfter = DateTime.MinValue;
     this.m_privateKey = null;
     this.m_publicKey = null;
     this.m_extensions = null;
     this.m_signatureAlgorithm = null;
     this.m_subjectName = null;
     this.m_issuerName = null;
     if (!this.m_safeCertContext.IsInvalid)
     {
         this.m_safeCertContext.Dispose();
         this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     }
     base.Reset();
 }
Пример #19
0
		public void Indexer_Int ()
		{
			X509ExtensionCollection c = new X509ExtensionCollection ();
			c.Add (extn_empty);
			Assert.AreEqual (extn_empty, c[0], "0");
		}
Пример #20
0
		public void ICollection_CopyTo ()
		{
			X509ExtensionCollection c = new X509ExtensionCollection ();
			c.Add (extn_empty);
			X509Extension[] array = new X509Extension[1];
			(c as ICollection).CopyTo (array, 0);
			Assert.AreEqual (extn_empty, array[0], "0");
		}
Пример #21
0
		public void Add ()
		{
			X509ExtensionCollection c = new X509ExtensionCollection ();
			Assert.AreEqual (0, c.Count, "Count-0");
			c.Add (extn_empty);
			Assert.AreEqual (1, c.Count, "Count-1");
		}
Пример #22
0
        private void buttonCreate_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            int rsaKeySize = 0;

            if (radioButtonSimpleCN.Checked && String.IsNullOrWhiteSpace(textBoxCN.Text))
            {
                MessageBox.Show(this, CANAPE.Properties.Resources.CreateCertForm_MustSpecifyCN,
                    CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (radioButtonTemplate.Checked && _templateCert == null)
            {
                MessageBox.Show(this, CANAPE.Properties.Resources.CreateCertForm_MustSpecifyTemplate,
                   CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (radioButtonSpecifyCA.Checked && _specifyCert == null)
            {
                MessageBox.Show(this, CANAPE.Properties.Resources.CreateCertForm_MustSpecifyCA,
                    CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (!int.TryParse(comboBoxRsaKeySize.Text, out rsaKeySize))
            {
                MessageBox.Show(this, CANAPE.Properties.Resources.CreateCertForm_MustSpecifyAValidRSAKeySize,
                    CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                try
                {
                    X509Certificate2 rootCert = null;

                    if (radioButtonSpecifyCA.Checked)
                    {
                        rootCert = _specifyCert;
                    }
                    else if (radioButtonDefaultCA.Checked)
                    {
                        rootCert = CertManager.GetRootCert();
                    }
                    else
                    {
                        // Self signed
                    }

                    if (radioButtonTemplate.Checked)
                    {
                        Certificate = CertificateUtils.CloneAndSignCertificate(_templateCert, rootCert, false, rsaKeySize, (CertificateHashAlgorithm)comboBoxHash.SelectedItem);
                    }
                    else
                    {
                        X509ExtensionCollection exts = new X509ExtensionCollection();
                        if (checkBoxCA.Checked)
                        {
                            exts.Add(new X509BasicConstraintsExtension(true, false, 0, true));
                        }

                        DateTime notBefore = DateTime.Now.Subtract(TimeSpan.FromDays(1));
                        Certificate = CertificateUtils.CreateCert(rootCert,
                            new X500DistinguishedName(radioButtonSubject.Checked ? textBoxCN.Text : String.Format("CN={0}", textBoxCN.Text)), null, false, rsaKeySize,
                            (CertificateHashAlgorithm)comboBoxHash.SelectedItem, notBefore, notBefore.AddYears(10), exts);
                    }
                }
                catch (Win32Exception ex)
                {
                    MessageBox.Show(ex.Message, CANAPE.Properties.Resources.MessageBox_ErrorString,
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (CryptographicException ex)
                {
                    MessageBox.Show(ex.Message, CANAPE.Properties.Resources.MessageBox_ErrorString,
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Пример #23
0
        /// <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);

                cert = new X509Certificate2(certData, (string)null, X509KeyStorageFlags.Exportable);
                cert.PrivateKey = key;
            }
            finally
            {
                if (certInfo.rgExtension != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(certInfo.rgExtension);
                }

                if (certInfo.Subject != null)
                {
                    certInfo.Subject.Release();
                }

                if (certInfo.Issuer != null)
                {
                    certInfo.Issuer.Release();
                }

                if (publicKeyInfoPtr != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(publicKeyInfoPtr);
                }
            }

            return cert;
        }
Пример #24
0
		public void Indexer_String ()
		{
			X509ExtensionCollection c = new X509ExtensionCollection ();
			c.Add (extn_empty);
			Assert.IsNull (c[String.Empty]);
			Assert.IsNull (c ["1.2.3"]);
			Assert.AreEqual (extn_empty, c["1.2"], "0");
		}
 internal X509ExtensionEnumerator(X509ExtensionCollection extensions)
 {
     this.m_extensions = extensions;
     this.m_current = -1;
 }
Пример #26
0
        // returns a list of IntPtr's; the first IntPtr is the pointer to the CERT_EXTENSIONS
        // strucuture; the other pointers are pointers that have to be released in order
        // to avoid leaking memory
        private static unsafe List<IntPtr> ConvertExtensions(X509ExtensionCollection extensions)
        {
            List<IntPtr> ret = new List<IntPtr>();
            if (extensions == null && extensions.Count == 0) {
                ret.Add(IntPtr.Zero);
                return ret;
            }

            int extensionStructSize = Marshal.SizeOf(typeof(CERT_EXTENSION));
            // create the pointer to the CERT_EXTENSIONS object
            CERT_EXTENSIONS extensionsStruct = new CERT_EXTENSIONS();
            IntPtr extensionsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CERT_EXTENSIONS)));
            ret.Add(extensionsPtr);
            extensionsStruct.cExtension = extensions.Count;
            extensionsStruct.rgExtension = Marshal.AllocHGlobal(extensionStructSize * extensions.Count); ;
            ret.Add(extensionsStruct.rgExtension);
            Marshal.StructureToPtr(extensionsStruct, extensionsPtr, false);

            // create the array of CERT_EXTENSION objects
            CERT_EXTENSION extensionStruct = new CERT_EXTENSION();
            byte* workPointer = (byte*)extensionsStruct.rgExtension.ToPointer();
            foreach(X509Extension ext in extensions) {
                // initialize the extension structure
                extensionStruct.pszObjId = Marshal.StringToHGlobalAnsi(ext.Oid.Value);
                ret.Add(extensionStruct.pszObjId);
                extensionStruct.fCritical = ext.Critical ? 1 : 0;
                byte[] rawData = ext.RawData;
                extensionStruct.cbData = rawData.Length;
                extensionStruct.pbData = Marshal.AllocHGlobal(rawData.Length); ;
                Marshal.Copy(rawData, 0, extensionStruct.pbData, rawData.Length);
                ret.Add(extensionStruct.pbData);
                // copy it to unmanaged memory
                Marshal.StructureToPtr(extensionStruct, new IntPtr(workPointer), false);
                workPointer += extensionStructSize;
            }
            // everything successfully created; return
            return ret;
        }
Пример #27
0
 /// <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="hashAlgorithm">The hash algorithm for the certificate</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>
 /// <returns>The created X509 certificate</returns>
 public static X509Certificate2 CreateCert(X509Certificate2 issuer, X500DistinguishedName subjectName, 
     byte[] serialNumber, bool signature, int keySize, CertificateHashAlgorithm hashAlgorithm, DateTime notBefore, DateTime notAfter, X509ExtensionCollection extensions)
 {
     return builder.CreateCert(issuer, subjectName, serialNumber, signature, keySize, hashAlgorithm, notBefore, notAfter, extensions);
 }
Пример #28
0
		public void FixtureSetUp ()
		{
			empty = new X509ExtensionCollection ();
			extn_empty = new X509Extension ("1.2", new byte[] { 0x05, 0x00 }, false);
		}
        ///// <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="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 static SystemX509.X509Certificate2 CreateCert(SystemX509.X509Certificate2 issuer, SystemX509.X500DistinguishedName subjectName,
                                                             byte[] serialNumber, int keySize, CertificateHashAlgorithm hashAlgorithm, DateTime notBefore,
                                                             DateTime notAfter, SystemX509.X509ExtensionCollection extensions)
        {
            SecureRandom random = new SecureRandom();
            X509V3CertificateGenerator builder      = new X509V3CertificateGenerator();
            AsymmetricCipherKeyPair    bcSubjectKey = CreateRSAKey(keySize, random);
            AsymmetricCipherKeyPair    bcSignKey    = issuer == null ? bcSubjectKey : issuer.GetBCPrivateKey();

            if (bcSignKey == null)
            {
                throw new ArgumentException("issuer");
            }

            X509Name issuerNameObj = issuer == null?X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData))
                                         : X509Name.GetInstance(Asn1Object.FromByteArray(issuer.SubjectName.RawData));

            X509Name subjectNameObj = X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData));

            BigInteger subjectSerial = new BigInteger(1, serialNumber != null ? serialNumber : Guid.NewGuid().ToByteArray());
            BigInteger issuerSerial  = issuer == null ? subjectSerial : new BigInteger(1, issuer.GetSerialNumber());

            builder.SetIssuerDN(issuerNameObj);
            builder.SetSubjectDN(subjectNameObj);
            builder.SetSerialNumber(subjectSerial);
            builder.SetNotBefore(notBefore.ToUniversalTime());
            builder.SetNotAfter(notAfter.ToUniversalTime());
            builder.SetPublicKey(bcSubjectKey.Public);

            SubjectPublicKeyInfo   info         = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSignKey.Public);
            AuthorityKeyIdentifier authKeyId    = new AuthorityKeyIdentifier(info, new GeneralNames(new GeneralName(issuerNameObj)), issuerSerial);
            SubjectKeyIdentifier   subjectKeyid = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSubjectKey.Public));

            builder.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authKeyId);
            builder.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, true, subjectKeyid);

            if (extensions != null)
            {
                foreach (SystemX509.X509Extension ext in extensions)
                {
                    if (!ext.Oid.Value.Equals(X509Extensions.AuthorityKeyIdentifier.Id) &&
                        !ext.Oid.Value.Equals(X509Extensions.SubjectKeyIdentifier.Id) &&
                        !ext.Oid.Value.Equals(szOID_AUTHORITY_KEY_IDENTIFIER2))
                    {
                        Asn1InputStream istm = new Asn1InputStream(ext.RawData);
                        Asn1Object      obj  = istm.ReadObject();
                        builder.AddExtension(ext.Oid.Value, ext.Critical, obj);
                    }
                }
            }

            X509Certificate cert = builder.Generate(CreateSignatureFactory(hashAlgorithm, bcSignKey, random));

            Pkcs12StoreBuilder   pkcs  = new Pkcs12StoreBuilder();
            Pkcs12Store          store = pkcs.Build();
            X509CertificateEntry entry = new X509CertificateEntry(cert);

            store.SetCertificateEntry("main", entry);

            AsymmetricKeyEntry key_entry = new AsymmetricKeyEntry(bcSubjectKey.Private);

            store.SetKeyEntry("main", key_entry, new[] { entry });
            MemoryStream stm = new MemoryStream();

            store.Save(stm, new char[0], new SecureRandom());
            return(new SystemX509.X509Certificate2(stm.ToArray(), String.Empty, SystemX509.X509KeyStorageFlags.Exportable));
        }
Пример #30
0
		public override void Reset () 
		{
			_cert = null;
			_archived = false;
			_extensions = null;
			_name = String.Empty;
			_serial = null;
			_publicKey = null;
			issuer_name = null;
			subject_name = null;
			signature_algorithm = null;
			base.Reset ();
		}
Пример #31
0
        public override string ToString(bool verbose)
        {
            if (verbose == false || Pal == null)
            {
                return(ToString());
            }

            StringBuilder sb = new StringBuilder();

            // Version
            sb.AppendLine("[Version]");
            sb.Append("  V");
            sb.Append(Version);

            // Subject
            sb.AppendLine();
            sb.AppendLine();
            sb.AppendLine("[Subject]");
            sb.Append("  ");
            sb.Append(SubjectName.Name);
            string simpleName = GetNameInfo(X509NameType.SimpleName, false);

            if (simpleName.Length > 0)
            {
                sb.AppendLine();
                sb.Append("  ");
                sb.Append("Simple Name: ");
                sb.Append(simpleName);
            }
            string emailName = GetNameInfo(X509NameType.EmailName, false);

            if (emailName.Length > 0)
            {
                sb.AppendLine();
                sb.Append("  ");
                sb.Append("Email Name: ");
                sb.Append(emailName);
            }
            string upnName = GetNameInfo(X509NameType.UpnName, false);

            if (upnName.Length > 0)
            {
                sb.AppendLine();
                sb.Append("  ");
                sb.Append("UPN Name: ");
                sb.Append(upnName);
            }
            string dnsName = GetNameInfo(X509NameType.DnsName, false);

            if (dnsName.Length > 0)
            {
                sb.AppendLine();
                sb.Append("  ");
                sb.Append("DNS Name: ");
                sb.Append(dnsName);
            }

            // Issuer
            sb.AppendLine();
            sb.AppendLine();
            sb.AppendLine("[Issuer]");
            sb.Append("  ");
            sb.Append(IssuerName.Name);
            simpleName = GetNameInfo(X509NameType.SimpleName, true);
            if (simpleName.Length > 0)
            {
                sb.AppendLine();
                sb.Append("  ");
                sb.Append("Simple Name: ");
                sb.Append(simpleName);
            }
            emailName = GetNameInfo(X509NameType.EmailName, true);
            if (emailName.Length > 0)
            {
                sb.AppendLine();
                sb.Append("  ");
                sb.Append("Email Name: ");
                sb.Append(emailName);
            }
            upnName = GetNameInfo(X509NameType.UpnName, true);
            if (upnName.Length > 0)
            {
                sb.AppendLine();
                sb.Append("  ");
                sb.Append("UPN Name: ");
                sb.Append(upnName);
            }
            dnsName = GetNameInfo(X509NameType.DnsName, true);
            if (dnsName.Length > 0)
            {
                sb.AppendLine();
                sb.Append("  ");
                sb.Append("DNS Name: ");
                sb.Append(dnsName);
            }

            // Serial Number
            sb.AppendLine();
            sb.AppendLine();
            sb.AppendLine("[Serial Number]");
            sb.Append("  ");
            sb.AppendLine(SerialNumber);

            // NotBefore
            sb.AppendLine();
            sb.AppendLine("[Not Before]");
            sb.Append("  ");
            sb.AppendLine(FormatDate(NotBefore));

            // NotAfter
            sb.AppendLine();
            sb.AppendLine("[Not After]");
            sb.Append("  ");
            sb.AppendLine(FormatDate(NotAfter));

            // Thumbprint
            sb.AppendLine();
            sb.AppendLine("[Thumbprint]");
            sb.Append("  ");
            sb.AppendLine(Thumbprint);

            // Signature Algorithm
            sb.AppendLine();
            sb.AppendLine("[Signature Algorithm]");
            sb.Append("  ");
            sb.Append(SignatureAlgorithm.FriendlyName);
            sb.Append('(');
            sb.Append(SignatureAlgorithm.Value);
            sb.AppendLine(")");

            // Public Key
            sb.AppendLine();
            sb.Append("[Public Key]");
            // It could throw if it's some user-defined CryptoServiceProvider
            try
            {
                PublicKey pubKey = PublicKey;

                sb.AppendLine();
                sb.Append("  ");
                sb.Append("Algorithm: ");
                sb.Append(pubKey.Oid.FriendlyName);
                // So far, we only support RSACryptoServiceProvider & DSACryptoServiceProvider Keys
                try
                {
                    sb.AppendLine();
                    sb.Append("  ");
                    sb.Append("Length: ");

                    using (RSA? pubRsa = this.GetRSAPublicKey())
                    {
                        if (pubRsa != null)
                        {
                            sb.Append(pubRsa.KeySize);
                        }
                    }
                }
                catch (NotSupportedException)
                {
                }

                sb.AppendLine();
                sb.Append("  ");
                sb.Append("Key Blob: ");
                sb.AppendLine(pubKey.EncodedKeyValue.Format(true));

                sb.Append("  ");
                sb.Append("Parameters: ");
                sb.Append(pubKey.EncodedParameters.Format(true));
            }
            catch (CryptographicException)
            {
            }

            // Private key
            Pal.AppendPrivateKeyInfo(sb);

            // Extensions
            X509ExtensionCollection extensions = Extensions;

            if (extensions.Count > 0)
            {
                sb.AppendLine();
                sb.AppendLine();
                sb.Append("[Extensions]");
                foreach (X509Extension extension in extensions)
                {
                    try
                    {
                        sb.AppendLine();
                        sb.Append("* ");
                        sb.Append(extension.Oid !.FriendlyName);
                        sb.Append('(');
                        sb.Append(extension.Oid.Value);
                        sb.Append("):");

                        sb.AppendLine();
                        sb.Append("  ");
                        sb.Append(extension.Format(true));
                    }
                    catch (CryptographicException)
                    {
                    }
                }
            }

            sb.AppendLine();
            return(sb.ToString());
        }
		internal X509ExtensionEnumerator (X509ExtensionCollection collection)
		{
			enumerator = ((IEnumerable) collection).GetEnumerator ();
		}