Beispiel #1
0
 private static X509Certificate GetPubKeyCert(string pubKeyCert)
 {
     try
     {
         pubKeyCert = pubKeyCert
                      .Replace("-----END CERTIFICATE-----", "")
                      .Replace("-----BEGIN CERTIFICATE-----", "");
         byte[] x509CertBytes           = Convert.FromBase64String(pubKeyCert);
         X509CertificateParser cf       = new X509CertificateParser();
         X509Certificate       x509Cert = cf.ReadCertificate(x509CertBytes);
         return(x509Cert);
     }
     catch
     {
         return(null);
     }
 }
        public static SigningCertificates GetSigningCertificates(IDigitalSignatureCertificateSelector certificateSelector)
        {
            SigningCertificates signingCertificates = new SigningCertificates();

            X509CertificateParser parser    = new X509CertificateParser();
            X509Store             x509Store = new X509Store(StoreLocation.CurrentUser);

            x509Store.Open(OpenFlags.ReadOnly);

            X509Certificate2Collection validCertificates = FindDigitalSignatureCertificates(x509Store);

            signingCertificates.X509Certificate2 = certificateSelector.SelectCertificate(validCertificates.Cast <X509Certificate2>());
            signingCertificates.X509Certificate  = parser.ReadCertificate(signingCertificates.X509Certificate2.Export(X509ContentType.Cert));
            signingCertificates.FinalChain       = CreateChain(signingCertificates.X509Certificate, signingCertificates.X509Certificate2, parser);

            return(signingCertificates);
        }
Beispiel #3
0
        /// <summary>
        /// Firma un documento PDF
        /// </summary>
        /// <param name="Source">Path del PDF a firmar</param>
        /// <param name="Target">Path del PDF firmado</param>
        /// <param name="Certificate">Certificado para realizar la firma</param>
        /// <param name="Reason">Motivo</param>
        /// <param name="Location">Ubicación</param>
        /// <param name="AddVisibleSign">Indica si la firma es visible dentro del documento</param>
        /// <param name="AddTimeStamp">Indica si se va a añadir sello de tiempo en el documento</param>
        /// <param name="strTSA">TSA del sello de tiempo</param>

        public static void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, bool AddTimeStamp, string strTSA)
        {
            X509CertificateParser objCP = new X509CertificateParser();

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

            //IList<ICrlClient> crlList = new List<ICrlClient>();
            //crlList.Add(new CrlClientOnline(objChain));

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

            // Creamos la apariencia
            PdfSignatureAppearance signatureAppearance = objStamper.SignatureAppearance;

            signatureAppearance.Reason   = Reason;
            signatureAppearance.Location = Location;

            // Si está la firma visible:
            if (AddVisibleSign)
            {
                signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 300, 200), 1, null); //signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 250, 150), objReader.NumberOfPages, "Signature");
            }
            ITSAClient  tsaClient  = null;
            IOcspClient ocspClient = null;

            // Si se ha añadido el sello de tiempo
            if (AddTimeStamp)
            {
                //  ocspClient = new OcspClientBouncyCastle();
                tsaClient = new TSAClientBouncyCastle(strTSA);
            }

            // Creating the signature
            //  IExternalSignature externalSignature = new X509Certificate2Signature(Certificate, "SHA-1");
            //  MakeSignature.SignDetached(signatureAppearance, externalSignature, objChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS);

            if (objReader != null)
            {
                objReader.Close();
            }
            if (objStamper != null)
            {
                objStamper.Close();
            }
        }
Beispiel #4
0
        public static void SerialDbAdd(string folder, string dbname)
        {
            string       CertSerial = String.Empty;
            StreamWriter w          = File.AppendText(dbname);

            foreach (string str in Directory.GetFiles(folder, "*.cer", SearchOption.AllDirectories))
            {
                X509CertificateParser parser = new X509CertificateParser();
                X509Certificate       cert   = parser.ReadCertificate(File.ReadAllBytes(str));
                CertSerial = "00" + cert.SerialNumber.ToString(16).ToUpper();
                w.WriteLine(CertSerial);
            }
            w.Close();

            Console.WriteLine("Информация успешно выгружена в файл: " + dbname);
            Console.ReadLine();
        }
Beispiel #5
0
        public async Task InstallAsync(string certResponse)
        {
            #region Bouncy castle PKCS #12 cert file generation
            var data = Convert.FromBase64String(certResponse);

            var parser = new X509CertificateParser();
            var cert   = parser.ReadCertificate(data);

            Pkcs12Store          store     = new Pkcs12StoreBuilder().Build();
            X509CertificateEntry certEntry = new X509CertificateEntry(cert);
            store.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias.

            AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(_privateKey);
            store.SetKeyEntry(cert.SubjectDN.ToString() + "_key", keyEntry, new X509CertificateEntry[] { certEntry }); //

            string pfx      = string.Empty;
            string password = "";
            using (MemoryStream ms = new MemoryStream())
            {
                store.Save(ms, password.ToCharArray(), _random);

                ms.Position = 0;
                await _storage.SetAsync("accessCert", ms.GetWindowsRuntimeBuffer());

                StreamReader streamReader = new StreamReader(ms);
                // Write to .PFX string
                byte[] arr = ms.ToArray();

                pfx = CryptographicBuffer.EncodeToBase64String(arr.AsBuffer());
            }
            #endregion
            await _storage.SetAsync(StorageKeyNames.PrivateKey, pfx);

            await CertificateEnrollmentManager.ImportPfxDataAsync(pfx, password, ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.None, "MAG_CERT");

            // Store the registered cert subject
            if (cert.SubjectDN != null)
            {
                var valueList = cert.SubjectDN.GetValueList(X509Name.CN);
                if (valueList.Count > 0)
                {
                    await _storage.SetAsync(StorageKeyNames.RegisteredCertSubject, (string)valueList[0]);
                }
            }
        }
Beispiel #6
0
        private static X509Certificate GetBankCertificate()
        {
            //base64 encoded bank (!) certificate
            //you can get it, when bank will "approve" your CMS request from API
            //so just copy paste bank certificate from API

            /*
             * "uuid": "....",
             * "active": true,
             * "cert": "-----BEGIN CERTIFICATE-----\r\nMIIEk....
             * remove all \r\n and comments and paste in bankCertificate.txt
             */
            var sbercert  = File.ReadAllText("bankCertificate.txt");
            var sberBytes = Convert.FromBase64String(sbercert);
            var parser    = new X509CertificateParser();

            return(parser.ReadCertificate(sberBytes));
        }
        private static List <X509Certificate> CreateChain(X509Certificate x509Certificate, X509Certificate2 x509Certificate2, X509CertificateParser parser)
        {
            X509Chain chain = new X509Chain(false);

            chain.Build(x509Certificate2);

            List <X509Certificate> finalChain = new List <X509Certificate>();

            foreach (var chainElement in chain.ChainElements)
            {
                chainElement.Certificate.Verify();
                finalChain.Add(parser.ReadCertificate(chainElement.Certificate.Export(X509ContentType.Cert)));
            }

            finalChain.Add(x509Certificate);

            return(finalChain);
        }
Beispiel #8
0
        private void importbutton_Click(object sender, EventArgs e)
        {
            OpenFileDialog opener = new OpenFileDialog();

            opener.InitialDirectory = Environment.CurrentDirectory;
            opener.Filter           = "公钥证书|*.cer|私钥证书|*.pfx";
            opener.RestoreDirectory = true;
            opener.FilterIndex      = 1;
            if (opener.ShowDialog() == DialogResult.OK)
            {
                var fname     = opener.FileName;
                var cerin     = File.OpenText(fname);
                var txtreader = cerin.ReadToEnd();
                if (Path.GetExtension(fname) == ".cer")
                {
                    certificate.Text = txtreader;
                    txtreader        = txtreader.Replace("-----BEGIN CERTIFICATE-----", "");
                    txtreader        = txtreader.Replace("-----END CERTIFICATE-----", "");
                    txtreader        = txtreader.Replace("\r\n", "");

                    var certb   = Convert.FromBase64String(txtreader);
                    var cholder = new X509CertificateParser();
                    bouncy = cholder.ReadCertificate(certb);
                    cert   = new System.Security.Cryptography.X509Certificates.X509Certificate2(certb);

                    nametxt.Text = bouncy.IssuerDN.ToString();

                    pubtxt.Text = Convert.ToBase64String(cert.GetPublicKey());
                    //Subtxt.Text = cert.Subject;
                }
                else if (Path.GetExtension(fname) == ".pfx")
                {
                    var pfxin  = File.ReadAllBytes(fname);
                    var store  = new Org.BouncyCastle.Pkcs.Pkcs12Store();
                    var stream = new MemoryStream(pfxin);
                    store.Load(stream, pswtxt.Text.ToCharArray());
                    foreach (string al in store.Aliases)
                    {
                        Castlekey = store.GetKey(al).Key;
                        Castle    = store.GetCertificate(al).Certificate;
                    }
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Constructor to be used to recover the existing RSA key pair and server
        /// signed certificate found on the local file system.
        /// </summary>
        /// <param name="passphrase">Passphrase for private key.</param>
        public RsaKeyPair(string passphrase)
        {
            if (!IsConfigured)
            {
                Configure();
            }

            if (File.Exists(_clientPrivateKeyPemFile) && File.Exists(_clientCertPemFile))
            {
                byte[] pkData = File.ReadAllBytes(_clientPrivateKeyPemFile);
                _pwd = passphrase.ToSecureString();
                AsymmetricCipherKeyPair keyPair = PemDecodeKeyPair(pkData);
                // Generate key info's
                PrivateKeyInfo       pkInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
                SubjectPublicKeyInfo info   =
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);

                _privateKey = new EncryptionKey(KeyType.RSAPrivate,
                                                Convert.ToBase64String(pkInfo.GetDerEncoded()).ToSecureString(),
                                                EncryptionParameters.KEY_GENERATION_START);

                _publicKey = new EncryptionKey(KeyType.RSAPublic,
                                               Convert.ToBase64String(info.GetDerEncoded()).ToSecureString(),
                                               EncryptionParameters.KEY_GENERATION_START);

                byte[] certData = File.ReadAllBytes(_clientCertPemFile);
                X509CertificateParser certParser = new X509CertificateParser();
                _certificate = certParser.ReadCertificate(certData);


                pkData   = null;
                certData = null;
                keyPair  = null;
                pkInfo   = null;
                info     = null;
                _pwd     = null;
                GC.Collect();
            }
            else
            {
                throw new Exception("Cannot find the PEM formatted certificate or private key file");
            }
        }
Beispiel #10
0
        public InfoCertificateResult Info(InfoCertificateCommand request)
        {
            X509CertificateParser parser = new X509CertificateParser();

            X509Certificate certificate = parser.ReadCertificate(Encoding.UTF8.GetBytes(request.Content));

            return(new InfoCertificateResult()
            {
                Issuer = certificate.IssuerDN.ToString(),
                Subject = certificate.SubjectDN.ToString(),
                SerialNumber = certificate.SerialNumber.ToString(),
                NotAfter = certificate.NotAfter,
                NotBefore = certificate.NotBefore,
                Algorithm = certificate.SigAlgName,
                Type = certificate.Version.ToString(),
                Expired = DateTime.Now > certificate.NotAfter,
                Revoged = false,
            });
        }
Beispiel #11
0
        public static void TestParser()
        {
            string pfxLocation = @"D:\lol\certificate.pfx";

            pfxLocation = @"D:\username\Desktop\DesktopArchiv\20180329_Desktop\CORMailService\CORMailService\CORMailService\CORMailService_TemporaryKey.pfx";



            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate =
                new System.Security.Cryptography.X509Certificates.X509Certificate2(pfxLocation);


            // Private Key
            if (!certificate.HasPrivateKey)
            {
                throw new System.IO.InvalidDataException("no private key in pfx file.");
            }

            System.Security.Cryptography.RSACng rsa = (System.Security.Cryptography.RSACng)certificate.PrivateKey;



            X509CertificateStore xs = new X509CertificateStore();

            xs.Import(pfxLocation);
            foreach (X509Certificate thisCert in xs.Certificates)
            {
                System.Console.WriteLine(thisCert);
                thisCert.GetPublicKey();

                // var signer = Org.BouncyCastle.Security.SignerUtilities.GetSigner(Sdk.SIGNATURE_ALGORITHM);
            }


            X509CertificateParser certParser = new X509CertificateParser();

            using (var fs = System.IO.File.OpenRead(pfxLocation))
            {
                certParser.ReadCertificate(fs);
            }

            System.Console.WriteLine(certParser);
        }
Beispiel #12
0
		/// <summary>
		/// Initialize a new instance of the <see cref="CmsRecipient"/> class.
		/// </summary>
		/// <remarks>
		/// <para>Creates a new <see cref="CmsRecipient"/>, loading the certificate from the specified stream.</para>
		/// <para>If the X.509 certificate contains an S/MIME capability extension, the initial value of the
		/// <see cref="EncryptionAlgorithms"/> property will be set to whatever encryption algorithms are
		/// defined by the S/MIME capability extension, otherwise int will be initialized to a list
		/// containing only the Triple-Des encryption algorithm which should be safe to assume for all
		/// modern S/MIME v3.x client implementations.</para>
		/// </remarks>
		/// <param name="stream">The stream containing the recipient's certificate.</param>
		/// <param name="recipientIdentifierType">The recipient identifier type.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="stream"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.FormatException">
		/// The specified file does not contain a certificate.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		public CmsRecipient (Stream stream, SubjectIdentifierType recipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber)
		{
			if (stream == null)
				throw new ArgumentNullException (nameof (stream));

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

			var parser = new X509CertificateParser ();

			Certificate = parser.ReadCertificate (stream);

			if (Certificate == null)
				throw new FormatException ();

			EncryptionAlgorithms = Certificate.GetEncryptionAlgorithms ();
		}
Beispiel #13
0
        /// <summary>
        /// Verifies the signature of a prevously signed PDF document using the specified public key
        /// </summary>
        /// <param name="pdfFile">a Previously signed pdf document</param>
        /// <param name="publicKeyStream">Public key to be used to verify the signature in .cer format</param>
        /// <exception cref="System.InvalidOperationException">Throw System.InvalidOperationException if the document is not signed or the signature could not be verified</exception>
        public static void VerifyPdfSignature(string pdfFile, Stream publicKeyStream)
        {
            var parser      = new X509CertificateParser();
            var certificate = parser.ReadCertificate(publicKeyStream);

            publicKeyStream.Dispose();

            PdfReader  reader = new PdfReader(pdfFile);
            AcroFields af     = reader.AcroFields;
            var        names  = af.GetSignatureNames();

            if (names.Count == 0)
            {
                throw new InvalidOperationException("No Signature present in pdf file.");
            }

            foreach (string name in names)
            {
                if (!af.SignatureCoversWholeDocument(name))
                {
                    throw new InvalidOperationException(string.Format("The signature: {0} does not covers the whole document.", name));
                }

                PdfPKCS7 pk  = af.VerifySignature(name);
                var      cal = pk.SignDate;
                var      pkc = pk.Certificates;

                if (!pk.Verify())
                {
                    throw new InvalidOperationException("The signature could not be verified.");
                }
                if (!pk.VerifyTimestampImprint())
                {
                    throw new InvalidOperationException("The signature timestamp could not be verified.");
                }

                var fails = CertificateVerification.VerifyCertificates(pkc, new[] { certificate }, null, cal);
                if (fails != null && fails.Any())
                {
                    throw new InvalidOperationException("The file is not signed using the specified key-pair.");
                }
            }
        }
        public static bool IsSignatureValid(byte[] message, byte[] signature, byte[] x509Cert)
        {
            X509CertificateParser parser = new X509CertificateParser();
            X509Certificate       cert   = parser.ReadCertificate(x509Cert);

            var data = CreateDatabaseInfoFromCertificate(cert);

            if (data == null || UpdateByValidTime(data))
            {
                return(false);
            }

            var signatureFunc = GetDigitalSignatureProvider(data.SignAlg_Cert.AlgParSet_SignAlg);
            var hashFunc      = GetHashFunctionProvider(data.SignAlg_Cert.AlgParSet_SignAlg);

            return(signatureFunc.IsSignatureValid(hashFunc.GetHash(message), signature, (PublicKeyFactory.CreateKey(data.SignAlg_Cert.PublicKey_SignAlg) as ECPublicKeyParameters)?.Q.XCoord.GetEncoded()
                                                  .Concat((PublicKeyFactory.CreateKey(data.SignAlg_Cert.PublicKey_SignAlg) as ECPublicKeyParameters)?.Q.YCoord.GetEncoded())
                                                  .ToArray()));
        }
Beispiel #15
0
        public static RawRegisterResponse FromBase64(String rawDataBase64)
        {
            byte[] bytes = Utils.Base64StringToByteArray(rawDataBase64);

            Stream stream       = new MemoryStream(bytes);
            var    binaryReader = new BinaryReader(stream);

            byte reservedByte = binaryReader.ReadByte();

            if (reservedByte != RegistrationReservedByteValue)
            {
                throw new U2fException(String.Format(
                                           "Incorrect value of reserved byte. Expected: {0}. Was: {1}",
                                           RegistrationReservedByteValue, reservedByte));
            }

            try
            {
                byte[] publicKey = binaryReader.ReadBytes(65);
                byte[] keyHandle = binaryReader.ReadBytes(binaryReader.ReadByte());
                X509CertificateParser x509CertificateParser = new X509CertificateParser();
                var x509Certificate = x509CertificateParser.ReadCertificate(stream);

                var rawRegisterResponse = new RawRegisterResponse(
                    publicKey,
                    keyHandle,
                    x509Certificate,
                    Utils.ReadAllBytes(binaryReader)
                    );

                return(rawRegisterResponse);
            }
            catch (CertificateException e)
            {
                throw new U2fException("Error when parsing attestation certificate", e);
            }
            finally
            {
                stream.Dispose();
                binaryReader.Dispose();
            }
        }
Beispiel #16
0
        public XadesObject GetXadesObject(XadesInfo xadesInfo, string signatureId)
        {
            var xadesObject = new XadesObject
            {
                QualifyingProperties = new QualifyingProperties
                {
                    Target           = $"#{signatureId}",
                    SignedProperties = new SignedProperties {
                        Id = $"{signatureId}-signedprops"
                    }
                }
            };

            var hashAlgorithm = GetHashAlgorithm();
            var hashValue     = hashAlgorithm.ComputeHash(xadesInfo.RawCertData);

            var x509CertificateParser = new X509CertificateParser();
            var bouncyCert            = x509CertificateParser.ReadCertificate(xadesInfo.RawCertData);

            var cert = new Cert
            {
                IssuerSerial = new IssuerSerial
                {
                    X509IssuerName   = bouncyCert.IssuerDN.ToX509IssuerName(),
                    X509SerialNumber = bouncyCert.SerialNumber.ToString()
                },
                CertDigest =
                {
                    DigestValue  = hashValue,
                    DigestMethod = new DigestMethod {
                        Algorithm = DigestMethod
                    }
                }
            };

            var signedSignatureProperties = xadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties;

            signedSignatureProperties.SigningCertificate.CertCollection.Add(cert);
            signedSignatureProperties.SigningTime = xadesInfo.SigningDateTimeUtc.ToDateTimeOffset(xadesInfo.TimeZoneOffsetMinutes);

            return(xadesObject);
        }
Beispiel #17
0
        private void AddCertsFromSet(IList certs, Asn1Set certSet)
        {
            X509CertificateParser x509CertificateParser = new X509CertificateParser();

            foreach (Asn1Encodable asn1Encodable in certSet)
            {
                try
                {
                    Asn1Object asn1Object = asn1Encodable.ToAsn1Object();
                    if (asn1Object is Asn1Sequence)
                    {
                        certs.Add(x509CertificateParser.ReadCertificate(asn1Object.GetEncoded()));
                    }
                }
                catch (Exception e)
                {
                    throw new CmsException("can't re-encode certificate!", e);
                }
            }
        }
        private static string Sign(string data)
        {
            var certBytes = File.ReadAllBytes("certificate.pfx");
            var cert      = new X509Certificate2(certBytes, ConvertToSecureString(Password));
            var bytes     = File.ReadAllBytes(@"private.key");

            var key           = new BigInteger(bytes);
            var keyParameters = new ECPrivateKeyParameters(KeyAlgorithm, key, PublicKeyParamSet);

            var signature = SignData(data, keyParameters);
            var parser    = new X509CertificateParser();
            var bcCert    = parser.ReadCertificate(cert.GetRawCertData());

            if (!VerifySignature(bcCert.GetPublicKey(), signature, data))
            {
                throw new Exception("sign error");
            }

            return(Convert.ToBase64String(signature));
        }
        private static PersonalCertificate CreateFromX509(X509Certificate certificate, CertificateStoreType certStoreType)
        {
            var parser = new X509CertificateParser();
            var read   = parser.ReadCertificate(certificate.GetRawCertData());

            var cert = new PersonalCertificate
            {
                Issuer          = certificate.Issuer,
                Thumbprint      = certificate.GetCertHashString(),
                Subject         = certificate.Subject,
                DigestAlgorithm = (read.SigAlgName.EndsWith("withRSA", StringComparison.OrdinalIgnoreCase) ? read.SigAlgName.Substring(0, read.SigAlgName.Length - "withRSA".Length) : read.SigAlgName).Replace("-", string.Empty),
                StoreType       = certStoreType
            };

            var list = read.SubjectDN.GetValueList();

            if (list?.Count > 0)
            {
                // ReSharper disable once PossibleNullReferenceException
                cert.DisplayName = list[^ 1].ToString();
Beispiel #20
0
        static void TestPDF(string path)
        {
            Console.WriteLine("processing PDF");
            AcroFields    acroFields = new PdfReader(path).AcroFields;
            List <string> names      = acroFields.GetSignatureNames();

            foreach (var name in names)
            {
                try {
                    Console.WriteLine(name);
                    PdfDictionary dict = acroFields.GetSignatureDictionary(name);

                    PdfString contents = (PdfString)PdfReader.GetPdfObject(dict.Get(PdfName.CONTENTS));


                    byte[] PKCS7      = contents.GetOriginalBytes();
                    var    signedData = new SignedCms();
                    signedData.Decode(PKCS7);
                    Console.WriteLine(signedData.Certificates.Count);
                    int i = 0;
                    foreach (var certificate in signedData.Certificates)
                    {
                        i++;

                        X509CertificateParser x509CertificateParser = new X509CertificateParser();
                        X509Certificate       x509Certificate       = x509CertificateParser.ReadCertificate(certificate.GetRawCertData());
                        RsaKeyParameters      rsaKeyParameters      = x509Certificate.GetPublicKey() as RsaKeyParameters;
                        if (RocaTest.IsVulnerable(rsaKeyParameters))
                        {
                            Console.WriteLine("Cetificate #" + i + " is vulnerable. Cert Hash: " + certificate.GetCertHashString());
                        }
                        else
                        {
                            Console.WriteLine("Cetificate #" + i + " is NOT vulnerable");
                        }
                    }
                } catch (Exception exc) {
                    Console.WriteLine(exc.Message);
                }
            }
        }
Beispiel #21
0
        public override void CreateContainer(ICadesExternalSignature externalSigner, string ouputFilePath)
        {
            if (externalSigner == null)
            {
                throw new ArgumentNullException(nameof(externalSigner));
            }

            if (ouputFilePath == null)
            {
                throw new ArgumentNullException(nameof(ouputFilePath));
            }

            AsicManifestBuilder asicManifestBuilder = new AsicManifestBuilder();

            asicManifestBuilder.AddP7Signature(SignaturePath);

            foreach ((FileInfo file, string mimeType) in this.inputFiles)
            {
                using Stream contentStream = file.OpenRead();
                asicManifestBuilder.AddFile(file.Name, mimeType, contentStream);
            }

            byte[] manifestData = asicManifestBuilder.ToByteArray();

            Pkcs7DetachedSignatureGenerator p7Generator = new Pkcs7DetachedSignatureGenerator(externalSigner);

            X509CertificateParser x509CertificateParser = new X509CertificateParser();
            X509Certificate       signingCertificate    = x509CertificateParser.ReadCertificate(externalSigner.GetCertificate());

            byte[] signature = p7Generator.GenerateP7s(manifestData, signingCertificate, this.BuildCertificatePath(signingCertificate));

            using ZipArchive archive = ZipFile.Open(ouputFilePath, ZipArchiveMode.Create);
            this.AddFileToArchive(archive, ContainerMimeTypePath, ContainerMimeType);
            this.AddFileToArchive(archive, ManifestPath, manifestData);
            this.AddFileToArchive(archive, SignaturePath, signature);

            foreach ((FileInfo file, _) in this.inputFiles)
            {
                this.AddFileToArchive(archive, file.Name, file);
            }
        }
Beispiel #22
0
        /// <summary>
        /// Convert DER encoded private key data and certificate data into a PKCS12 container.
        /// </summary>
        /// <param name="password">The password to encrypt the container with, or null for no encryption.</param>
        /// <param name="privateKeyData">The private key data that will be stored in the container.</param>
        /// <param name="certificateData">The list of certificates that will be stored in the container.</param>
        /// <returns>A PKCS12 byte array.</returns>
        static public byte[] GetPkcs12Certificate(string password, byte[] privateKeyData, ICollection <byte[]> certificateData)
        {
            var certPrivateKey = PrivateKeyFactory.CreateKey(privateKeyData);
            List <X509CertificateEntry> certificates = new List <X509CertificateEntry>();
            var x509Parser = new X509CertificateParser();
            var pkStore    = new Pkcs12Store();

            //
            // Load all the certificates from the raw data.
            //
            foreach (var certdata in certificateData)
            {
                certificates.Add(new X509CertificateEntry(x509Parser.ReadCertificate(certdata)));
            }

            //
            // Set the primary certificate and key.
            //
            var keyEntry = new AsymmetricKeyEntry(certPrivateKey);

            pkStore.SetCertificateEntry(string.Empty, certificates[0]);
            pkStore.SetKeyEntry(string.Empty, new AsymmetricKeyEntry(certPrivateKey), new[] { certificates[0] });

            //
            // Add in any additional chain certificates.
            //
            for (int i = 1; i < certificates.Count; i++)
            {
                pkStore.SetCertificateEntry(i.ToString(), certificates[i]);
            }

            //
            // Do a final conversion of the certificate data into a PKCS12 blob and add it to the store.
            //
            using (var ms = new MemoryStream())
            {
                pkStore.Save(ms, password?.ToArray(), new SecureRandom());

                return(ms.ToArray());
            }
        }
Beispiel #23
0
        private void createDB()
        {
            certs = new List <DataBase>();
            X509CertificateParser cp = new X509CertificateParser();

            XDocument db;

            if (XmlSigning.VerifyXmlFile(dbLocation))
            {
                db = XDocument.Load(dbLocation);
            }
            else
            {
                throw new GeneralSecurityException("Signature failure on db file");
            }

            // Select records of the appropriate status
            var records = db.Element("OSCA").Descendants("record").Where
                              (m => m.Element("revocation").Attribute("status").Value == certStatus.ToString().ToLower());

            foreach (XElement record in records)
            {
                DataBase entry = new DataBase();

                entry.dn           = Utility.OrderDN(record.Element("dn").Value);
                entry.serialNumber = record.Element("serialNumber").Value;
                entry.profile      = record.Element("profile").Value;
                entry.created      = friendlyDate(record.Element("created").Value);
                entry.expiry       = friendlyDate(record.Element("expiry").Value);
                entry.certificate  = cp.ReadCertificate(Convert.FromBase64String(record.Element("certificate").Value));
                entry.status       = record.Element("revocation").Attribute("status").Value;


                if (certStatus == CertStatus.Revoked)
                {
                    entry.revDate   = friendlyDate(record.Element("revocation").Element("date").Value);
                    entry.revReason = CrlReason.GetReason(record.Element("revocation").Element("reason").Value);
                }
                certs.Add(entry);
            }
        }
Beispiel #24
0
        public static bool StoreCertificateFromPem(string pem, string storeName, bool useMachineStore = true)
        {
            try
            {
                var x509CertificateParser = new X509CertificateParser();
                var cert = x509CertificateParser.ReadCertificate(System.Text.UTF8Encoding.UTF8.GetBytes(pem));

                var certToStore = new X509Certificate2(DotNetUtilities.ToX509Certificate(cert));
                using (var store = useMachineStore ? GetMachineStore(storeName) : GetUserStore(storeName))
                {
                    store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
                    store.Add(certToStore);
                    store.Close();
                    return(true);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
            /// <summary>
            /// Imports the X509 certificate.
            /// </summary>
            /// <param name="purpose">The purpose.</param>
            /// <param name="input">The input.</param>
            /// <returns></returns>
            public virtual ImportedKeySet X509Certificate(KeyPurpose purpose, Stream input)
            {
                var parser    = new X509CertificateParser();
                var cert      = parser.ReadCertificate(input);
                var bouncyKey = cert.GetPublicKey();

                Key key;

                if (bouncyKey is RsaKeyParameters)
                {
                    var keyParam = bouncyKey as RsaKeyParameters;
                    key = new RsaPublicKey
                    {
                        Modulus        = keyParam.Modulus.ToSystemBigInteger(),
                        PublicExponent = keyParam.Exponent.ToSystemBigInteger(),
                        Size           = keyParam.Modulus.BitLength,
                    };
                }
                else if (bouncyKey is DsaPublicKeyParameters)
                {
                    var keyParam = bouncyKey as DsaPublicKeyParameters;
                    if (KeyPurpose.Encrypt == purpose)
                    {
                        throw new InvalidKeySetException("DSA key cannot be used for encryption!");
                    }
                    key = new DsaPublicKey
                    {
                        Y    = keyParam.Y.ToSystemBigInteger(),
                        G    = keyParam.Parameters.G.ToSystemBigInteger(),
                        P    = keyParam.Parameters.P.ToSystemBigInteger(),
                        Q    = keyParam.Parameters.Q.ToSystemBigInteger(),
                        Size = keyParam.Parameters.P.BitLength
                    };
                }
                else
                {
                    throw new InvalidKeySetException("Unsupported key type!");
                }
                return(new ImportedKeySet(key, purpose, "imported from certificate"));
            }
Beispiel #26
0
        private void doTestCertWithBaseCertificateID()
        {
            IX509AttributeCertificate attrCert = new X509V2AttributeCertificate(certWithBaseCertificateID);
            X509CertificateParser     fact     = new X509CertificateParser();
            X509Certificate           cert     = fact.ReadCertificate(holderCertWithBaseCertificateID);

            AttributeCertificateHolder holder = attrCert.Holder;

            if (holder.GetEntityNames() != null)
            {
                Fail("entity names set when none expected");
            }

            if (!holder.SerialNumber.Equals(cert.SerialNumber))
            {
                Fail("holder serial number doesn't Match");
            }

            if (!holder.GetIssuer()[0].Equivalent(cert.IssuerDN))
            {
                Fail("holder issuer doesn't Match");
            }

            if (!holder.Match(cert))
            {
                Fail("holder not matching holder certificate");
            }

            if (!holder.Equals(holder.Clone()))
            {
                Fail("holder clone test failed");
            }

            if (!attrCert.Issuer.Equals(attrCert.Issuer.Clone()))
            {
                Fail("issuer clone test failed");
            }

            equalityAndHashCodeTest(attrCert, certWithBaseCertificateID);
        }
Beispiel #27
0
        /// <summary>
        /// Gets a list of all certificates suitable for the given key usage.
        /// </summary>
        /// <returns>The matching certificates.</returns>
        /// <param name="keyUsage">The key usage.</param>
        /// <exception cref="System.ObjectDisposedException">
        /// The keychain has been disposed.
        /// </exception>
        public IList <X509Certificate> GetCertificates(CssmKeyUse keyUsage)
        {
            if (disposed)
            {
                throw new ObjectDisposedException("SecKeychain");
            }

            var      parser = new X509CertificateParser();
            var      certs = new List <X509Certificate> ();
            IntPtr   searchRef, itemRef, certRef;
            OSStatus status;

            status = SecIdentitySearchCreate(Handle, keyUsage, out searchRef);
            if (status != OSStatus.Ok)
            {
                return(certs);
            }

            while (SecIdentitySearchCopyNext(searchRef, out itemRef) == OSStatus.Ok)
            {
                if (SecIdentityCopyCertificate(itemRef, out certRef) == OSStatus.Ok)
                {
                    using (var data = new CFData(SecCertificateCopyData(certRef), true)) {
                        var rawData = data.GetBuffer();

                        try {
                            certs.Add(parser.ReadCertificate(rawData));
                        } catch (CertificateException ex) {
                            Debug.WriteLine("Failed to parse X509 certificate from keychain: {0}", ex);
                        }
                    }
                }

                CFRelease(itemRef);
            }

            CFRelease(searchRef);

            return(certs);
        }
        public static bool IsValid(byte[] x509Cert)
        {
            X509CertificateParser parser = new X509CertificateParser();
            X509Certificate       cert   = parser.ReadCertificate(x509Cert);

            var data = CreateDatabaseInfoFromCertificate(cert);

            if (data == null || UpdateByValidTime(data))
            {
                return(false);
            }

            AsymmetricKeyParameter key;

            if (data.SerialNumber_Cert == data.SignSerialNumber_Cert)
            {
                key = PublicKeyFactory.CreateKey(data.SignAlg_Cert.PublicKey_SignAlg);
            }
            else
            {
                var root = GetCertificateBySerialNumber(data.SignSerialNumber_Cert);
                if (root == null)
                {
                    return(false);
                }
                key = PublicKeyFactory.CreateKey(root.SignAlg_Cert.PublicKey_SignAlg);
            }

            try
            {
                cert.Verify(key);
            }
            catch (CertificateException)
            {
                return(false);
            }

            return(true);
        }
        private static void CertSign(X509Certificate2 cert, X509CertificateParser cp, string destinationPath, PdfReader reader, string reason, string location)
        {
            Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[]
            {
                cp.ReadCertificate(cert.RawData)
            };

            IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA-1");

            using (FileStream fout = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite))
            {
                using (PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0', null, true))
                {
                    PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                    appearance.Reason   = reason;
                    appearance.Location = location;
                    MakeSignature.SignDetached(appearance, externalSignature, chain, null, null, null, 0,
                                               CryptoStandard.CADES);
                    stamper.Close();
                }
            }
        }
Beispiel #30
0
        public static Certificate Parse(byte[] certBytes)
        {
            Certificate certificate = new Certificate();

            try
            {
                X509Certificate2 x509 = new X509Certificate2(certBytes);
                certificate.IsLoaded         = true;
                certificate.Version          = x509.Version;
                certificate.BasicConstraints = retrieveBasicContraints(x509);
                certificate.KeyUsage         = retrieveKeyUsage(x509);
                Validity validity = new Validity();
                validity.NotBefore   = new DateTimeOffset(x509.NotBefore).ToUnixTimeSeconds();
                validity.NotAfter    = new DateTimeOffset(x509.NotAfter).ToUnixTimeSeconds();
                certificate.Validity = validity;

                X509CertificateParser x509CertificateParser = new X509CertificateParser();
                X509Certificate       bouncyCertificate     = x509CertificateParser.ReadCertificate(certBytes);

                certificate.SerialNumber           = new BigInteger(bouncyCertificate.SerialNumber.ToByteArray());
                certificate.TbsCertificate         = bouncyCertificate.GetTbsCertificate();
                certificate.TBSSignatureAlgorithm  = bouncyCertificate.CertificateStructure.TbsCertificate.Signature.GetEncoded();
                certificate.SignatureAlgorithm     = bouncyCertificate.CertificateStructure.SignatureAlgorithm.GetEncoded();
                certificate.Signature              = bouncyCertificate.GetSignature();
                certificate.SubjectPublicKeyInfo   = bouncyCertificate.CertificateStructure.SubjectPublicKeyInfo.GetEncoded();
                certificate.SubjectKeyIdentifier   = retrieveSubjectKeyIdentifier(bouncyCertificate);
                certificate.AuthorityKeyIdentifier = retrieveAuthorityKeyIdentifier(bouncyCertificate);
                certificate.ExtendedKeyUsage       = retrieveExtendedKeyUsageOIDs(bouncyCertificate);
                certificate.Issuer   = RetrieveIssuerName(bouncyCertificate);
                certificate.Subject  = RetrieveSubjectName(bouncyCertificate);
                certificate.DNsNames = retrieveDnsNames(bouncyCertificate);
                return(certificate);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(certificate);
            }
        }