Exemplo n.º 1
0
        internal static X509Certificate2 IssueCertificate(
            string subjectName,
            X509Certificate2 issuerCertificate,
            bool isLeafCertificate,
            string[] subjectAlternativeNames = default(string[]),
            KeyPurposeID[] usages            = default(KeyPurposeID[]))
        {
            // It's self-signed, so these are the same.
            var issuerName = issuerCertificate.Subject;

            var random         = GetSecureRandom();
            var subjectKeyPair = GenerateKeyPair(random, 2048);

            var issuerKeyPair = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);

            var serialNumber       = GenerateSerialNumber(random);
            var issuerSerialNumber = new BigInteger(issuerCertificate.GetSerialNumber());

            bool isCertificateAuthority = !isLeafCertificate;
            var  certificate            = GenerateCertificate(
                random,
                subjectName,
                subjectKeyPair,
                serialNumber,
                subjectAlternativeNames,
                issuerName,
                issuerKeyPair,
                issuerSerialNumber,
                isCertificateAuthority,
                usages);

            return(ConvertCertificate(certificate, subjectKeyPair, random));
        }
        public bool Matches(X509Certificate2 certificate)
        {
            if (certificate == null)
                return false;

            return Matches(certificate.Issuer, Asn1IntegerConverter.Asn1IntegerToDecimalString(certificate.GetSerialNumber()));
        }
Exemplo n.º 3
0
        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();
        }
        public X509IssuerSerialKeyIdentifierClause(X509Certificate2 certificate)
            : base(null)
        {
            if (certificate == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate");

            this.issuerName = certificate.Issuer;
            this.issuerSerialNumber = Asn1IntegerConverter.Asn1IntegerToDecimalString(certificate.GetSerialNumber());
        }
Exemplo n.º 5
0
        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;
        }
Exemplo n.º 6
0
        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);
        }
        public static X509Certificates.X509Certificate2 IssueCertificate(
            string subjectName,
            X509Certificates.X509Certificate2 issuerCertificate,
            string[] subjectAlternativeNames,
            KeyPurposeID[] usages)
        {
            var random         = new SecureRandom(new CryptoApiRandomGenerator());
            var issuerName     = issuerCertificate.FriendlyName;
            var subjectKeyPair = GenerateKeyPair(random, 2048);
            var issuerKeyPair  = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);

            var subjectSerialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            var issuerSerialNumber  = new BigInteger(issuerCertificate.GetSerialNumber());

            var certificate = GenerateCertificate(random,
                                                  subjectName, subjectKeyPair, subjectSerialNumber, subjectAlternativeNames,
                                                  issuerName, issuerKeyPair, issuerSerialNumber, false, usages);

            return(certificate.ToX509Certificate2(subjectKeyPair, random));
        }
Exemplo n.º 8
0
        public static CertificadoDigital GetCertificadoDigital_v2(byte[] archivoCer)
        {
            var srtBase64   = "";
            var certificado = new CertificadoDigital();

            System.Security.Cryptography.X509Certificates.X509Certificate2 certEmisor = new System.Security.Cryptography.X509Certificates.X509Certificate2();
            byte[] data = archivoCer;

            certEmisor.Import(data);

            srtBase64 = Convert.ToBase64String(certEmisor.GetRawCertData());

            certificado.Certificado       = certEmisor.GetRawCertDataString();
            certificado.CertificadoBase64 = srtBase64;

            byte[] byteArray = certEmisor.GetSerialNumber();
            //string test = byteArray.ToString();

            string strSerialHex = certEmisor.GetSerialNumberString();

            string serialTest2 = certEmisor.SerialNumber;

            var strSerial = ConvertHexToString(strSerialHex);

            //var str = System.Text.Encoding.Default.GetString(byteArray);

            //string result = System.Text.Encoding.UTF8.GetString(byteArray);

            //System.Text.Encoding enc = System.Text.Encoding.ASCII;
            //string myString = enc.GetString(byteArray);
            //string s = System.Text.UTF8Encoding.UTF8.GetString(byteArray);


            //char[] array = str.ToCharArray();
            //Array.Reverse(array);
            //var nuevoStr = new string(array);

            certificado.NoCertificado = strSerial;//str;

            return(certificado);
        }
        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");
            }
        }
Exemplo n.º 10
0
        public CertificateAndPems IssueCertificate(string subjectName, X509Certificate2 issuerCertificate, AsymmetricAlgorithm issuerPrivateKey,
                                                   string[] subjectAlternativeNames, KeyPurposeID[] usages)
        {
            // It's self-signed, so these are the same.
            var issuerName = issuerCertificate.SubjectName.Decode(X500DistinguishedNameFlags.UseCommas);

            var random         = GetSecureRandom();
            var subjectKeyPair = GenerateKeyPair(random, 2048);

            var issuerKeyPair = DotNetUtilities.GetKeyPair(issuerPrivateKey);

            var serialNumber       = GenerateSerialNumber(random);
            var issuerSerialNumber = new BigInteger(issuerCertificate.GetSerialNumber());

            const bool isCertificateAuthority = false;
            var        certificate            = GenerateCertificate(random, subjectName, subjectKeyPair, serialNumber,
                                                                    subjectAlternativeNames, issuerName, issuerKeyPair,
                                                                    issuerSerialNumber, isCertificateAuthority,
                                                                    usages);

            return(new CertificateAndPems(ConvertCertificate(certificate, subjectKeyPair, random)));
        }
        void initializeFromCert(X509Certificate2 issuer, AuthorityKeyIdentifierFlags flags, Boolean critical)
        {
            Oid                = _oid;
            Critical           = critical;
            IncludedComponents = AuthorityKeyIdentifierFlags.None;
            // TODO rawData is not used
            List <Byte> rawData = new List <Byte>();

            if ((flags & AuthorityKeyIdentifierFlags.KeyIdentifier) > 0)
            {
                using (var hasher = SHA1.Create()) {
                    var hashbytes = hasher.ComputeHash(issuer.PublicKey.EncodedKeyValue.RawData);
                    KeyIdentifier = AsnFormatter.BinaryToString(hashbytes, EncodingType.HexRaw, EncodingFormat.NOCRLF);
                    rawData.AddRange(Asn1Utils.Encode(hashbytes, 0x80));
                }
                IncludedComponents |= AuthorityKeyIdentifierFlags.KeyIdentifier;
            }
            if ((flags & AuthorityKeyIdentifierFlags.AlternativeNames) > 0)
            {
                X509Extension san = issuer.Extensions[X509ExtensionOid.SubjectAlternativeNames];
                Debug.Assert(san != null, "san != null");
                AsnEncodedData encoded = new AsnEncodedData(san.RawData);
                var            sanExt  = new X509SubjectAlternativeNamesExtension(encoded, false);
                IssuerNames = sanExt.AlternativeNames;
                IssuerNames.Close();
                Asn1Reader asn = new Asn1Reader(san.RawData);
                rawData.AddRange(Asn1Utils.Encode(asn.GetPayload(), 0x81));
                IncludedComponents |= AuthorityKeyIdentifierFlags.AlternativeNames;
            }
            if ((flags & AuthorityKeyIdentifierFlags.SerialNumber) > 0)
            {
                SerialNumber = issuer.SerialNumber;
                rawData.AddRange(Asn1Utils.Encode(issuer.GetSerialNumber().Reverse().ToArray(), 0x82));
                IncludedComponents |= AuthorityKeyIdentifierFlags.SerialNumber;
            }
            RawData = Asn1Utils.Encode(rawData.ToArray(), 48);
        }
        ///// <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));
        }
Exemplo n.º 13
0
        private void Analizar(Byte[] ContenidoCertificado)
        {
            try
            {
                System.Security.Cryptography.X509Certificates.X509Certificate2 cer = new System.Security.Cryptography.X509Certificates.X509Certificate2(ContenidoCertificado);
                NumeroSerie            = InvertirStr(System.Text.Encoding.ASCII.GetString(cer.GetSerialNumber()));
                FechaFinCertificado    = System.Convert.ToDateTime(cer.GetExpirationDateString());
                FechaInicioCertificado = System.Convert.ToDateTime(cer.GetEffectiveDateString());
                EmisorCertificado      = cer.GetNameInfo(X509NameType.SimpleName, true);

                if (CA != null)
                {
                    foreach (System.Data.DataRow FilaCA in CA.Rows)
                    {
                        System.Security.Cryptography.X509Certificates.X509Certificate2 cerSAT = new System.Security.Cryptography.X509Certificates.X509Certificate2(System.Convert.FromBase64String(FilaCA["base64"].ToString()));
                        if (System.Convert.ToBase64String(cer.IssuerName.RawData) == System.Convert.ToBase64String(cerSAT.SubjectName.RawData))
                        {
                            EmitidoAutoridadCertificadora = true;
                        }
                    }
                }



                if (!String.IsNullOrEmpty(sArchivoKey) && !String.IsNullOrEmpty(sContraseña))
                {
                    byte[] CertModulus  = new byte[0];
                    byte[] CertExponent = new byte[0];

                    if (GetCertPublicKey(cer, out CertModulus, out CertExponent))
                    {
                        System.Security.Cryptography.RSACryptoServiceProvider RSA = null;
                        byte[] keyblob = SSLKey.opensslkey.GetFileBytes(sArchivoKey);
                        if (keyblob != null)
                        {
                            byte[] keyModulus  = new byte[0];
                            byte[] keyExponent = new byte[0];
                            if (SSLKey.opensslkey.getModulusExponentPrivateKeyInfo(keyblob, ConvertToSecureString(sContraseña), out keyModulus, out keyExponent))
                            {
                                if (CertExponent.Length == 3)
                                {
                                    CertExponent = IngresarByte(CertExponent, 4);
                                }
                                if (keyExponent.Length == 3)
                                {
                                    keyExponent = IngresarByte(keyExponent, 4);
                                }
                                if (CertModulus.Length < 128)
                                {
                                    CertModulus = IngresarByte(CertModulus, 128);
                                }
                                if (keyModulus.Length < 128)
                                {
                                    keyModulus = IngresarByte(keyModulus, 128);
                                }

                                if (CompareBytearrays(CertExponent, keyExponent) && CompareBytearrays(CertModulus, keyModulus))
                                {
                                    esKeyCertificado = true;
                                }
                            }
                        }
                    }
                }

                try
                {
                    String DatCert = cer.Subject;
                    int    posrfc  = DatCert.IndexOf("OID.2.5.4.45=") + ("OID.2.5.4.45=").Length;
                    RFCCertificado = DatCert.Substring(posrfc, DatCert.IndexOf(" ", posrfc) - posrfc).Trim().Replace(",", "");
                }
                catch (Exception ei)
                {
                }



                if (cer.Extensions["Uso de la clave"] != null)
                {
                    if (cer.Extensions["Uso de la clave"].RawData[3] == 192)
                    {
                        esCSD  = true;
                        esFIEL = false;
                    }

                    if (cer.Extensions["Uso de la clave"].RawData[3] == 232 || cer.Extensions["Uso de la clave"].RawData[3] == 216)
                    {
                        esFIEL = true;
                        esCSD  = false;
                    }
                }
                else if (cer.Extensions["Key Usage"] != null)
                {
                    if (cer.Extensions["Key Usage"].RawData[3] == 192)
                    {
                        esCSD  = true;
                        esFIEL = false;
                    }

                    if (cer.Extensions["Key Usage"].RawData[3] == 232 || cer.Extensions["Key Usage"].RawData[3] == 216)
                    {
                        esFIEL = true;
                        esCSD  = false;
                    }
                }
            }
            catch (Exception ex)
            {
                String Inner  = "";
                String Source = "";
                String Target = "";

                /* if (ex.InnerException != null)
                 *   Inner = " InnerException: " + ex.InnerException.Message;
                 * if (ex.Source != null)
                 *   Source = " Source: " + ex.Source;
                 * if (ex.TargetSite != null)
                 *   Target = " TargetSite: " + ex.TargetSite;
                 * throw new Exception("error analizando el certificado error: " + ex.Message + Inner + Source + Target );*/

                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 14
0
    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);
    }
        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);
        }
Exemplo n.º 16
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;
        }
Exemplo n.º 17
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);
        }
 ///<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;
 }
Exemplo n.º 19
0
        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 });
        }
Exemplo n.º 20
0
            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;
            }
Exemplo n.º 21
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 X509CertificateBuilderResult Build()
        {
            var issuerX509Certificate2 = new SystemX509Certificates.X509Certificate2(
                IssuerCertificate,
                IssuerCertificatePassword,
                SystemX509Certificates.X509KeyStorageFlags.Exportable
                );

            var issuerSubjectDN = issuerX509Certificate2.ToX509Certificate().SubjectDN;

            X509V3CertificateGenerator.SetIssuerDN(issuerSubjectDN);

            // Generate Keys.
            var rsaKeyPairGenerator = new RsaKeyPairGenerator();

            rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), this.KeySize));
            var asymmetricCipherKeyPair = rsaKeyPairGenerator.GenerateKeyPair();

            // Set Public Key.
            X509V3CertificateGenerator.SetPublicKey(asymmetricCipherKeyPair.Public);

            // Key Usage - for maximum interoperability, specify all four flags.
            var keyUsage = KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyEncipherment | KeyUsage.KeyAgreement;

            X509V3CertificateGenerator.AddExtension(
                X509Extensions.KeyUsage,
                true,
                new KeyUsage(keyUsage)
                );

            X509V3CertificateGenerator.AddExtension(
                X509Extensions.BasicConstraints,
                true,
                new BasicConstraints(false)
                );

            // Extended Key Usage.
            var extendedKeyUsage = new List <KeyPurposeID>();

            // Set TLS Web Server Authentication (1.3.6.1.5.5.7.3.1).
            if (IsServerAuthKeyUsage)
            {
                extendedKeyUsage.Add(KeyPurposeID.IdKPServerAuth);
            }

            // Set TLS Web Client Authentication (1.3.6.1.5.5.7.3.2).
            if (IsClientAuthKeyUsage)
            {
                extendedKeyUsage.Add(KeyPurposeID.IdKPClientAuth);
            }

            X509V3CertificateGenerator.AddExtension(
                X509Extensions.ExtendedKeyUsage,
                true,
                new ExtendedKeyUsage(extendedKeyUsage)
                );

            // Set Subject Alternative Names.
            if (SubjectAlternativeNames != null)
            {
                var subjectAlternativeNames = new Asn1Encodable[SubjectAlternativeNames.Count];

                for (int i = 0; i < SubjectAlternativeNames.Count; i++)
                {
                    subjectAlternativeNames[i] = new GeneralName(GeneralName.DnsName, SubjectAlternativeNames[i]);
                }

                X509V3CertificateGenerator.AddExtension(
                    X509Extensions.SubjectAlternativeName,
                    false,
                    new DerSequence(subjectAlternativeNames)
                    );
            }

            X509V3CertificateGenerator.AddExtension(
                X509Extensions.AuthorityKeyIdentifier,
                false,
                new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerX509Certificate2.GetPublicKeyAsAsymmetricKeyParameter()),
                    new GeneralNames(new GeneralName(issuerSubjectDN)),
                    new Org.BouncyCastle.Math.BigInteger(issuerX509Certificate2.GetSerialNumber())
                    )
                );

            X509V3CertificateGenerator.AddExtension(
                X509Extensions.SubjectKeyIdentifier,
                false,
                new SubjectKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(asymmetricCipherKeyPair.Public)
                    )
                );

            var signatureFactory = new Asn1SignatureFactory(GetSignatureAlgorithm(this.KeySize), issuerX509Certificate2.GetPrivateKeyAsAsymmetricKeyParameter());

            // Generate X.509 Certificate.
            var x509Certificate = X509V3CertificateGenerator.Generate(signatureFactory);

            return(new X509CertificateBuilderResult(x509Certificate, asymmetricCipherKeyPair.Private));
        }
        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;
        }