Пример #1
0
        public override Crt ImportCertificate(EncodingFormat fmt, Stream source)
        {
            if (false)
            {
                throw new NotImplementedException();
            }

            X509Certificate bcCert = null;

            if (fmt == EncodingFormat.DER)
            {
                var certParser = new X509CertificateParser();
                bcCert = certParser.ReadCertificate(source);
            }
            else if (fmt == EncodingFormat.PEM)
            {
                using (var tr = new StreamReader(source))
                {
                    var pr = new PemReader(tr);
                    bcCert = (X509Certificate)pr.ReadObject();
                }
            }
            else
            {
                throw new NotSupportedException("encoding format has not been implemented");
            }

            using (var tw = new StringWriter())
            {
                var pw = new PemWriter(tw);
                pw.WriteObject(bcCert);
                return(new Crt {
                    Pem = tw.GetStringBuilder().ToString()
                });
            }
        }
Пример #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsRecipient"/> class.
        /// </summary>
        /// <remarks>
        /// <para>Creates a new <see cref="CmsRecipient"/>, loading the certificate from the specified file.</para>
        /// <para>The initial value of the <see cref="EncryptionAlgorithms"/> property will be set to
        /// the Triple-DES encryption algorithm, which should be safe to assume for all modern
        /// S/MIME v3.x client implementations.</para>
        /// </remarks>
        /// <param name="fileName">The file containing the recipient's certificate.</param>
        /// <param name="recipientIdentifierType">The recipient identifier type.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="fileName"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// <paramref name="fileName"/> is a zero-length string, contains only white space, or
        /// contains one or more invalid characters as defined by
        /// <see cref="System.IO.Path.InvalidPathChars"/>.
        /// </exception>
        /// <exception cref="System.IO.DirectoryNotFoundException">
        /// <paramref name="fileName"/> is an invalid file path.
        /// </exception>
        /// <exception cref="System.IO.FileNotFoundException">
        /// The specified file path could not be found.
        /// </exception>
        /// <exception cref="System.UnauthorizedAccessException">
        /// The user does not have access to read the specified file.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public CmsRecipient(string fileName, SubjectIdentifierType recipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            var parser = new X509CertificateParser();

            if (recipientIdentifierType == SubjectIdentifierType.IssuerAndSerialNumber)
            {
                RecipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
            }
            else
            {
                RecipientIdentifierType = SubjectIdentifierType.SubjectKeyIdentifier;
            }

            EncryptionAlgorithms    = new EncryptionAlgorithm[] { EncryptionAlgorithm.TripleDes };
            RecipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;

            using (var stream = File.OpenRead(fileName))
                Certificate = parser.ReadCertificate(stream);
        }
Пример #3
0
        private void AddCertsFromSet(
            IList certs,
            Asn1Set certSet)
        {
            X509CertificateParser cf = new X509CertificateParser();

            foreach (Asn1Encodable ae in certSet)
            {
                try
                {
                    Asn1Object obj = ae.ToAsn1Object();

                    if (obj is Asn1Sequence)
                    {
                        // TODO Build certificate directly from sequence?
                        certs.Add(cf.ReadCertificate(obj.GetEncoded()));
                    }
                }
                catch (Exception ex)
                {
                    throw new CmsException("can't re-encode certificate!", ex);
                }
            }
        }
        public ValidadorCertificado()
        {
            _certificados = new Dictionary <string, RSAPKCS1SignatureDeformatter>();
            var ruta = ConfigurationManager.AppSettings["CertsValidacion"];

            if (Directory.Exists(ruta))
            {
                var certs = Directory.EnumerateFiles(ruta);
                foreach (var cert in certs)
                {
                    X509CertificateParser parser            = new X509CertificateParser();
                    Org.BouncyCastle.X509.X509Certificate c = parser.ReadCertificate(File.ReadAllBytes(cert));
                    var pk            = c.GetPublicKey() as RsaKeyParameters;
                    var rsaParameters = new RSAParameters();
                    rsaParameters.Modulus  = pk.Modulus.ToByteArrayUnsigned();
                    rsaParameters.Exponent = pk.Exponent.ToByteArrayUnsigned();
                    RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)RSA.Create();
                    rsa.ImportParameters(rsaParameters);
                    RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(rsa);
                    deformatter.SetHashAlgorithm("SHA1");
                    _certificados.Add(Path.GetFileNameWithoutExtension(cert), deformatter);
                }
            }
        }
Пример #5
0
        /// <summary>
        /// Verifica singolo Certificato
        /// </summary>
        /// <param name="CertificateDer">Bytearray del certificato x509</param>
        /// <param name="CertificateCAPEM">non usato</param>
        /// <param name="args">parametri di oggetti opzionali</param>
        /// <returns>Ritorna lo status della verifica.</returns>
        public EsitoVerifica VerificaCertificato(byte[] CertificateDer, byte[] CertificateCAPEM, Object[] args)
        {
            EsitoVerifica retval = null;
            string        cachePath;
            bool          forceDownload = false;

            if (args.Length > 0)
            {
                cachePath = args[1] as string;

                string fdl = args[2] as string;
                if (!String.IsNullOrEmpty(fdl))
                {
                    Boolean.TryParse(fdl, out forceDownload);
                }

                //funzioni bouncycastle per estrapolare il certificato dal binario
                X509CertificateParser cp   = new X509CertificateParser();
                X509Certificate       cert = cp.ReadCertificate(CertificateDer);

                List <DocsPaVO.documento.Internal.SignerInfo> retSI = new List <DocsPaVO.documento.Internal.SignerInfo>();
                List <PKCS7Document> p7doc = new List <PKCS7Document>();
                retSI.Add(GetCertSignersInfo(cert));
                p7doc.Add(new PKCS7Document {
                    SignersInfo = retSI.ToArray()
                });

                //Questo scarica la CRL e fa la verifica.
                retval = controllaCrlCert(cert, cachePath, forceDownload);
                int statusInt = (int)retval.status;
                retval.VerifySignatureResult = new VerifySignatureResult {
                    StatusCode = statusInt, PKCS7Documents = p7doc.ToArray()
                };
            }
            return(retval);
        }
Пример #6
0
        public void TestAddRemoveRange()
        {
            var certificates = new List <X509Certificate> ();
            var parser       = new X509CertificateParser();
            var store        = new X509CertificateStore();

            foreach (var authority in CertificateAuthorities)
            {
                var path = GetTestDataPath(authority);

                using (var stream = File.OpenRead(path)) {
                    foreach (X509Certificate certificate in parser.ReadCertificates(stream))
                    {
                        certificates.Add(certificate);
                    }
                }
            }

            store.AddRange(certificates);

            var count = store.Certificates.Count();

            Assert.AreEqual(CertificateAuthorities.Length, count, "Unexpected number of certificates after AddRange.");

            foreach (var certificate in certificates)
            {
                var key = store.GetPrivateKey(certificate);
                Assert.IsNull(key, "GetPrivateKey");
            }

            store.RemoveRange(certificates);

            count = store.Certificates.Count();

            Assert.AreEqual(0, count, "Unexpected number of certificates after RemoveRange.");
        }
Пример #7
0
        public static BcCertificate ImportCertificate(EncodingFormat fmt, Stream source)
        {
            X509Certificate bcCert = null;

            if (fmt == EncodingFormat.DER)
            {
                var certParser = new X509CertificateParser();
                bcCert = certParser.ReadCertificate(source);
            }
            else if (fmt == EncodingFormat.PEM)
            {
                using (var tr = new StreamReader(source))
                {
                    var pr = new PemReader(tr);
                    bcCert = (X509Certificate)pr.ReadObject();
                }
            }
            else
            {
                throw new NotSupportedException("encoding format has not been implemented");
            }

            return(bcCert);
        }
Пример #8
0
        X509CertificateRecord LoadCertificateRecord(DbDataReader reader, X509CertificateParser parser, ref byte[] buffer)
        {
            var record = new X509CertificateRecord();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                switch (reader.GetName(i).ToUpperInvariant())
                {
                case "CERTIFICATE":
                    record.Certificate = DecodeCertificate(reader, parser, i, ref buffer);
                    break;

                case "PRIVATEKEY":
                    record.PrivateKey = DecodePrivateKey(reader, i, ref buffer);
                    break;

                case "ALGORITHMS":
                    record.Algorithms = DecodeEncryptionAlgorithms(reader, i);
                    break;

                case "ALGORITHMSUPDATED":
                    record.AlgorithmsUpdated = DateTime.SpecifyKind(reader.GetDateTime(i), DateTimeKind.Utc);
                    break;

                case "TRUSTED":
                    record.IsTrusted = reader.GetBoolean(i);
                    break;

                case "ID":
                    record.Id = reader.GetInt32(i);
                    break;
                }
            }

            return(record);
        }
Пример #9
0
        /// <summary>
        /// Finds the certificates matching the specified selector.
        /// </summary>
        /// <remarks>
        /// Searches the database for certificates matching the selector, returning all
        /// matching certificates.
        /// </remarks>
        /// <returns>The matching certificates.</returns>
        /// <param name="selector">The match selector or <c>null</c> to return all certificates.</param>
        public IEnumerable <X509Certificate> FindCertificates(IX509Selector selector)
        {
            using (var command = GetSelectCommand(selector, false, false, X509CertificateRecordFields.Certificate)) {
                var reader = command.ExecuteReader();

                try {
                    var parser = new X509CertificateParser();
                    var buffer = new byte[4096];

                    while (reader.Read())
                    {
                        var record = LoadCertificateRecord(reader, parser, ref buffer);
                        if (selector == null || selector.Match(record.Certificate))
                        {
                            yield return(record.Certificate);
                        }
                    }
                } finally {
                    reader.Close();
                }
            }

            yield break;
        }
Пример #10
0
        /// <summary>
        /// Generate PFX File
        /// </summary>
        /// <param name="signedCERFile"></param>
        /// <param name="privateKeyFile"></param>
        /// <param name="v"></param>
        /// <param name="password"></param>
        private async void GeneratePFXFile(string signedCERFile, string privateKeyFile, string generateCertificateFile,
                                           string password, string friendlyName, string signedCACERFile = null)
        {
            // Prepare the pkcs12 certificate store
            Pkcs12Store            store      = new Pkcs12StoreBuilder().Build();
            AsymmetricKeyParameter privateKey = ReadPrivateKey(privateKeyFile);

            X509CertificateEntry[] chain = null;

            // Check if CA root public key file exist? If exist read data from file and verify certificate inside signed requested public key file with CA root public key
            // If Ca root public key file does not exist, certificate inside signed requested public key file CAN NOT be veryfied
            // Bundle together the private key, signed certificate and CA
            Org.BouncyCastle.X509.X509Certificate CAX509Cert = null;
            if (String.IsNullOrEmpty(signedCACERFile))
            {
                chain = new X509CertificateEntry[1];
                //chain[0] = certEntry;
            }
            else
            {
                chain = new X509CertificateEntry[2];
                //chain[0] = certEntry;

                try
                {
                    // Import the CA certificate
                    X509Certificate2 certCA = new X509Certificate2(signedCACERFile);
                    //then export it like so
                    byte[] p12CA = certCA.Export(X509ContentType.Cert);
                    CAX509Cert = new X509CertificateParser().ReadCertificate(p12CA);
                    X509CertificateEntry certCAEntry = new X509CertificateEntry(CAX509Cert);
                    chain[1] = certCAEntry;
                }
                catch (Exception ex)
                {
                    Brush bckForeground = tbOutputMessageBox.Foreground;
                    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                    tbOutputMessageBox.Text      += "Error reading root CA certificate file: " + signedCACERFile + "\n";
                    tbOutputMessageBox.Foreground = bckForeground;
                    return;
                }
            }

            // Import data from the signed requested certificate file => file with .cer extension (NOT CA root public key file)
            X509Certificate2 certSigned = new X509Certificate2(signedCERFile);

            int errorNum = 0;

            #region check - old
            // This is .cer public key file and it doesn't have private key => it's OK
            //bool isHasPrivateKey = certSigned.HasPrivateKey;
            //if (!isHasPrivateKey)
            //{
            //    errorNum++;
            //    Brush bckForeground = tbOutputMessageBox.Foreground;
            //    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
            //    tbOutputMessageBox.Text += "Error, certificate file: "+ signedCERFile+" DOES NOT have a private key!!!" + "\n";
            //    tbOutputMessageBox.Foreground = bckForeground;
            //}

            // This is certificate signed with CA root that not yet been imported to Trusted Root Certification Authorities and can't be verified
            //bool isOK = certSigned.Verify();
            //if (!isOK)
            //{
            //    errorNum++;
            //    Brush bckForeground = tbOutputMessageBox.Foreground;
            //    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
            //    tbOutputMessageBox.Text += "Error, certificate file: " + signedCERFile + " NOT valid!!!" + "\n";
            //    tbOutputMessageBox.Foreground = bckForeground;
            //}
            #endregion

            //then export it like so
            byte[] p12 = certSigned.Export(X509ContentType.Cert);
            Org.BouncyCastle.X509.X509Certificate signedX509Cert = new X509CertificateParser().ReadCertificate(p12);

            if (CAX509Cert != null)
            {
                try
                {
                    signedX509Cert.Verify(CAX509Cert.GetPublicKey());
                }
                catch (Exception ex)
                {
                    errorNum++;
                    Brush bckForeground = tbOutputMessageBox.Foreground;
                    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                    tbOutputMessageBox.Text      += "Error certificate file: " + signedCERFile + " Verification error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                    tbOutputMessageBox.Foreground = bckForeground;
                }
            }
            else
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Yellow);
                tbOutputMessageBox.Text      += "Certificate file: " + signedCERFile + " CAN NOT be verified, because CA root public key file not provided" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            if (errorNum > 0)
            {
                return;
            }

            X509CertificateEntry certEntry = new X509CertificateEntry(signedX509Cert);
            chain[0] = certEntry;
            store.SetKeyEntry(signedX509Cert.SubjectDN.ToString() + "_key", new AsymmetricKeyEntry(privateKey), chain);

            // Add the certificate.
            X509CertificateEntry certificateEntry = new X509CertificateEntry(signedX509Cert);
            store.SetCertificateEntry(friendlyName, certificateEntry);

            // Add the private key.
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), new[] { certificateEntry });

            try
            {
                using (var filestream = new FileStream(generateCertificateFile, FileMode.Create, FileAccess.ReadWrite))
                {
                    store.Save(filestream, password.ToCharArray(), new SecureRandom());
                }

                if (chain.Length > 1)
                {
                    tbOutputMessageBox.Text += "Certificate file with private key: " + generateCertificateFile + " and CA public key sucessfully generated." + "\n";
                }
                else
                {
                    tbOutputMessageBox.Text += "Certificate file with private key: " + generateCertificateFile + " sucessfully generated." + "\n";
                }
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                if (chain.Length > 1)
                {
                    tbOutputMessageBox.Text += "Error, certificate file with private key: " + generateCertificateFile + " and CA public key DOES NOT sucessfully generated." + "\n";
                }
                else
                {
                    tbOutputMessageBox.Text += "Certificate file with private key: " + generateCertificateFile + " DOES NOT sucessfully generated." + "\n";
                }
                tbOutputMessageBox.Foreground = bckForeground;

                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR creating certificate file with private key file (.pfx)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }
        }
Пример #11
0
        public void Load(
            Stream input,
            char[] password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            Asn1Sequence obj             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          bag             = new Pfx(obj);
            ContentInfo  info            = bag.AuthSafe;
            bool         unmarkedKey     = false;
            bool         wrongPkcs12Zero = false;

            if (bag.MacData != null) // check the mac code
            {
                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

                byte[] data = ((Asn1OctetString)info.Content).GetOctets();

                byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data);
                byte[] dig = dInfo.GetDigest();

                if (!Arrays.ConstantTimeAreEqual(mac, dig))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    // Try with incorrect zero length password
                    mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data);

                    if (!Arrays.ConstantTimeAreEqual(mac, dig))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    wrongPkcs12Zero = true;
                }
            }

            keys.Clear();
            localIds.Clear();

            IList chain = Platform.CreateArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octs     = ((Asn1OctetString)info.Content).GetOctets();
                AuthenticatedSafe authSafe = new AuthenticatedSafe(
                    (Asn1Sequence)Asn1OctetString.FromByteArray(octs));
                ContentInfo[] cis = authSafe.GetContentInfo();

                foreach (ContentInfo ci in cis)
                {
                    DerObjectIdentifier oid = ci.ContentType;

                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        byte[]       octets = ((Asn1OctetString)ci.Content).GetOctets();
                        Asn1Sequence seq    = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                                    password, wrongPkcs12Zero, eIn);
                                IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                IDictionary        attributes = Platform.CreateHashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                string             alias      = null;
                                Asn1OctetString    localId    = null;

                                if (b.BagAttributes != null)
                                {
                                    foreach (Asn1Sequence sq in b.BagAttributes)
                                    {
                                        DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                        Asn1Set             attrSet = (Asn1Set)sq[1];
                                        Asn1Encodable       attr    = null;

                                        if (attrSet.Count > 0)
                                        {
                                            // TODO We should be adding all attributes in the set
                                            attr = attrSet[0];

                                            // TODO We might want to "merge" attribute sets with
                                            // the same OID - currently, differing values give an error
                                            if (attributes.Contains(aOid.Id))
                                            {
                                                // OK, but the value has to be the same
                                                if (!attributes[aOid.Id].Equals(attr))
                                                {
                                                    throw new IOException("attempt to add existing attribute with different value");
                                                }
                                            }
                                            else
                                            {
                                                attributes.Add(aOid.Id, attr);
                                            }

                                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                            {
                                                alias = ((DerBmpString)attr).GetString();
                                                // TODO Do these in a separate loop, just collect aliases here
                                                keys[alias] = pkcs12Key;
                                            }
                                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                            {
                                                localId = (Asn1OctetString)attr;
                                            }
                                        }
                                    }
                                }

                                if (localId != null)
                                {
                                    string name = Hex.ToHexString(localId.GetOctets());

                                    if (alias == null)
                                    {
                                        keys[name] = pkcs12Key;
                                    }
                                    else
                                    {
                                        // TODO There may have been more than one alias
                                        localIds[alias] = name;
                                    }
                                }
                                else
                                {
                                    unmarkedKey      = true;
                                    keys["unmarked"] = pkcs12Key;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                chain.Add(b);
                            }
                            else
                            {
#if !NETFX_CORE
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
#endif
                            }
                        }
                    }
                    else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        EncryptedData d      = EncryptedData.GetInstance(ci.Content);
                        byte[]        octets = CryptPbeData(false, d.EncryptionAlgorithm,
                                                            password, wrongPkcs12Zero, d.Content.GetOctets());
                        Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                chain.Add(b);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                                    password, wrongPkcs12Zero, eIn);
                                IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                IDictionary        attributes = Platform.CreateHashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                string             alias      = null;
                                Asn1OctetString    localId    = null;

                                foreach (Asn1Sequence sq in b.BagAttributes)
                                {
                                    DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                    Asn1Set             attrSet = (Asn1Set)sq[1];
                                    Asn1Encodable       attr    = null;

                                    if (attrSet.Count > 0)
                                    {
                                        // TODO We should be adding all attributes in the set
                                        attr = attrSet[0];

                                        // TODO We might want to "merge" attribute sets with
                                        // the same OID - currently, differing values give an error
                                        if (attributes.Contains(aOid.Id))
                                        {
                                            // OK, but the value has to be the same
                                            if (!attributes[aOid.Id].Equals(attr))
                                            {
                                                throw new IOException("attempt to add existing attribute with different value");
                                            }
                                        }
                                        else
                                        {
                                            attributes.Add(aOid.Id, attr);
                                        }

                                        if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                        {
                                            alias = ((DerBmpString)attr).GetString();
                                            // TODO Do these in a separate loop, just collect aliases here
                                            keys[alias] = pkcs12Key;
                                        }
                                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                        {
                                            localId = (Asn1OctetString)attr;
                                        }
                                    }
                                }

                                // TODO Should we be checking localIds != null here
                                // as for PkcsObjectIdentifiers.Data version above?

                                string name = Hex.ToHexString(localId.GetOctets());

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    // TODO There may have been more than one alias
                                    localIds[alias] = name;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                PrivateKeyInfo          privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue);
                                IAsymmetricKeyParameter privKey     = PrivateKeyFactory.CreateKey(privKeyInfo);

                                //
                                // set the attributes on the key
                                //
                                string             alias      = null;
                                Asn1OctetString    localId    = null;
                                IDictionary        attributes = Platform.CreateHashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);

                                foreach (Asn1Sequence sq in b.BagAttributes)
                                {
                                    DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                    Asn1Set             attrSet = (Asn1Set)sq[1];
                                    Asn1Encodable       attr    = null;

                                    if (attrSet.Count > 0)
                                    {
                                        // TODO We should be adding all attributes in the set
                                        attr = attrSet[0];

                                        // TODO We might want to "merge" attribute sets with
                                        // the same OID - currently, differing values give an error
                                        if (attributes.Contains(aOid.Id))
                                        {
                                            // OK, but the value has to be the same
                                            if (!attributes[aOid.Id].Equals(attr))
                                            {
                                                throw new IOException("attempt to add existing attribute with different value");
                                            }
                                        }
                                        else
                                        {
                                            attributes.Add(aOid.Id, attr);
                                        }

                                        if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                        {
                                            alias = ((DerBmpString)attr).GetString();
                                            // TODO Do these in a separate loop, just collect aliases here
                                            keys[alias] = pkcs12Key;
                                        }
                                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                        {
                                            localId = (Asn1OctetString)attr;
                                        }
                                    }
                                }

                                // TODO Should we be checking localIds != null here
                                // as for PkcsObjectIdentifiers.Data version above?

                                string name = Hex.ToHexString(localId.GetOctets());

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    // TODO There may have been more than one alias
                                    localIds[alias] = name;
                                }
                            }
                            else
                            {
#if !NETFX_CORE
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
#endif
                            }
                        }
                    }
                    else
                    {
#if !NETFX_CORE
                        Console.WriteLine("extra " + oid);
                        Console.WriteLine("extra " + Asn1Dump.DumpAsString(ci.Content));
#endif
                    }
                }
            }

            certs.Clear();
            chainCerts.Clear();
            keyCerts.Clear();

            foreach (SafeBag b in chain)
            {
                CertBag         cb     = new CertBag((Asn1Sequence)b.BagValue);
                byte[]          octets = ((Asn1OctetString)cb.CertValue).GetOctets();
                X509Certificate cert   = new X509CertificateParser().ReadCertificate(octets);

                //
                // set the attributes
                //
                IDictionary     attributes = Platform.CreateHashtable();
                Asn1OctetString localId    = null;
                string          alias      = null;

                if (b.BagAttributes != null)
                {
                    foreach (Asn1Sequence sq in b.BagAttributes)
                    {
                        DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                        Asn1Set             attrSet = (Asn1Set)sq[1];

                        if (attrSet.Count > 0)
                        {
                            // TODO We should be adding all attributes in the set
                            Asn1Encodable attr = attrSet[0];

                            // TODO We might want to "merge" attribute sets with
                            // the same OID - currently, differing values give an error
                            if (attributes.Contains(aOid.Id))
                            {
                                // OK, but the value has to be the same
                                if (!attributes[aOid.Id].Equals(attr))
                                {
                                    throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                attributes.Add(aOid.Id, attr);
                            }

                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                alias = ((DerBmpString)attr).GetString();
                            }
                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                localId = (Asn1OctetString)attr;
                            }
                        }
                    }
                }

                CertId certId = new CertId(cert.GetPublicKey());
                X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes);

                chainCerts[certId] = pkcs12Cert;

                if (unmarkedKey)
                {
                    if (keyCerts.Count == 0)
                    {
                        string name = Hex.ToHexString(certId.Id);

                        keyCerts[name] = pkcs12Cert;

                        object temp = keys["unmarked"];
                        keys.Remove("unmarked");
                        keys[name] = temp;
                    }
                }
                else
                {
                    if (localId != null)
                    {
                        string name = Hex.ToHexString(localId.GetOctets());

                        keyCerts[name] = pkcs12Cert;
                    }

                    if (alias != null)
                    {
                        // TODO There may have been more than one alias
                        certs[alias] = pkcs12Cert;
                    }
                }
            }
        }
Пример #12
0
        public void Load(
            Stream input,
            char[]      password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            Asn1Sequence obj             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          bag             = new Pfx(obj);
            ContentInfo  info            = bag.AuthSafe;
            bool         wrongPkcs12Zero = false;

            if (password != null && bag.MacData != null) // check the mac code
            {
                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

                byte[] data = ((Asn1OctetString)info.Content).GetOctets();

                byte[] mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, false, data);
                byte[] dig = dInfo.GetDigest();

                if (!Arrays.ConstantTimeAreEqual(mac, dig))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    // Try with incorrect zero length password
                    mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, true, data);

                    if (!Arrays.ConstantTimeAreEqual(mac, dig))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    wrongPkcs12Zero = true;
                }
            }

            keys.Clear();
            localIds.Clear();
            unmarkedKeyEntry = null;

            IList certBags = Platform.CreateArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octs     = ((Asn1OctetString)info.Content).GetOctets();
                AuthenticatedSafe authSafe = new AuthenticatedSafe(
                    (Asn1Sequence)Asn1OctetString.FromByteArray(octs));
                ContentInfo[] cis = authSafe.GetContentInfo();

                foreach (ContentInfo ci in cis)
                {
                    DerObjectIdentifier oid = ci.ContentType;

                    byte[] octets = null;
                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        octets = ((Asn1OctetString)ci.Content).GetOctets();
                    }
                    else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        if (password != null)
                        {
                            EncryptedData d = EncryptedData.GetInstance(ci.Content);
                            octets = CryptPbeData(false, d.EncryptionAlgorithm,
                                                  password, wrongPkcs12Zero, d.Content.GetOctets());
                        }
                    }
                    else
                    {
                        // TODO Other data types
                    }

                    if (octets != null)
                    {
                        Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                certBags.Add(b);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(b.BagValue),
                                                        b.BagAttributes, password, wrongPkcs12Zero);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                LoadKeyBag(PrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes);
                            }
                            else
                            {
                                // TODO Other bag types
                            }
                        }
                    }
                }
            }

            certs.Clear();
            chainCerts.Clear();
            keyCerts.Clear();

            foreach (SafeBag b in certBags)
            {
                CertBag         certBag = new CertBag((Asn1Sequence)b.BagValue);
                byte[]          octets  = ((Asn1OctetString)certBag.CertValue).GetOctets();
                X509Certificate cert    = new X509CertificateParser().ReadCertificate(octets);

                //
                // set the attributes
                //
                IDictionary     attributes = Platform.CreateHashtable();
                Asn1OctetString localId    = null;
                string          alias      = null;

                if (b.BagAttributes != null)
                {
                    foreach (Asn1Sequence sq in b.BagAttributes)
                    {
                        DerObjectIdentifier aOid    = DerObjectIdentifier.GetInstance(sq[0]);
                        Asn1Set             attrSet = Asn1Set.GetInstance(sq[1]);

                        if (attrSet.Count > 0)
                        {
                            // TODO We should be adding all attributes in the set
                            Asn1Encodable attr = attrSet[0];

                            // TODO We might want to "merge" attribute sets with
                            // the same OID - currently, differing values give an error
                            if (attributes.Contains(aOid.Id))
                            {
                                // OK, but the value has to be the same
                                if (!attributes[aOid.Id].Equals(attr))
                                {
                                    throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                attributes.Add(aOid.Id, attr);
                            }

                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                alias = ((DerBmpString)attr).GetString();
                            }
                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                localId = (Asn1OctetString)attr;
                            }
                        }
                    }
                }

                CertId certId = new CertId(cert.GetPublicKey());
                X509CertificateEntry certEntry = new X509CertificateEntry(cert, attributes);

                chainCerts[certId] = certEntry;

                if (unmarkedKeyEntry != null)
                {
                    if (keyCerts.Count == 0)
                    {
                        string name = Hex.ToHexString(certId.Id);

                        keyCerts[name] = certEntry;
                        keys[name]     = unmarkedKeyEntry;
                    }
                }
                else
                {
                    if (localId != null)
                    {
                        string name = Hex.ToHexString(localId.GetOctets());

                        keyCerts[name] = certEntry;
                    }

                    if (alias != null)
                    {
                        // TODO There may have been more than one alias
                        certs[alias] = certEntry;
                    }
                }
            }
        }
Пример #13
0
        public KeyInfoX509Data(byte[] rgbCert)
        {
            var parser = new X509CertificateParser();

            AddCertificate(parser.ReadCertificate(rgbCert));
        }
Пример #14
0
        protected virtual PkixCertPathBuilderResult Build(
            X509Certificate tbvCert,
            PkixBuilderParameters pkixParams,
            IList tbvPath)
        {
            // If tbvCert is readily present in tbvPath, it indicates having run
            // into a cycle in the PKI graph.
            if (tbvPath.Contains(tbvCert))
            {
                return(null);
            }

            // step out, the certificate is not allowed to appear in a certification
            // chain.
            if (pkixParams.GetExcludedCerts().Contains(tbvCert))
            {
                return(null);
            }

            // test if certificate path exceeds maximum length
            if (pkixParams.MaxPathLength != -1)
            {
                if (tbvPath.Count - 1 > pkixParams.MaxPathLength)
                {
                    return(null);
                }
            }

            tbvPath.Add(tbvCert);

            X509CertificateParser     certParser    = new X509CertificateParser();
            PkixCertPathBuilderResult builderResult = null;
            PkixCertPathValidator     validator     = new PkixCertPathValidator();

            try
            {
                // check whether the issuer of <tbvCert> is a TrustAnchor
                if (PkixCertPathValidatorUtilities.FindTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()) != null)
                {
                    // exception message from possibly later tried certification
                    // chains
                    PkixCertPath certPath = null;
                    try
                    {
                        certPath = new PkixCertPath(tbvPath);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(
                                  "Certification path could not be constructed from certificate list.",
                                  e);
                    }

                    PkixCertPathValidatorResult result = null;
                    try
                    {
                        result = (PkixCertPathValidatorResult)validator.Validate(
                            certPath, pkixParams);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(
                                  "Certification path could not be validated.", e);
                    }

                    return(new PkixCertPathBuilderResult(certPath, result.TrustAnchor,
                                                         result.PolicyTree, result.SubjectPublicKey));
                }
                else
                {
                    // add additional X.509 stores from locations in certificate
                    try
                    {
                        PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames(
                            tbvCert, pkixParams);
                    }
                    catch (CertificateParsingException e)
                    {
                        throw new Exception(
                                  "No additiontal X.509 stores can be added from certificate locations.",
                                  e);
                    }

                    // try to get the issuer certificate from one of the stores
                    HashSet issuers = new HashSet();
                    try
                    {
                        issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams));
                    }
                    catch (Exception e)
                    {
                        throw new Exception(
                                  "Cannot find issuer certificate for certificate in certification path.",
                                  e);
                    }

                    if (issuers.IsEmpty)
                    {
                        throw new Exception("No issuer certificate for certificate in certification path found.");
                    }

                    foreach (X509Certificate issuer in issuers)
                    {
                        builderResult = Build(issuer, pkixParams, tbvPath);

                        if (builderResult != null)
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                certPathException = e;
            }

            if (builderResult == null)
            {
                tbvPath.Remove(tbvCert);
            }

            return(builderResult);
        }
Пример #15
0
        /// <summary>
        /// Firma un documento
        /// </summary>
        /// <param name="Source">Documento origen</param>
        /// <param name="Target">Documento destino</param>
        /// <param name="Certificate">Certificado a utilizar</param>
        /// <param name="Reason">Razón de la firma</param>
        /// <param name="Location">Ubicación</param>
        /// <param name="AddVisibleSign">Establece si hay que agregar la firma visible al documento</param>
        public void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, DatosPersonales datos)
        {
            X509CertificateParser objCP = new X509CertificateParser();

            Org.BouncyCastle.X509.X509Certificate[] objChain = new Org.BouncyCastle.X509.X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) };

            PdfReader              objReader  = new PdfReader(Source);
            PdfStamper             objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0', null, true);
            PdfSignatureAppearance objSA      = objStamper.SignatureAppearance;

            if (AddVisibleSign)
            {
                objSA.SetVisibleSignature(new Rectangle(100f, objReader.XrefSize, 500, 100), 1, null);
            }

            objSA.SignDate = DateTime.Now;
            objSA.SetCrypto(null, objChain, null, null);
            objSA.Reason      = Reason;
            objSA.Location    = Location;
            objSA.Acro6Layers = true;
            objSA.Render      = PdfSignatureAppearance.SignatureRender.NameAndDescription;
            PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);

            objSignature.Date = new PdfDate(objSA.SignDate);
            objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN");
            if (objSA.Reason != null)
            {
                objSignature.Reason = objSA.Reason;
            }
            if (objSA.Location != null)
            {
                objSignature.Location = objSA.Location;
            }
            objSA.CryptoDictionary = objSignature;
            int intCSize = 4000;


            //  Hashtable objTable = new Hashtable();
            //  objTable[PdfName.CONTENTS] = intCSize * 2 + 2;
            Dictionary <PdfName, int> objTable = new Dictionary <PdfName, int>();
            PdfName pdfname = new PdfName("firma");

            // Add some elements to the dictionary. There are no
            // duplicate keys, but some of the values are duplicates.
            objTable.Add(pdfname, intCSize * 2 + 2);
            objSA.PreClose(objTable);

            HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();

            Stream objStream = objSA.RangeStream;
            int    intRead   = 0;

            byte[] bytBuffer = new byte[8192];
            while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
            {
                objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
            }
            objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

            byte[] bytPK  = SignMsg(objSHA1.Hash, Certificate, false);
            byte[] bytOut = new byte[intCSize];

            PdfDictionary objDict = new PdfDictionary();

            Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

            objDict.Put(pdfname, new PdfString(bytOut).SetHexWriting(true));
            try
            {
                objSA.Close(objDict);
            }
            catch (Exception ex)
            {
            }
        }
Пример #16
0
        /**
         * Verifies a signature using the sub-filter adbe.pkcs7.detached or
         * adbe.pkcs7.sha1.
         * @param contentsKey the /Contents key
         * @param provider the provider or <code>null</code> for the default provider
         * @throws SecurityException on error
         * @throws CRLException on error
         * @throws InvalidKeyException on error
         * @throws CertificateException on error
         * @throws NoSuchProviderException on error
         * @throws NoSuchAlgorithmException on error
         */
        public PdfPKCS7(byte[] contentsKey)
        {
            ASN1InputStream din = new ASN1InputStream(new MemoryStream(contentsKey));

            //
            // Basic checks to make sure it's a PKCS#7 SignedData Object
            //
            ASN1Object pkcs;

            try {
                pkcs = din.readObject();
            }
            catch  {
                throw new ArgumentException("can't decode PKCS7SignedData object");
            }
            if (!(pkcs is ASN1Sequence))
            {
                throw new ArgumentException("Not a valid PKCS#7 object - not a sequence");
            }
            ASN1Sequence        signedData = (ASN1Sequence)pkcs;
            DERObjectIdentifier objId      = (DERObjectIdentifier)signedData.getObjectAt(0);

            if (!objId.getId().Equals(ID_PKCS7_SIGNED_DATA))
            {
                throw new ArgumentException("Not a valid PKCS#7 object - not signed data");
            }
            ASN1Sequence content = (ASN1Sequence)((DERTaggedObject)signedData.getObjectAt(1)).getObject();

            // the positions that we care are:
            //     0 - version
            //     1 - digestAlgorithms
            //     2 - possible ID_PKCS7_DATA
            //     (the certificates and crls are taken out by other means)
            //     last - signerInfos

            // the version
            version = ((DERInteger)content.getObjectAt(0)).getValue().intValue();

            // the digestAlgorithms
            digestalgos = new Hashtable();
            IEnumerator e = ((ASN1Set)content.getObjectAt(1)).getObjects();

            while (e.MoveNext())
            {
                ASN1Sequence        s = (ASN1Sequence)e.Current;
                DERObjectIdentifier o = (DERObjectIdentifier)s.getObjectAt(0);
                digestalgos[o.getId()] = null;
            }

            // the certificates and crls
            X509CertificateParser cf = new X509CertificateParser(contentsKey);

            certs = new ArrayList();
            while (true)
            {
                X509Certificate cc = cf.ReadCertificate();
                if (cc == null)
                {
                    break;
                }
                certs.Add(cc);
            }
            crls = new ArrayList();

            // the possible ID_PKCS7_DATA
            ASN1Sequence rsaData = (ASN1Sequence)content.getObjectAt(2);

            if (rsaData.size() > 1)
            {
                DEROctetString rsaDataContent = (DEROctetString)((DERTaggedObject)rsaData.getObjectAt(1)).getObject();
                RSAdata = rsaDataContent.getOctets();
            }

            // the signerInfos
            int next = 3;

            while (content.getObjectAt(next) is DERTaggedObject)
            {
                ++next;
            }
            ASN1Set signerInfos = (ASN1Set)content.getObjectAt(next);

            if (signerInfos.size() != 1)
            {
                throw new ArgumentException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time");
            }
            ASN1Sequence signerInfo = (ASN1Sequence)signerInfos.getObjectAt(0);

            // the positions that we care are
            //     0 - version
            //     1 - the signing certificate serial number
            //     2 - the digest algorithm
            //     3 or 4 - digestEncryptionAlgorithm
            //     4 or 5 - encryptedDigest
            signerversion = ((DERInteger)signerInfo.getObjectAt(0)).getValue().intValue();
            // Get the signing certificate
            ASN1Sequence issuerAndSerialNumber = (ASN1Sequence)signerInfo.getObjectAt(1);
            BigInteger   serialNumber          = ((DERInteger)issuerAndSerialNumber.getObjectAt(1)).getValue();

            foreach (X509Certificate cert in certs)
            {
                if (serialNumber.Equals(cert.getSerialNumber()))
                {
                    signCert = cert;
                    break;
                }
            }
            if (signCert == null)
            {
                throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16));
            }
            digestAlgorithm = ((DERObjectIdentifier)((ASN1Sequence)signerInfo.getObjectAt(2)).getObjectAt(0)).getId();
            next            = 3;
            if (signerInfo.getObjectAt(next) is ASN1TaggedObject)
            {
                ASN1TaggedObject tagsig = (ASN1TaggedObject)signerInfo.getObjectAt(next);
                ASN1Sequence     sseq   = (ASN1Sequence)tagsig.getObject();
                MemoryStream     bOut   = new MemoryStream();
                ASN1OutputStream dout   = new ASN1OutputStream(bOut);
                try {
                    ASN1EncodableVector attribute = new ASN1EncodableVector();
                    for (int k = 0; k < sseq.size(); ++k)
                    {
                        attribute.add(sseq.getObjectAt(k));
                    }
                    dout.writeObject(new DERSet(attribute));
                    dout.Close();
                }
                catch (IOException) {}
                sigAttr = bOut.ToArray();

                for (int k = 0; k < sseq.size(); ++k)
                {
                    ASN1Sequence seq2 = (ASN1Sequence)sseq.getObjectAt(k);
                    if (((DERObjectIdentifier)seq2.getObjectAt(0)).getId().Equals(ID_MESSAGE_DIGEST))
                    {
                        ASN1Set sset = (ASN1Set)seq2.getObjectAt(1);
                        digestAttr = ((DEROctetString)sset.getObjectAt(0)).getOctets();
                        break;
                    }
                }
                if (digestAttr == null)
                {
                    throw new ArgumentException("Authenticated attribute is missing the digest.");
                }
                ++next;
            }
            digestEncryptionAlgorithm = ((DERObjectIdentifier)((ASN1Sequence)signerInfo.getObjectAt(next++)).getObjectAt(0)).getId();
            digest = ((DEROctetString)signerInfo.getObjectAt(next)).getOctets();
            if (RSAdata != null || digestAttr != null)
            {
                messageDigest = GetHashClass();
            }
            sig = SignerUtil.getSigner(GetDigestAlgorithm());
            sig.init(false, signCert.getPublicKey());
        }
Пример #17
0
        public bool FirmarPDF(string pdfOriginal, string pdfFirmado, SysX509.X509Certificate2 certificado, string imagenFirma, bool firmaVisible, float puntoEsquinaInferiorIzquierdaX, float puntoEsquinaInferiorIzquierdaY, float puntoEsquinaSuperiorDerechaX, float puntoEsquinaSuperiorDerechaY, eTipoPagina paginaFirma, int pagina)
        {
            int numPagina = 0;

            try
            {
                X509CertificateParser objCP = new X509CertificateParser();
                Org.BouncyCastle.X509.X509Certificate[] objChain = new Org.BouncyCastle.X509.X509Certificate[] { objCP.ReadCertificate(certificado.RawData) };

                PdfReader              objReader  = new PdfReader(pdfOriginal);
                PdfStamper             objStamper = PdfStamper.CreateSignature(objReader, new FileStream(pdfFirmado, FileMode.Create), '\0');
                PdfSignatureAppearance objSA      = objStamper.SignatureAppearance;

                if (paginaFirma == eTipoPagina.Ultima)
                {
                    numPagina = objReader.NumberOfPages;
                }
                else
                {
                    if (pagina <= objReader.NumberOfPages)
                    {
                        numPagina = pagina;
                    }
                    else if (pagina > objReader.NumberOfPages)
                    {
                        numPagina = objReader.NumberOfPages;
                    }
                    else if (pagina < 1)
                    {
                        numPagina = 1;
                    }
                }
                if (firmaVisible)
                {
                    Rectangle rect = new Rectangle(puntoEsquinaInferiorIzquierdaX, puntoEsquinaInferiorIzquierdaY, puntoEsquinaSuperiorDerechaX, puntoEsquinaSuperiorDerechaY);
                    objSA.SetVisibleSignature(rect, numPagina, null);
                }


                objSA.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED;

                objSA.SignDate = DateTime.Now;
                objSA.SetCrypto(null, objChain, null, null);
                objSA.Acro6Layers = true;
                objSA.Render      = PdfSignatureAppearance.SignatureRender.NameAndDescription;
                //objSA.SignatureGraphic = iTextSharp.text.Image.GetInstance(imagenFirma); //
                PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
                objSignature.Date = new PdfDate(objSA.SignDate);
                objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN");
                if (objSA.Reason != null)
                {
                    objSignature.Reason = objSA.Reason;
                }
                if (objSA.Location != null)
                {
                    objSignature.Location = objSA.Location;
                }
                if (objSA.Contact != null)
                {
                    objSignature.Contact = objSA.Contact;
                }
                objSA.CryptoDictionary = objSignature;
                int intCSize = 4000;
                Dictionary <PdfName, int> objTable = new Dictionary <PdfName, int>();
                objTable[PdfName.CONTENTS] = intCSize * 2 + 2;
                objSA.PreClose(objTable);

                HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();

                Stream objStream = objSA.RangeStream;
                int    intRead   = 0;
                byte[] bytBuffer = new byte[8192];
                while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
                {
                    objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
                }
                objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

                byte[] bytPK  = GenerarFirmar(objSHA1.Hash, certificado, false);
                byte[] bytOut = new byte[intCSize];

                PdfDictionary objDict = new PdfDictionary();

                Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

                objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true));
                objSA.Close(objDict);

                return(true);
            }
            catch
            {
                throw;
            }
        }
Пример #18
0
        public X509CertificateBC(Stream stream)
        {
            var parser = new X509CertificateParser();

            m_Certificate = parser.ReadCertificate(stream);
        }
Пример #19
0
            void Parse(Certificate cert)
            {
                var certParser = new X509CertificateParser();

                x509 = certParser.ReadCertificate(cert.data);
            }
Пример #20
0
        private static X509Certificate GetBankCertificate(byte[] rawCertificate)
        {
            var parser = new X509CertificateParser();

            return(parser.ReadCertificate(rawCertificate));
        }
Пример #21
0
        static void signPDF(string document)
        {
            //string certificate_dn = "C=RU, S=lenobl, L=spb, O=fil, OU=IT, CN=iks, E=iks@iks";  // Subject->Name

            string certificate_dn = "L=Санкт-Петербург, O=ООО Филберт, CN=iks, [email protected]";



            X509Store store = new X509Store("My", StoreLocation.CurrentUser);

            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
            X509Certificate2Collection found = store.Certificates.Find(
                X509FindType.FindBySubjectDistinguishedName, certificate_dn, true);


            if (found.Count == 0)
            {
                Console.Out.Write("Сертфикат [" + certificate_dn + "] не найден ");
                return;
            }

            if (found.Count > 1)
            {
                Console.WriteLine("Найдено более одного секретного ключа.");
                return;
            }



            X509Certificate2 certificate = found[0];

            CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider cert_key = certificate.PrivateKey as CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider;


            var cspParameters = new CspParameters();

            //копируем параметры csp из исходного контекста сертификата
            cspParameters.KeyContainerName = cert_key.CspKeyContainerInfo.KeyContainerName;
            cspParameters.ProviderType     = cert_key.CspKeyContainerInfo.ProviderType;
            cspParameters.ProviderName     = cert_key.CspKeyContainerInfo.ProviderName;
            cspParameters.Flags            = cert_key.CspKeyContainerInfo.MachineKeyStore
                              ? (CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore)
                              : (CspProviderFlags.UseExistingKey);
            cspParameters.KeyPassword = new SecureString();
            string pass = "******";

            foreach (var c in pass)
            {
                cspParameters.KeyPassword.AppendChar(c);
            }
            //создаем новый контекст сертификат, поскольку исходный открыт readonly
            certificate = new X509Certificate2(certificate.RawData);
            //задаем криптопровайдер с установленным паролем
            certificate.PrivateKey = new CryptoPro.Sharpei.Gost3410_2012_256CryptoServiceProvider(cspParameters);


            /////////////////////////читаем файл

            /*
             *          System.IO.StreamReader file = new System.IO.StreamReader("C:\\TEMP\\test.json");
             *
             *          string s = file.ReadToEnd();
             *                byte[] body = Encoding.Default.GetBytes(s);
             */


            /////////////////////////////   PDF  подпись ////////////////////////////////////////////////

            PdfReader reader = new PdfReader(document);


            string newSigned = Path.Combine(Path.GetDirectoryName(document) + @"\" + Path.GetFileNameWithoutExtension(document) + "_signed" + Path.GetExtension(document));

            FileStream             signedPDF = new FileStream(newSigned, FileMode.Create, FileAccess.ReadWrite);
            PdfStamper             st        = PdfStamper.CreateSignature(reader, signedPDF, '\0', null, true);
            PdfSignatureAppearance sap       = st.SignatureAppearance;



            // Загружаем сертификат в объект iTextSharp
            X509CertificateParser parser = new X509CertificateParser();

            Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] {
                parser.ReadCertificate(certificate.RawData)
            };

            sap.Certificate = parser.ReadCertificate(certificate.RawData);
            sap.Reason      = "I like to sign";
            sap.Location    = "Universe";
            sap.Acro6Layers = true;

            //sap.Render = PdfSignatureAppearance.SignatureRender.NameAndDescription;
            sap.SignDate = DateTime.Now;

            // Выбираем подходящий тип фильтра
            PdfName filterName = new PdfName("CryptoPro PDF");

            // Создаем подпись
            PdfSignature dic = new PdfSignature(filterName, PdfName.ADBE_PKCS7_DETACHED);

            dic.Date = new PdfDate(sap.SignDate);
            dic.Name = "iks";
            if (sap.Reason != null)
            {
                dic.Reason = sap.Reason;
            }
            if (sap.Location != null)
            {
                dic.Location = sap.Location;
            }
            sap.CryptoDictionary = dic;

            int intCSize = 4000;
            Dictionary <PdfName, int> hashtable = new Dictionary <PdfName, int>();

            hashtable[PdfName.CONTENTS] = intCSize * 2 + 2;
            sap.PreClose(hashtable);
            Stream       s    = sap.GetRangeStream();
            MemoryStream ss   = new MemoryStream();
            int          read = 0;

            byte[] buff = new byte[8192];
            while ((read = s.Read(buff, 0, 8192)) > 0)
            {
                ss.Write(buff, 0, read);
            }



            //////////////////////////////////////////



            // Вычисляем подпись
            ContentInfo contentInfo = new ContentInfo(ss.ToArray());
            SignedCms   signedCms   = new SignedCms(contentInfo, true);
            CmsSigner   cmsSigner   = new CmsSigner(certificate);

            signedCms.ComputeSignature(cmsSigner, false);
            byte[] pk = signedCms.Encode();


            /*
             * // Помещаем подпись в документ
             * byte[] outc = new byte[intCSize];
             * PdfDictionary dic2 = new PdfDictionary();
             * Array.Copy(pk, 0, outc, 0, pk.Length);
             * dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
             * sap.Close(dic2);
             */


            Console.WriteLine(string.Format("Документ {0} успешно подписан на ключе {1} => {2}.",
                                            document, certificate.Subject, newSigned));

            /*
             * System.IO.StreamWriter sw = null;
             * System.IO.FileStream fs = new System.IO.FileStream("C:\\TEMP\\test_json_signed.json", System.IO.FileMode.Append, System.IO.FileAccess.Write);
             *
             *
             * sw = new System.IO.StreamWriter(fs, Encoding.GetEncoding(1251));
             * sw.WriteLine(Encoding.Default.GetString(pk));
             * sw.Close();
             *
             * fs.Dispose();
             * fs.Close();
             */


            // Помещаем подпись в документ
            byte[]        outc = new byte[intCSize];
            PdfDictionary dic2 = new PdfDictionary();

            Array.Copy(pk, 0, outc, 0, pk.Length);
            dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
            sap.Close(dic2);



            /////////////////////////////////////////////////////////////////////////////
        }
Пример #22
0
        public static void SignHashed(MemoryStream Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, Image img, int nroHojaFirma, string path, float h, string att_1, string att_2, string att_3, string url_terminos)
        {
            try
            {
                X509CertificateParser objCP             = new X509CertificateParser();
                X509Certificate[]     objChain          = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) };
                IExternalSignature    externalSignature = new X509Certificate2Signature(Certificate, "SHA-1");

                PdfReader objReader = new PdfReader(Source);

                //string[] msg = Certificate.SubjectName.Name.Split(',');

                //Document document = new Document(PageSize.A4, 50, 50, 150, 100);
                //PdfWriter pdfwritter = PdfWriter.GetInstance(document, new FileStream("C:\\Users\\Public\\terminos_condiciones.pdf", FileMode.OpenOrCreate));

                using (PdfReader readerTerm = new PdfReader(url_terminos))
                    using (MemoryStream workStream = new MemoryStream())
                    {
                        PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.OpenOrCreate, FileAccess.Write), '\0');

                        int       nroPages  = objReader.NumberOfPages + 1;
                        Rectangle rectangle = readerTerm.GetPageSize(1);
                        objStamper.InsertPage(nroPages, rectangle);

                        PdfImportedPage bg = objStamper.GetImportedPage(readerTerm, 1);
                        objStamper.GetUnderContent(nroPages).AddTemplate(bg, 0, 0);

                        PdfSignatureAppearance objSA = objStamper.SignatureAppearance;

                        img.ScaleAbsolute(120f, 60f);
                        img.SetAbsolutePosition(0, 28);
                        BaseFont bf     = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
                        BaseFont bfBold = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, false);

                        if (true)
                        {
                            objSA.SetVisibleSignature(new Rectangle(50, h - 120, 200, h), nroHojaFirma, "Firma Digital emitida por el sistema BV Digital");
                        }

                        PdfTemplate n2Layer = objSA.GetLayer(2);
                        n2Layer.BeginText();
                        n2Layer.SetFontAndSize(bfBold, 7);
                        n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Inspectorate Services Perú S.A.C", 0, 100, 0);
                        n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "A Bureau Veritas Group Company", 0, 90, 0);

                        n2Layer.EndText();

                        n2Layer.AddImage(img);
                        n2Layer.BeginText();
                        n2Layer.SetFontAndSize(bf, 7);
                        n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Firmado Digitalmente por", 0, 40, 0);
                        //string user = msg[2].Substring(msg[2].IndexOf('=') + 1);
                        //user += " " + msg[3].Substring(msg[3].IndexOf('=') + 1);
                        n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_3, 0, 30, 0);
                        n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Fecha: " + objSA.SignDate.ToString(), 0, 20, 0);
                        n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_1, 0, 10, 0);
                        n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_2, 0, 0, 0);
                        n2Layer.EndText();
                        objSA.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
                        MakeSignature.SignDetached(objSA, externalSignature, objChain, null, null, null, 0, CryptoStandard.CMS);
                        objStamper.SetFullCompression();
                    }
            }
            catch (Exception e)
            {
                Utility.log_err.save(null, e);
            }
        }
Пример #23
0
    /// <summary>
    /// Revoke the CA signed certificate.
    /// The issuer CA public key, the private key and the crl reside in the storepath.
    /// The CRL number is increased by one and existing CRL for the issuer are deleted from the store.
    /// </summary>
    public static async Task <X509CRL> RevokeCertificateAsync(
        string storePath,
        X509Certificate2 certificate,
        string issuerKeyFilePassword = null
        )
    {
        X509CRL updatedCRL = null;

        try
        {
            string subjectName  = certificate.IssuerName.Name;
            string keyId        = null;
            string serialNumber = null;

            // caller may want to create empty CRL using the CA cert itself
            bool isCACert = IsCertificateAuthority(certificate);

            // find the authority key identifier.
            X509AuthorityKeyIdentifierExtension authority = FindAuthorityKeyIdentifier(certificate);

            if (authority != null)
            {
                keyId        = authority.KeyId;
                serialNumber = authority.SerialNumber;
            }
            else
            {
                throw new ArgumentException("Certificate does not contain an Authority Key");
            }

            if (!isCACert)
            {
                if (serialNumber == certificate.SerialNumber ||
                    Utils.CompareDistinguishedName(certificate.Subject, certificate.Issuer))
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Cannot revoke self signed certificates");
                }
            }

            X509Certificate2 certCA = null;
            using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(storePath))
            {
                if (store == null)
                {
                    throw new ArgumentException("Invalid store path/type");
                }
                certCA = await FindIssuerCABySerialNumberAsync(store, certificate.Issuer, serialNumber);

                if (certCA == null)
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Cannot find issuer certificate in store.");
                }

                if (!certCA.HasPrivateKey)
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Issuer certificate has no private key, cannot revoke certificate.");
                }

                CertificateIdentifier certCAIdentifier = new CertificateIdentifier(certCA);
                certCAIdentifier.StorePath = storePath;
                certCAIdentifier.StoreType = CertificateStoreIdentifier.DetermineStoreType(storePath);
                X509Certificate2 certCAWithPrivateKey = await certCAIdentifier.LoadPrivateKey(issuerKeyFilePassword);

                if (certCAWithPrivateKey == null)
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Failed to load issuer private key. Is the password correct?");
                }

                List <X509CRL> certCACrl = store.EnumerateCRLs(certCA, false);

                using (var cfrg = new CertificateFactoryRandomGenerator())
                {
                    // cert generators
                    SecureRandom random          = new SecureRandom(cfrg);
                    BigInteger   crlSerialNumber = BigInteger.Zero;

                    Org.BouncyCastle.X509.X509Certificate bcCertCA = new X509CertificateParser().ReadCertificate(certCA.RawData);
                    AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(certCAWithPrivateKey);

                    ISignatureFactory signatureFactory =
                        new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random);

                    X509V2CrlGenerator crlGen = new X509V2CrlGenerator();
                    crlGen.SetIssuerDN(bcCertCA.IssuerDN);
                    crlGen.SetThisUpdate(DateTime.UtcNow);
                    crlGen.SetNextUpdate(DateTime.UtcNow.AddMonths(12));

                    // merge all existing revocation list
                    X509CrlParser parser = new X509CrlParser();
                    foreach (X509CRL caCrl in certCACrl)
                    {
                        X509Crl crl = parser.ReadCrl(caCrl.RawData);
                        crlGen.AddCrl(crl);
                        var crlVersion = GetCrlNumber(crl);
                        if (crlVersion.IntValue > crlSerialNumber.IntValue)
                        {
                            crlSerialNumber = crlVersion;
                        }
                    }

                    if (isCACert)
                    {
                        // add a dummy revoked cert
                        crlGen.AddCrlEntry(BigInteger.One, DateTime.UtcNow, CrlReason.Superseded);
                    }
                    else
                    {
                        // add the revoked cert
                        crlGen.AddCrlEntry(GetSerialNumber(certificate), DateTime.UtcNow, CrlReason.PrivilegeWithdrawn);
                    }

                    crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier,
                                        false,
                                        new AuthorityKeyIdentifierStructure(bcCertCA));

                    // set new serial number
                    crlSerialNumber = crlSerialNumber.Add(BigInteger.One);
                    crlGen.AddExtension(X509Extensions.CrlNumber,
                                        false,
                                        new CrlNumber(crlSerialNumber));

                    // generate updated CRL
                    X509Crl updatedCrl = crlGen.Generate(signatureFactory);

                    // add updated CRL to store
                    updatedCRL = new X509CRL(updatedCrl.GetEncoded());
                    store.AddCRL(updatedCRL);

                    // delete outdated CRLs from store
                    foreach (X509CRL caCrl in certCACrl)
                    {
                        store.DeleteCRL(caCrl);
                    }
                }
                store.Close();
            }
        }
        catch (Exception e)
        {
            throw e;
        }
        return(updatedCRL);
    }
Пример #24
0
        public List <Tuple <IObjectAttribute, ClassAttribute> > ImportCertificate(string fileName, byte[] fileContent)
        {
            IObjectAttributeFactory objectAttributeFactory = Pkcs11Admin.Instance.Factories.ObjectAttributeFactory;

            X509CertificateParser x509CertificateParser = new X509CertificateParser();
            X509Certificate       x509Certificate       = x509CertificateParser.ReadCertificate(fileContent);

            List <Tuple <IObjectAttribute, ClassAttribute> > objectAttributes = StringUtils.GetCreateDefaultAttributes(Pkcs11Admin.Instance.Config.CertificateAttributes, (ulong)CKC.CKC_X_509);

            for (int i = 0; i < objectAttributes.Count; i++)
            {
                IObjectAttribute objectAttribute = objectAttributes[i].Item1;
                ClassAttribute   classAttribute  = objectAttributes[i].Item2;

                if (objectAttribute.Type == (ulong)CKA.CKA_LABEL)
                {
                    string label = fileName;
                    Dictionary <string, List <string> > subject = Utils.ParseX509Name(x509Certificate.SubjectDN);
                    if (subject.ContainsKey(X509ObjectIdentifiers.CommonName.Id) && (subject[X509ObjectIdentifiers.CommonName.Id].Count > 0))
                    {
                        label = subject[X509ObjectIdentifiers.CommonName.Id][0];
                    }

                    objectAttributes[i] = new Tuple <IObjectAttribute, ClassAttribute>(objectAttributeFactory.Create(CKA.CKA_LABEL, label), classAttribute);
                }
                else if (objectAttribute.Type == (ulong)CKA.CKA_START_DATE)
                {
                    objectAttributes[i] = new Tuple <IObjectAttribute, ClassAttribute>(objectAttributeFactory.Create(CKA.CKA_START_DATE, x509Certificate.NotBefore), classAttribute);
                }
                else if (objectAttribute.Type == (ulong)CKA.CKA_END_DATE)
                {
                    objectAttributes[i] = new Tuple <IObjectAttribute, ClassAttribute>(objectAttributeFactory.Create(CKA.CKA_END_DATE, x509Certificate.NotAfter), classAttribute);
                }
                else if (objectAttribute.Type == (ulong)CKA.CKA_SUBJECT)
                {
                    objectAttributes[i] = new Tuple <IObjectAttribute, ClassAttribute>(objectAttributeFactory.Create(CKA.CKA_SUBJECT, x509Certificate.SubjectDN.GetDerEncoded()), classAttribute);
                }
                else if (objectAttribute.Type == (ulong)CKA.CKA_ID)
                {
                    byte[] thumbPrint = null;
                    using (SHA1Managed sha1Managed = new SHA1Managed())
                        thumbPrint = sha1Managed.ComputeHash(x509Certificate.GetEncoded());

                    objectAttributes[i] = new Tuple <IObjectAttribute, ClassAttribute>(objectAttributeFactory.Create(CKA.CKA_ID, thumbPrint), classAttribute);
                }
                else if (objectAttribute.Type == (ulong)CKA.CKA_ISSUER)
                {
                    objectAttributes[i] = new Tuple <IObjectAttribute, ClassAttribute>(objectAttributeFactory.Create(CKA.CKA_ISSUER, x509Certificate.IssuerDN.GetDerEncoded()), classAttribute);
                }
                else if (objectAttribute.Type == (ulong)CKA.CKA_SERIAL_NUMBER)
                {
                    objectAttributes[i] = new Tuple <IObjectAttribute, ClassAttribute>(objectAttributeFactory.Create(CKA.CKA_SERIAL_NUMBER, new DerInteger(x509Certificate.SerialNumber).GetDerEncoded()), classAttribute);
                }
                else if (objectAttribute.Type == (ulong)CKA.CKA_VALUE)
                {
                    objectAttributes[i] = new Tuple <IObjectAttribute, ClassAttribute>(objectAttributeFactory.Create(CKA.CKA_VALUE, x509Certificate.GetEncoded()), classAttribute);
                }
            }

            return(objectAttributes);
        }
Пример #25
0
        /// <summary>
        /// Generates pfx from client configuration
        /// </summary>
        /// <param name="config">Kubernetes Client Configuration</param>
        /// <returns>Generated Pfx Path</returns>
        public static X509Certificate2 GeneratePfx(KubernetesClientConfiguration config)
        {
            byte[] keyData  = null;
            byte[] certData = null;

            if (!string.IsNullOrWhiteSpace(config.ClientCertificateKeyData))
            {
                keyData = Convert.FromBase64String(config.ClientCertificateKeyData);
            }
            if (!string.IsNullOrWhiteSpace(config.ClientKeyFilePath))
            {
                keyData = File.ReadAllBytes(config.ClientKeyFilePath);
            }

            if (keyData == null)
            {
                throw new KubeConfigException("keyData is empty");
            }

            if (!string.IsNullOrWhiteSpace(config.ClientCertificateData))
            {
                certData = Convert.FromBase64String(config.ClientCertificateData);
            }
            if (!string.IsNullOrWhiteSpace(config.ClientCertificateFilePath))
            {
                certData = File.ReadAllBytes(config.ClientCertificateFilePath);
            }

            if (certData == null)
            {
                throw new KubeConfigException("certData is empty");
            }

            var cert = new X509CertificateParser().ReadCertificate(new MemoryStream(certData));

            // key usage is a bit string, zero-th bit is 'digitalSignature'
            // See https://www.alvestrand.no/objectid/2.5.29.15.html for more details.
            if (cert != null && cert.GetKeyUsage() != null && !cert.GetKeyUsage()[0])
            {
                throw new Exception(
                          "Client certificates must be marked for digital signing. " +
                          "See https://github.com/kubernetes-client/csharp/issues/319");
            }
            object obj;

            using (var reader = new StreamReader(new MemoryStream(keyData)))
            {
                obj = new PemReader(reader).ReadObject();
                var key = obj as AsymmetricCipherKeyPair;
                if (key != null)
                {
                    var cipherKey = key;
                    obj = cipherKey.Private;
                }
            }

            var keyParams = (AsymmetricKeyParameter)obj;

            var store = new Pkcs12StoreBuilder().Build();

            store.SetKeyEntry("K8SKEY", new AsymmetricKeyEntry(keyParams), new[] { new X509CertificateEntry(cert) });

            using (var pkcs = new MemoryStream())
            {
                store.Save(pkcs, new char[0], new SecureRandom());

                if (config.ClientCertificateKeyStoreFlags.HasValue)
                {
                    return(new X509Certificate2(pkcs.ToArray(), "", config.ClientCertificateKeyStoreFlags.Value));
                }
                else
                {
                    return(new X509Certificate2(pkcs.ToArray()));
                }
            }
        }
Пример #26
0
        internal static X509Certificate CloneCertificate(X509Certificate cert)
        {
            var parser = new X509CertificateParser();

            return(parser.ReadCertificate(cert.GetEncoded()));
        }
        public override async Task PairAsync(string ipAddress, TextBox outputTextBox)
        {
            // Create SHA256 hash digest. This is not supported by server version < 7
            // (need to use SHA1 for those cases) but that doesn't really matter right now.
            IDigest hashAlgorithm  = new Sha256Digest();
            int     hashDigestSize = hashAlgorithm.GetDigestSize();

            // Create and salt pin
            byte[] salt = this.GenerateRandomBytes(16);
            string pin  = GenerateRandomPin();

            byte[] saltAndPin = SaltPin(salt, pin);

            // Asymmetric key pair
            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(new KeyGenerationParameters(this.SecureRandom, 2048));
            AsymmetricCipherKeyPair keyPair = keyPairGenerator.GenerateKeyPair();

            // Certificate issuer and name
            X509Name name = new X509Name("CN=NVIDIA GameStream Client");

            // Certificate serial number
            byte[]     serialBytes = this.GenerateRandomBytes(8);
            BigInteger serial      = new BigInteger(serialBytes).Abs();

            // Expires in 20 years
            DateTime now        = DateTime.UtcNow;
            DateTime expiration = now.AddYears(20);

            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

            generator.SetSubjectDN(name);
            generator.SetIssuerDN(name);
            generator.SetSerialNumber(serial);
            generator.SetNotBefore(now);
            generator.SetNotAfter(expiration);
            generator.SetPublicKey(keyPair.Public);

            BouncyCastleX509Certificate certificate =
                generator.Generate(
                    new Asn1SignatureFactory("SHA1WithRSA", keyPair.Private));

            // Create PKCS12 certificate bytes.
            Pkcs12Store          store            = new Pkcs12Store();
            X509CertificateEntry certificateEntry = new X509CertificateEntry(certificate);
            string friendlyName = "Moonlight Xbox";
            string password     = "******";

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(
                friendlyName,
                new AsymmetricKeyEntry(keyPair.Private),
                new X509CertificateEntry[] { certificateEntry });
            string pfxData;

            using (MemoryStream memoryStream = new MemoryStream(512))
            {
                store.Save(memoryStream, password.ToCharArray(), this.SecureRandom);
                pfxData = CryptographicBuffer.EncodeToBase64String(memoryStream.ToArray().AsBuffer());
            }

            await CertificateEnrollmentManager.ImportPfxDataAsync(
                pfxData,
                password,
                ExportOption.NotExportable,
                KeyProtectionLevel.NoConsent,
                InstallOptions.DeleteExpired,
                friendlyName);

            // Read the UWP cert from the cert store
            Certificate uwpCertificate =
                (await CertificateStores.FindAllAsync(
                     new CertificateQuery {
                FriendlyName = friendlyName
            }))[0];

            string keyString;

            using (StringWriter keyWriter = new StringWriter())
            {
                PemWriter pemWriter = new PemWriter(keyWriter);
                pemWriter.WriteObject(keyPair);
                keyString = keyWriter.ToString();

                // Line endings must be UNIX style for GFE to accept the certificate.
                keyString = keyString.Replace(Environment.NewLine, "\n");
            }

            string certString;

            using (StringWriter certWriter = new StringWriter())
            {
                PemWriter pemWriter = new PemWriter(certWriter);
                pemWriter.WriteObject(certificate);
                certString = certWriter.ToString();

                // Line endings must be UNIX style for GFE to accept the certificate.
                certString = certString.Replace(Environment.NewLine, "\n");
            }

            byte[] pemCertBytes = Encoding.UTF8.GetBytes(certString);
            byte[] uniqueId     = GenerateRandomBytes(8);

            // Create the HTTP client.
            HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();

            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
            filter.ClientCertificate = uwpCertificate;

            HttpClient httpClient = new HttpClient(filter);

            // Unpair before doing anything else in this test app.
            string uriString =
                string.Format(
                    "http://{0}:47989/unpair?uniqueid={1}&uuid={2}",
                    ipAddress,
                    BytesToHex(uniqueId),
                    Guid.NewGuid().ToString("N"));

            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString)))
            {
                using (HttpResponseMessage response = await httpClient.SendRequestAsync(request))
                {
                    outputTextBox.Text = $"Unpair status code: {response.StatusCode}\n";
                    string responseContent = await response.Content.ReadAsStringAsync();

                    outputTextBox.Text += responseContent + "\n";
                }
            }

            await Task.Delay(2000);

            outputTextBox.Text = $"Enter pin: {pin}";

            // Get server certificate.
            // TODO: Call should have no timeout because it requires the user to enter a pin.
            PairResponse pairResponse = null;

            uriString =
                string.Format(
                    "http://{0}:47989/pair?uniqueid={1}&uuid={2}&devicename=roth&updateState=1&phrase=getservercert&salt={3}&clientcert={4}",
                    ipAddress,
                    BytesToHex(uniqueId),
                    Guid.NewGuid().ToString("N"),
                    BytesToHex(salt),
                    BytesToHex(pemCertBytes));
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString)))
            {
                using (HttpResponseMessage response = await httpClient.SendRequestAsync(request))
                {
                    outputTextBox.Text = $"Get server cert status code: {response.StatusCode}\n";
                    string responseContent = await response.Content.ReadAsStringAsync();

                    outputTextBox.Text += responseContent + "\n";
                    using (StringReader reader = new StringReader(responseContent))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(PairResponse));
                        pairResponse = serializer.Deserialize(new StringReader(responseContent)) as PairResponse;
                    }
                }
            }

            if (pairResponse == null || pairResponse.Paired != 1)
            {
                outputTextBox.Text += "Pairing failed.\n";
                return;
            }

            if (string.IsNullOrEmpty(pairResponse.PlainCert))
            {
                outputTextBox.Text += "Pairing already in progress.\n";
                return;
            }

            // Parse server certificate
            byte[] serverCertBytes = HexToBytes(pairResponse.PlainCert);
            BouncyCastleX509Certificate serverCertificate = new X509CertificateParser().ReadCertificate(serverCertBytes);

            // Hash the salt and pin and use it to generate an AES key.
            byte[]            hashedSaltAndPin = HashData(hashAlgorithm, saltAndPin);
            ICipherParameters aesKey           = GenerateCipherKey(hashedSaltAndPin);

            // Generate a random challenge and encrypt it using AES.
            byte[] challenge          = GenerateRandomBytes(16);
            byte[] encryptedChallenge = DoAesCipher(true, aesKey, challenge);

            await Task.Delay(2000);

            // Send the encrypted challenge to the server.
            // TODO: Call should have a timeout.
            uriString =
                string.Format(
                    "http://{0}:47989/pair?uniqueid={1}&uuid={2}&devicename=roth&updateState=1&clientchallenge={3}",
                    ipAddress,
                    BytesToHex(uniqueId),
                    Guid.NewGuid().ToString("N"),
                    BytesToHex(encryptedChallenge));
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString)))
            {
                using (HttpResponseMessage response = await httpClient.SendRequestAsync(request))
                {
                    outputTextBox.Text = $"Send challenge status code: {response.StatusCode}\n";
                    string responseContent = await response.Content.ReadAsStringAsync();

                    outputTextBox.Text += responseContent + "\n";
                    using (StringReader reader = new StringReader(responseContent))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(PairResponse));
                        pairResponse = serializer.Deserialize(new StringReader(responseContent)) as PairResponse;
                    }
                }
            }

            if (pairResponse == null || pairResponse.Paired != 1)
            {
                outputTextBox.Text += "Pairing failed.\n";
                return;
            }

            // Decode the server's response and subsequent challenge.
            byte[] encryptedServerChallengeResponse = HexToBytes(pairResponse.ChallengeResponse);
            byte[] decryptedServerChallengeResponse = DoAesCipher(false, aesKey, encryptedServerChallengeResponse);

            byte[] serverResponse  = new byte[hashDigestSize];
            byte[] serverChallenge = new byte[16];
            Array.Copy(decryptedServerChallengeResponse, serverResponse, hashDigestSize);
            Array.Copy(decryptedServerChallengeResponse, hashDigestSize, serverChallenge, 0, 16);

            // Using another 16 byte secret, compute a challenge response hash using the secret,
            // our certificate signature, and the challenge.
            byte[] clientSecret          = GenerateRandomBytes(16);
            byte[] challengeResponseHash =
                HashData(
                    hashAlgorithm,
                    ConcatenateByteArrays(serverChallenge, certificate.GetSignature(), clientSecret));
            byte[] encryptedChallengeResponse = DoAesCipher(true, aesKey, challengeResponseHash);

            await Task.Delay(2000);

            // Send the challenge response to the server.
            // TODO: Call should have a timeout.
            uriString =
                string.Format(
                    "http://{0}:47989/pair?uniqueid={1}&uuid={2}&devicename=roth&updateState=1&serverchallengeresp={3}",
                    ipAddress,
                    BytesToHex(uniqueId),
                    Guid.NewGuid().ToString("N"),
                    BytesToHex(encryptedChallengeResponse));
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString)))
            {
                using (HttpResponseMessage response = await httpClient.SendRequestAsync(request))
                {
                    outputTextBox.Text = $"Send challenge response status code: {response.StatusCode}\n";
                    string responseContent = await response.Content.ReadAsStringAsync();

                    outputTextBox.Text += responseContent + "\n";
                    using (StringReader reader = new StringReader(responseContent))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(PairResponse));
                        pairResponse = serializer.Deserialize(new StringReader(responseContent)) as PairResponse;
                    }
                }
            }

            if (pairResponse == null || pairResponse.Paired != 1)
            {
                outputTextBox.Text += "Pairing failed.\n";
                // TODO: Unpair here by calling http://<blah>/unpair?uniqueid={1}&uuid={2}.
                return;
            }

            // Get the server's signed secret.
            byte[] serverSecretResponse = HexToBytes(pairResponse.PairingSecret);
            byte[] serverSecret         = new byte[16];
            byte[] serverSignature      = new byte[256];
            Array.Copy(serverSecretResponse, serverSecret, serverSecret.Length);
            Array.Copy(serverSecretResponse, serverSecret.Length, serverSignature, 0, serverSignature.Length);

            if (!VerifySignature(serverSecret, serverSignature, serverCertificate.GetPublicKey()))
            {
                outputTextBox.Text += "Pairing failed.\n";
                // TODO: Unpair as above.
                return;
            }

            // Ensure the server challenge matched what we expected (the PIN was correct).
            byte[] serverChallengeResponseHash =
                HashData(
                    hashAlgorithm,
                    ConcatenateByteArrays(
                        challenge,
                        serverCertificate.GetSignature(),
                        serverSecret));
            if (!serverChallengeResponseHash.SequenceEqual(serverResponse))
            {
                outputTextBox.Text += "Pairing failed due to wrong pin.\n";
                // TODO: Unpair as above.
                return;
            }

            await Task.Delay(2000);

            // Send the server our signed secret
            // TODO: Call should have a timeout.
            byte[] signedSecret        = SignData(clientSecret, keyPair.Private);
            byte[] clientPairingSecret =
                ConcatenateByteArrays(
                    clientSecret,
                    signedSecret);
            uriString =
                string.Format(
                    "http://{0}:47989/pair?uniqueid={1}&uuid={2}&devicename=roth&updateState=1&clientpairingsecret={3}",
                    ipAddress,
                    BytesToHex(uniqueId),
                    Guid.NewGuid().ToString("N"),
                    BytesToHex(clientPairingSecret));
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString)))
            {
                using (HttpResponseMessage response = await httpClient.SendRequestAsync(request))
                {
                    outputTextBox.Text = $"Send client pairing secret status code: {response.StatusCode}\n";
                    string responseContent = await response.Content.ReadAsStringAsync();

                    outputTextBox.Text += responseContent + "\n";
                    using (StringReader reader = new StringReader(responseContent))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(PairResponse));
                        pairResponse = serializer.Deserialize(new StringReader(responseContent)) as PairResponse;
                    }
                }
            }

            if (pairResponse == null || pairResponse.Paired != 1)
            {
                outputTextBox.Text += "Pairing failed.\n";
                // TODO: Unpair as above.
                return;
            }

            await Task.Delay(2000);

            // Do the initial challenge (seems neccessary for us to show as paired).
            // TODO: Call should have a timeout.
            uriString =
                string.Format(
                    "https://{0}:47984/pair?uniqueid={1}&uuid={2}&devicename=roth&updateState=1&phrase=pairchallenge",
                    ipAddress,
                    BytesToHex(uniqueId),
                    Guid.NewGuid().ToString("N"));
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(uriString)))
            {
                using (HttpResponseMessage response = await httpClient.SendRequestAsync(request))
                {
                    outputTextBox.Text = $"Send pair challenge status code: {response.StatusCode}\n";
                    string responseContent = await response.Content.ReadAsStringAsync();

                    outputTextBox.Text += responseContent + "\n";
                    using (StringReader reader = new StringReader(responseContent))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(PairResponse));
                        pairResponse = serializer.Deserialize(new StringReader(responseContent)) as PairResponse;
                    }
                }
            }

            if (pairResponse == null || pairResponse.Paired != 1)
            {
                outputTextBox.Text += "Pairing failed.\n";
                // TODO: Unpair as above.
                return;
            }

            await Task.Delay(2000);

            outputTextBox.Text = "Pairing succeeded!\n";
        }
Пример #28
0
        public static bool certificateValid(string certificateLocation)
        {
            FileStream            fs         = new FileStream(certificateLocation, FileMode.Open);
            X509CertificateParser certParser = new X509CertificateParser();

            X509Certificate userCertificate = certParser.ReadCertificate(fs);

            fs.Close();

            string CA  = Application.Current.Properties["CA"].ToString();
            string CRL = Application.Current.Properties["CRL"].ToString();

            fs = new FileStream(CA, FileMode.Open);
            X509Certificate CACertificate = certParser.ReadCertificate(fs);

            fs.Close();


            X509CrlParser crlParser = new X509CrlParser();

            fs = new FileStream(CRL, FileMode.Open);
            X509Crl CRLCertificate = crlParser.ReadCrl(fs);

            fs.Close();

            //verify that the certificate is signed by the CA
            try
            {
                userCertificate.Verify(CACertificate.GetPublicKey());
            }
            catch (GeneralSecurityException)
            {
                MessageBox.Show("Your certificate is not signed by an authorized CA");
                return(false);
            }

            //verify that the crl is signed by the CA
            try
            {
                CRLCertificate.Verify(CACertificate.GetPublicKey());
            }
            catch (GeneralSecurityException)
            {
                MessageBox.Show("Your CRL is not signed by an authorized CA");
                return(false);
            }

            //verify that the certificate is not revoked
            if (CRLCertificate.IsRevoked(userCertificate))
            {
                MessageBox.Show("Your certificate has been revoked");
                return(false);
            }

            //verify the certificate time validity
            if (!userCertificate.IsValidNow)
            {
                MessageBox.Show("Your certificate is not valid");
                return(false);
            }
            return(true);
        }
Пример #29
0
        /// <summary>
        /// Generates pfx from client configuration
        /// </summary>
        /// <param name="config">Kubernetes Client Configuration</param>
        /// <returns>Generated Pfx Path</returns>
        public static X509Certificate2 GeneratePfx(KubernetesClientConfiguration config)
        {
            byte[] keyData  = null;
            byte[] certData = null;

            if (!string.IsNullOrWhiteSpace(config.ClientCertificateKeyData))
            {
                keyData = Convert.FromBase64String(config.ClientCertificateKeyData);
            }
            if (!string.IsNullOrWhiteSpace(config.ClientKeyFilePath))
            {
                keyData = File.ReadAllBytes(config.ClientKeyFilePath);
            }

            if (keyData == null)
            {
                throw new KubeConfigException("keyData is empty");
            }

            if (!string.IsNullOrWhiteSpace(config.ClientCertificateData))
            {
                certData = Convert.FromBase64String(config.ClientCertificateData);
            }
            if (!string.IsNullOrWhiteSpace(config.ClientCertificateFilePath))
            {
                certData = File.ReadAllBytes(config.ClientCertificateFilePath);
            }

            if (certData == null)
            {
                throw new KubeConfigException("certData is empty");
            }

            var cert = new X509CertificateParser().ReadCertificate(new MemoryStream(certData));

            object obj;

            using (var reader = new StreamReader(new MemoryStream(keyData)))
            {
                obj = new PemReader(reader).ReadObject();
                var key = obj as AsymmetricCipherKeyPair;
                if (key != null)
                {
                    var cipherKey = key;
                    obj = cipherKey.Private;
                }
            }

            var rsaKeyParams = (RsaPrivateCrtKeyParameters)obj;

            var store = new Pkcs12StoreBuilder().Build();

            store.SetKeyEntry("K8SKEY", new AsymmetricKeyEntry(rsaKeyParams), new[] { new X509CertificateEntry(cert) });

            using (var pkcs = new MemoryStream())
            {
                store.Save(pkcs, new char[0], new SecureRandom());

                if (config.ClientCertificateKeyStoreFlags.HasValue)
                {
                    return(new X509Certificate2(pkcs.ToArray(), "", config.ClientCertificateKeyStoreFlags.Value));
                }
                else
                {
                    return(new X509Certificate2(pkcs.ToArray()));
                }
            }
        }
Пример #30
0
        /**
         * Creates a CertPath of the specified type.
         * This constructor is protected because most users should use
         * a CertificateFactory to create CertPaths.
         *
         * @param type the standard name of the type of Certificatesin this path
         **/
        public PkixCertPath(
            Stream inStream,
            String encoding)
//			: base("X.509")
        {
            try
            {
                if (encoding.ToUpper().Equals("PkiPath".ToUpper()))
                {
                    Asn1InputStream derInStream = new Asn1InputStream(inStream);
                    Asn1Object      derObject   = derInStream.ReadObject();
                    if (!(derObject is Asn1Sequence))
                    {
                        throw new CertificateException(
                                  "input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath");
                    }
                    IEnumerator     e = ((Asn1Sequence)derObject).GetEnumerator();
                    Stream          certInStream;
                    MemoryStream    outStream;
                    DerOutputStream derOutStream;
                    certificates = new ArrayList();

                    while (e.MoveNext())
                    {
                        outStream    = new MemoryStream();
                        derOutStream = new DerOutputStream(outStream);

                        derOutStream.WriteObject((Asn1Encodable)e.Current);
                        derOutStream.Close();

                        certInStream = new MemoryStream(outStream.ToArray(), false);
                        certificates.Insert(0, new X509CertificateParser().ReadCertificate(certInStream));
                    }
                }
                else if (encoding.ToUpper().Equals("PKCS7") ||
                         encoding.ToUpper().Equals("PEM"))
                {
                    inStream     = new BufferedStream(inStream);
                    certificates = new ArrayList();

                    X509CertificateParser certParser = new X509CertificateParser();
                    X509Certificate       cert       = null;

                    while ((cert = certParser.ReadCertificate(inStream)) != null)
                    {
                        certificates.Add(cert);
                    }
                }
                else
                {
                    throw new CertificateException("unsupported encoding: " + encoding);
                }
            }
            catch (IOException ex)
            {
                throw new CertificateException(
                          "IOException throw while decoding CertPath:\n"
                          + ex.ToString());
            }

            this.certificates = SortCerts(certificates);
        }