Beispiel #1
0
		public void SetUp ()
		{
			using (var ctx = CreateContext ()) {
				var dataDir = Path.Combine ("..", "..", "TestData", "smime");
				string path;

				CryptographyContext.Register (ctx.GetType ());

				foreach (var filename in CertificateAuthorities) {
					path = Path.Combine (dataDir, filename);
					using (var file = File.OpenRead (path)) {
						if (ctx is DefaultSecureMimeContext) {
							((DefaultSecureMimeContext) ctx).Import (file, true);
						} else {
							var parser = new X509CertificateParser ();
							foreach (X509Certificate certificate in parser.ReadCertificates (file))
								ctx.Import (certificate);
						}
					}
				}

				path = Path.Combine (dataDir, "smime.p12");

				using (var file = File.OpenRead (path))
					ctx.Import (file, "no.secret");
			}
		}
Beispiel #2
0
        public static void AssinaComCertificado(List <ICrlClient> crlList, string FileName, string SignFileName, CertSimples cert, int X, int Y, int Pagina, int Rotation, bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-256", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", TipoAssinatura Tipo = TipoAssinatura.Normal, string Cargo = "", string CREACRM = "")
        {
            string             SourcePdfFileName = FileName;
            string             DestPdfFileName   = SignFileName;
            int                Largura           = 140;
            int                Altura            = 63;
            PdfReader          pdfReader         = new PdfReader(SourcePdfFileName);
            FileStream         signedPdf         = new FileStream(DestPdfFileName, FileMode.Create, FileAccess.ReadWrite);
            StampingProperties osp = new StampingProperties();

            osp.UseAppendMode();
            PdfSigner   objStamper = new PdfSigner(pdfReader, signedPdf, osp);
            ITSAClient  tsaClient  = null;
            IOcspClient ocspClient = null;

            ConfiguraAparencia(objStamper, cert, X, Y, Largura, Altura, Pagina, Rotation, Contact, Reason, Location, Creator, Tipo);

            Org.BouncyCastle.X509.X509Certificate       vert       = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert.Certificado);
            Org.BouncyCastle.X509.X509CertificateParser cp         = new Org.BouncyCastle.X509.X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate[]     Arraychain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) };
            X509CertificateParser objCP = new X509CertificateParser();

            RSACryptoServiceProvider rsa;
            RSACryptoServiceProvider Provider;
            IExternalSignature       externalSignature;

            if (cert.Certificado.PrivateKey is RSACryptoServiceProvider)
            {
                rsa               = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                Provider          = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm);
            }
            else
            {
                //RETIRAR ESSA PARTE PARA IMPLEMENTAR OS DEMAIS MÉTODOS, OLHANDO OUTROS TIPOS DE CERTIFICADO
                rsa               = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                Provider          = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm);
            }
            if (AddTimeStamper)
            {
                tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass);
            }
            OCSPVerifier ocspVerifier = new OCSPVerifier(null, null);

            ocspClient = new OcspClientBouncyCastle(ocspVerifier);
            if (AplicaPolitica)
            {
                SignaturePolicyInfo spi = getPolitica();
                objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES, spi);
            }
            else
            {
                objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES);
            }
            try { signedPdf.Flush(); }
            catch { }
            try { signedPdf.Close(); } catch { };
            pdfReader.Close();
        }
        public virtual IList<CertificateAndContext> GetCertificateBySubjectName(X509Name
			 subjectName)
		{
			IList<CertificateAndContext> list = new AList<CertificateAndContext>();
			try
			{
				string url = GetAccessLocation(certificate, X509ObjectIdentifiers.IdADCAIssuers);
				if (url != null)
				{
                    X509CertificateParser parser = new X509CertificateParser();
                    X509Certificate cert = parser.ReadCertificate(httpDataLoader.Get(url));

					if (cert.SubjectDN.Equals(subjectName))
					{
						list.Add(new CertificateAndContext());
					}
				}
			}
			catch (CannotFetchDataException)
			{
                return new List<CertificateAndContext>();
			}
			catch (CertificateException)
			{
                return new List<CertificateAndContext>();
			}
			return list;
		}
        static CrlDistPoint ExtractCrlDistributionPointsExtension(X509Certificate2 certificate)
        {
            var bouncyCastleCertificate = new X509CertificateParser().ReadCertificate(certificate.RawData);
            var extension = bouncyCastleCertificate.GetExtensionValue(new DerObjectIdentifier(ObjectIdentifiers.CrlDistributionPointsExtension));
            var stream = new Asn1InputStream(extension.GetOctetStream());

            return CrlDistPoint.GetInstance(stream.ReadObject());
        }
        public static X509Certificate LoadCertificate(string filename)
        {
            X509CertificateParser certParser = new X509CertificateParser();
            FileStream fs = new FileStream(filename, FileMode.Open);
            X509Certificate cert = certParser.ReadCertificate(fs);
            fs.Close();

            return cert;
        }
Beispiel #6
0
        public static bool SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, bool AddTimeStamp, string strTSA)
        {
            PdfReader  objReader  = null;
            PdfStamper objStamper = null;

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

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

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

                // Creamos la apariencia
                PdfSignatureAppearance signatureAppearance = objStamper.SignatureAppearance;
                signatureAppearance.Reason = "Inforegistro, S.L.";
                //signatureAppearance.Location = Location;

                // Custom signature appearance text
                var font = FontFactory.GetFont("Times New Roman", 11, iTextSharp.text.Font.BOLDITALIC, BaseColor.DARK_GRAY);
                signatureAppearance.Layer2Font = font;
                signatureAppearance.Layer2Text = "Firmado digitalmente por \r\nInforegistro, S.L.\r\nFecha  " + DateTime.Now.ToShortDateString();
                var rectangle = new Rectangle(350, 30, 500, 120);

                // Si está la firma visible:
                if (AddVisibleSign)
                {
                    signatureAppearance.SetVisibleSignature(rectangle, 2, "Inforegistro");
                }

                ITSAClient  tsaClient  = null;
                IOcspClient ocspClient = null;

                // Creating the signature
                IExternalSignature externalSignature = new X509Certificate2Signature(Certificate, "SHA-1");
                MakeSignature.SignDetached(signatureAppearance, externalSignature, objChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS);
                return(File.Exists(Target));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (objReader != null)
                {
                    objReader.Close();
                }
                if (objStamper != null)
                {
                    objStamper.Close();
                }
            }
        }
		private void baseTest()
		{
//			CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
			X509CertificateParser certParser = new X509CertificateParser();
			X509CrlParser crlParser = new X509CrlParser();

			// initialise CertStore
			X509Certificate rootCert = certParser.ReadCertificate(CertPathTest.rootCertBin);
			X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin);
			X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin);
			X509Crl rootCrl = crlParser.ReadCrl(CertPathTest.rootCrlBin);
			X509Crl interCrl = crlParser.ReadCrl(CertPathTest.interCrlBin);

			IList certList = new ArrayList();
			certList.Add(rootCert);
			certList.Add(interCert);
			certList.Add(finalCert);

			IList crlList = new ArrayList();
			crlList.Add(rootCrl);
			crlList.Add(interCrl);

//			CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list);
//			CertStore store = CertStore.getInstance("Collection", ccsp, "BC");
			IX509Store x509CertStore = X509StoreFactory.Create(
				"Certificate/Collection",
				new X509CollectionStoreParameters(certList));
			IX509Store x509CrlStore = X509StoreFactory.Create(
				"CRL/Collection",
				new X509CollectionStoreParameters(crlList));

			// NB: Month is 1-based in .NET
            //DateTime validDate = new DateTime(2008, 9, 4, 14, 49, 10).ToUniversalTime();
            DateTime validDate = new DateTime(2008, 9, 4, 5, 49, 10);//.ToUniversalTime();

			//Searching for rootCert by subjectDN without CRL
			ISet trust = new HashSet();
			trust.Add(new TrustAnchor(rootCert, null));

//			CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX","BC");
			PkixCertPathBuilder cpb = new PkixCertPathBuilder();
			X509CertStoreSelector targetConstraints = new X509CertStoreSelector();
			targetConstraints.Subject = finalCert.SubjectDN;
			PkixBuilderParameters parameters = new PkixBuilderParameters(trust, targetConstraints);
//			parameters.addCertStore(store);
			parameters.AddStore(x509CertStore);
			parameters.AddStore(x509CrlStore);
			parameters.Date = new DateTimeObject(validDate);
			PkixCertPathBuilderResult result = cpb.Build(parameters);
			PkixCertPath path = result.CertPath;

			if (path.Certificates.Count != 2)
			{
				Fail("wrong number of certs in baseTest path");
			}
		}
        static X509Certificate ReadCertificate(String filename)
        {
            X509CertificateParser certParser = new X509CertificateParser();

            Stream stream = new FileStream(filename, FileMode.Open);
            X509Certificate cert = certParser.ReadCertificate(stream);
            stream.Close();

            return cert;
        }
		private IX509AttributeCertificate CreateAttrCert()
		{
//			CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
//			X509Certificate iCert = (X509Certificate) fact
//				.generateCertificate(new ByteArrayInputStream(holderCert));
			X509Certificate iCert = new X509CertificateParser().ReadCertificate(holderCert);

			//
			// a sample key pair.
			//
			// RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
			// new BigInteger(
			// "b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7",
			// 16), new BigInteger("11", 16));

			//
			// set up the keys
			//
//			KeyFactory kFact = KeyFactory.getInstance("RSA", "BC");
//			PrivateKey privKey = kFact.generatePrivate(RsaPrivateKeySpec);
			AsymmetricKeyParameter privKey = RsaPrivateKeySpec;

			X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator();

			// the actual attributes
			GeneralName roleName = new GeneralName(GeneralName.Rfc822Name, "*****@*****.**");
			Asn1EncodableVector roleSyntax = new Asn1EncodableVector(roleName);

			// roleSyntax OID: 2.5.24.72
			X509Attribute attributes = new X509Attribute("2.5.24.72",
				new DerSequence(roleSyntax));

			gen.AddAttribute(attributes);
			gen.SetHolder(new AttributeCertificateHolder(PrincipalUtilities.GetSubjectX509Principal(iCert)));
			gen.SetIssuer(new AttributeCertificateIssuer(new X509Name("cn=test")));
			gen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
			gen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
			gen.SetSerialNumber(BigInteger.One);
			gen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

			Target targetName = new Target(
				Target.Choice.Name,
				new GeneralName(GeneralName.DnsName, "www.test.com"));

			Target targetGroup = new Target(
				Target.Choice.Group,
				new GeneralName(GeneralName.DirectoryName, "o=Test, ou=Test"));

			Target[] targets = new Target[]{ targetName, targetGroup };

			TargetInformation targetInformation = new TargetInformation(targets);
			gen.AddExtension(X509Extensions.TargetInformation.Id, true, targetInformation);

			return gen.Generate(privKey);
		}
        /// <summary>
        /// Imports the certificate into the PKCS#11 compatible device and pairs it with the corresponding private key
        /// </summary>
        /// <param name="session">Session with user logged in</param>
        /// <param name="certificate">Certificate that should be imported</param>
        /// <returns>Handle of created certificate object</returns>
        public static ObjectHandle ImportCertificate(Session session, byte[] certificate)
        {
            // Parse certificate
            X509CertificateParser x509CertificateParser = new X509CertificateParser();
            X509Certificate x509Certificate = x509CertificateParser.ReadCertificate(certificate);

            // Get public key from certificate
            AsymmetricKeyParameter pubKeyParams = x509Certificate.GetPublicKey();
            if (!(pubKeyParams is RsaKeyParameters))
                throw new NotSupportedException("Currently only RSA keys are supported");
            RsaKeyParameters rsaPubKeyParams = (RsaKeyParameters)pubKeyParams;

            // Find corresponding private key
            List<ObjectAttribute> privKeySearchTemplate = new List<ObjectAttribute>();
            privKeySearchTemplate.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY));
            privKeySearchTemplate.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_RSA));
            privKeySearchTemplate.Add(new ObjectAttribute(CKA.CKA_MODULUS, rsaPubKeyParams.Modulus.ToByteArrayUnsigned()));
            privKeySearchTemplate.Add(new ObjectAttribute(CKA.CKA_PUBLIC_EXPONENT, rsaPubKeyParams.Exponent.ToByteArrayUnsigned()));

            List<ObjectHandle> foundObjects = session.FindAllObjects(privKeySearchTemplate);
            if (foundObjects.Count != 1)
                throw new ObjectNotFoundException("Corresponding RSA private key not found");

            ObjectHandle privKeyObjectHandle = foundObjects[0];

            // Read CKA_LABEL and CKA_ID attributes of private key
            List<CKA> privKeyAttrsToRead = new List<CKA>();
            privKeyAttrsToRead.Add(CKA.CKA_LABEL);
            privKeyAttrsToRead.Add(CKA.CKA_ID);

            List<ObjectAttribute> privKeyAttributes = session.GetAttributeValue(privKeyObjectHandle, privKeyAttrsToRead);

            // Define attributes of new certificate object
            List<ObjectAttribute> certificateAttributes = new List<ObjectAttribute>();
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE));
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, false));
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_MODIFIABLE, true));
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, privKeyAttributes[0].GetValueAsString()));
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_CERTIFICATE_TYPE, CKC.CKC_X_509));
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_TRUSTED, false));
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_SUBJECT, x509Certificate.SubjectDN.GetDerEncoded()));
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_ID, privKeyAttributes[1].GetValueAsByteArray()));
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_ISSUER, x509Certificate.IssuerDN.GetDerEncoded()));
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_SERIAL_NUMBER, new DerInteger(x509Certificate.SerialNumber).GetDerEncoded()));
            certificateAttributes.Add(new ObjectAttribute(CKA.CKA_VALUE, x509Certificate.GetEncoded()));

            // Create certificate object
            return session.CreateObject(certificateAttributes);
        }
        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;
        }
        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 #13
0
		private void certPairTest()
		{
			X509CertificateParser certParser = new X509CertificateParser();

			X509Certificate rootCert = certParser.ReadCertificate(CertPathTest.rootCertBin);
			X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin);
			X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin);

			// Testing CollectionCertStore generation from List
			X509CertificatePair pair1 = new X509CertificatePair(rootCert, interCert);

			IList certList = new ArrayList();
			certList.Add(pair1);
			certList.Add(new X509CertificatePair(interCert, finalCert));

			IX509Store certStore = X509StoreFactory.Create(
				"CertificatePair/Collection",
				new X509CollectionStoreParameters(certList));

			X509CertPairStoreSelector selector = new X509CertPairStoreSelector();
			X509CertStoreSelector fwSelector = new X509CertStoreSelector();

			fwSelector.SerialNumber = rootCert.SerialNumber;
			fwSelector.Subject = rootCert.IssuerDN;

			selector.ForwardSelector = fwSelector;

			IList col = new ArrayList(certStore.GetMatches(selector));

			if (col.Count != 1 || !col.Contains(pair1))
			{
				Fail("failed pair1 test");
			}

			col = new ArrayList(certStore.GetMatches(null));

			if (col.Count != 2)
			{
				Fail("failed null test");
			}
		}
        /// <summary>
        /// Gets a new instance of a code signing certificate from a file 
        /// </summary>
        /// <param name="path">path to the certificate file</param>
        /// <returns>a codesigningcertificate object</returns>
        public static CodeSigningCertificate GetNewInstance(string path)
        {
            X509CertificateParser parser = new X509CertificateParser();
            X509Certificate cert;

            try
            {
                FileStream f = File.OpenRead(path);
                cert = parser.ReadCertificate(f);
            }
            catch(Exception)
            {
                throw new ApplicationException("certificate not found at specified location or not certificate file");
            }

            if (IsSelfSigned(cert))
            {
                return new CodeSigningCertificateRoot(cert, path);
            }
            return new CodeSigningCertificateChild(cert, path);
        }
        /// <summary>
        /// Obtém os certificados no Sistema Operacional
        /// </summary>
        /// <param name="sn">"Tipo" de certificados</param>
        /// <param name="sl">"Escopo" dos certificados: usuário, máquina ...</param>
        /// <param name="kall">Variável de referência com a lista dos certificados</param>
        private static void getSystemCertificates(StoreName sn, StoreLocation sl, ref List <BCX.X509Certificate> kall)
        {
            // "dealing" with the system certificates
            BCX.X509CertificateParser parser = new BCX.X509CertificateParser();

            // get the certificates store
            X509Store st = new X509Store(sn, sl);

            st.Open(OpenFlags.ReadOnly);

            // get the certificates and close the store
            X509Certificate2Collection col = st.Certificates;

            st.Close();

            // add the certificates to the list
            foreach (X509Certificate2 cert in col)
            {
                BCX.X509Certificate c2 = parser.ReadCertificate(cert.GetRawCertData());
                kall.Add(c2);
            }
        }
 private static bool Verify(X509Certificate2 certificate, AsymmetricKeyParameter publicKey)
 {
     try
     {
         var bcCertificate = new X509CertificateParser().ReadCertificate(certificate.RawData);
         bcCertificate.Verify(publicKey);
         return true;
     }
     catch (InvalidKeyException)
     {
         //ignore on purpose
     }
     catch (CertificateException)
     {
         //ignore on purpose
     }
     catch (SignatureException)
     {
         //ignore on purpose
     }
     return false;
 }
Beispiel #17
0
        internal void checkNameCertificate(
            int     id,
            byte[]  bytes)
        {
            string dump = "";

            try
            {
                X509Certificate cert = new X509CertificateParser().ReadCertificate(bytes);

                AsymmetricKeyParameter k = cert.GetPublicKey();
                if (!cert.IssuerDN.ToString().Equals("C=DE,O=DATEV eG,0.2.262.1.10.7.20=1+CN=CA DATEV D03 1:PN"))
                {
                    Fail(id + " failed - name test.");
                }
                // Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail(dump + SimpleTest.NewLine + Name + ": "+ id + " failed - exception " + e.Message, e);
            }

        }
		/// <summary>
		/// Imports the certificate(s) from the specified stream.
		/// </summary>
		/// <remarks>
		/// Imports the certificate(s) from the specified stream.
		/// </remarks>
		/// <param name="stream">The stream to import.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="stream"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An error occurred reading the stream.
		/// </exception>
		public void Import (Stream stream)
		{
			if (stream == null)
				throw new ArgumentNullException ("stream");

			var parser = new X509CertificateParser ();

			foreach (X509Certificate certificate in parser.ReadCertificates (stream)) {
				if (unique.Add (certificate))
					certs.Add (certificate);
			}
		}
Beispiel #19
0
        private void pkcs7Test()
        {
            Asn1Encodable rootCert = Asn1Object.FromByteArray(CertPathTest.rootCertBin);
            Asn1Encodable rootCrl = Asn1Object.FromByteArray(CertPathTest.rootCrlBin);

            X509CertificateParser certParser = new X509CertificateParser();
            X509CrlParser crlParser = new X509CrlParser();

            SignedData sigData = new SignedData(
                DerSet.Empty,
                new ContentInfo(CmsObjectIdentifiers.Data, null),
                new DerSet(
                    rootCert,
                    new DerTaggedObject(false, 2, Asn1Object.FromByteArray(AttrCertTest.attrCert))),
                new DerSet(rootCrl),
                DerSet.Empty);

            ContentInfo info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            X509Certificate cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert == null || !AreEqual(cert.GetEncoded(), rootCert.ToAsn1Object().GetEncoded()))
            {
                Fail("PKCS7 cert not read");
            }
            X509Crl crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl == null || !AreEqual(crl.GetEncoded(), rootCrl.ToAsn1Object().GetEncoded()))
            {
                Fail("PKCS7 crl not read");
            }
            ArrayList col = new ArrayList(certParser.ReadCertificates(info.GetEncoded()));
            if (col.Count != 1 || !col.Contains(cert))
            {
                Fail("PKCS7 cert collection not right");
            }
            col = new ArrayList(crlParser.ReadCrls(info.GetEncoded()));
            if (col.Count != 1 || !col.Contains(crl))
            {
                Fail("PKCS7 crl collection not right");
            }

            // data with no certificates or CRLs

            sigData = new SignedData(DerSet.Empty, new ContentInfo(CmsObjectIdentifiers.Data, null), DerSet.Empty, DerSet.Empty, DerSet.Empty);

            info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert != null)
            {
                Fail("PKCS7 cert present");
            }
            crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl != null)
            {
                Fail("PKCS7 crl present");
            }

            // data with absent certificates and CRLS

            sigData = new SignedData(DerSet.Empty, new ContentInfo(CmsObjectIdentifiers.Data, null), null, null, DerSet.Empty);

            info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert != null)
            {
                Fail("PKCS7 cert present");
            }
            crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl != null)
            {
                Fail("PKCS7 crl present");
            }

            //
            // sample message
            //
            ICollection certCol = certParser.ReadCertificates(pkcs7CrlProblem);
            ICollection crlCol = crlParser.ReadCrls(pkcs7CrlProblem);

            if (crlCol.Count != 0)
            {
                Fail("wrong number of CRLs: " + crlCol.Count);
            }

            if (certCol.Count != 4)
            {
                Fail("wrong number of Certs: " + certCol.Count);
            }
        }
Beispiel #20
0
        /**
         * we Generate a self signed certificate for the sake of testing - GOST3410
         */
        internal void checkCreation4()
        {
            //
            // set up the keys
            //
            AsymmetricKeyParameter privKey;
            AsymmetricKeyParameter pubKey;

//			GOST3410ParameterSpec gost3410P = new GOST3410ParameterSpec("GostR3410-94-CryptoPro-A");
//			g.initialize(gost3410P, new SecureRandom());
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");
            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            privKey = p.Private;
            pubKey = p.Public;

            //
            // distinguished name table.
            //
            IDictionary attrs = new Hashtable();
            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.E, "*****@*****.**");

            IList order = new ArrayList();
            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.L);
            order.Add(X509Name.ST);
            order.Add(X509Name.E);

            //
            // extensions
            //

            //
            // create the certificate - version 3
            //
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(order, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(order, attrs));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("GOST3411withGOST3410");

            X509Certificate cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            //
            // check verifies in general
            //
            cert.Verify(pubKey);

            //
            // check verifies with contained key
            //
            cert.Verify(cert.GetPublicKey());

            cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

            //Console.WriteLine(cert);

            //check getEncoded()
            byte[] bytesch = cert.GetEncoded();
        }
Beispiel #21
0
        /**
         * we Generate a self signed certificate for the sake of testing - ECDSA
         */
        internal void checkCreation3()
        {
            ECCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

            ECDomainParameters spec = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n

            ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
                spec);

            //
            // set up the keys
            //
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;
//
//			try
//			{
//				KeyFactory fact = KeyFactory.GetInstance("ECDSA");
//
//				privKey = fact.generatePrivate(privKeySpec);
//				pubKey = fact.generatePublic(pubKeySpec);
//			}
//			catch (Exception e)
//			{
//				Fail("error setting up keys - " + e.ToString());
//				return;
//			}

            //
            // distinguished name table.
            //
            IDictionary attrs = new Hashtable();
            IList order = new ArrayList();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.E, "*****@*****.**");

            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.L);
            order.Add(X509Name.ST);
            order.Add(X509Name.E);


            //
            // ToString test
            //
            X509Name p = new X509Name(order, attrs);
            string s = p.ToString();

            if (!s.Equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne,ST=Victoria,[email protected]"))
            {
                Fail("ordered X509Principal test failed - s = " + s + ".");
            }

            //
            // create the certificate - version 3
            //
            X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(order, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(order, attrs));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("SHA1withECDSA");

            try
            {
                X509Certificate cert = certGen.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                X509CertificateParser fact = new X509CertificateParser();
                cert = fact.ReadCertificate(cert.GetEncoded());

                //
                // try with point compression turned off
                //
//				((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
                ECPoint q = pubKey.Q.Normalize();
                pubKey = new ECPublicKeyParameters(
                    pubKey.AlgorithmName,
                    q.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()),
                    pubKey.Parameters);

                certGen.SetPublicKey(pubKey);

                cert = certGen.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                cert = fact.ReadCertificate(cert.GetEncoded());

                // Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail("error setting generating cert - " + e.ToString());
            }

            X509Name pr = new X509Name("O=\"The Bouncy Castle, The Legion of\",[email protected],ST=Victoria,L=Melbourne,C=AU");

            if (!pr.ToString().Equals("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU"))
            {
                Fail("string based X509Principal test failed.");
            }

            pr = new X509Name("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU");

            if (!pr.ToString().Equals("O=The Bouncy Castle\\, The Legion of,[email protected],ST=Victoria,L=Melbourne,C=AU"))
            {
                Fail("string based X509Principal test failed.");
            }
        }
Beispiel #22
0
        /**
         * we Generate a self signed certificate for the sake of testing - RSA
         */
        internal void checkCreation1()
        {
            //
            // a sample key pair.
            //
            RsaKeyParameters pubKey = new RsaKeyParameters(
                false,
                new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
                new BigInteger("11", 16));

            RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
                new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
                new BigInteger("11", 16),
                new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16),
                new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16),
                new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16),
                new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16),
                new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16),
                new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));

            //
            // set up the keys
            //
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;

//			KeyFactory  fact = KeyFactory.GetInstance("RSA");
//
//			privKey = fact.generatePrivate(privKeySpec);
//			pubKey = fact.generatePublic(pubKeySpec);

            //
            // distinguished name table.
            //
            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            //
            // extensions
            //

            //
            // create the certificate - version 3 - without extensions
            //
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, values));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(ord, values));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption");

            X509Certificate cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            ISet dummySet = cert.GetNonCriticalExtensionOids();
            if (dummySet != null)
            {
                Fail("non-critical oid set should be null");
            }
            dummySet = cert.GetCriticalExtensionOids();
            if (dummySet != null)
            {
                Fail("critical oid set should be null");
            }

            //
            // create the certificate - version 3 - with extensions
            //
            certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, values));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(ord, values));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");
            certGen.AddExtension("2.5.29.15", true,
                new X509KeyUsage(X509KeyUsage.EncipherOnly));
            certGen.AddExtension("2.5.29.37", true,
                new DerSequence(KeyPurposeID.AnyExtendedKeyUsage));
            certGen.AddExtension("2.5.29.17", true,
                new GeneralNames(new GeneralName(GeneralName.Rfc822Name, "*****@*****.**")));

            cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

            if (!cert.GetKeyUsage()[7])
            {
                Fail("error generating cert - key usage wrong.");
            }

            IList l = cert.GetExtendedKeyUsage();
            if (!l[0].Equals(KeyPurposeID.AnyExtendedKeyUsage.Id))
            {
                Fail("failed extended key usage test");
            }

            foreach (IList gn in cert.GetSubjectAlternativeNames())
            {
                if (!gn[1].Equals("*****@*****.**"))
                {
                    Fail("failed subject alternative names test");
                }
            }

            // Console.WriteLine(cert);

            //
            // create the certificate - version 1
            //
            X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator();

            certGen1.SetSerialNumber(BigInteger.One);
            certGen1.SetIssuerDN(new X509Name(ord, values));
            certGen1.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen1.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen1.SetSubjectDN(new X509Name(ord, values));
            certGen1.SetPublicKey(pubKey);
            certGen1.SetSignatureAlgorithm("MD5WithRSAEncryption");

            cert = certGen1.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

            // Console.WriteLine(cert);
            if (!cert.IssuerDN.Equivalent(cert.SubjectDN))
            {
                Fail("name comparison fails");
            }
        }
Beispiel #23
0
        public static void AssinaComCertificado(List <ICrlClient> crlList, byte[] File, out byte[] SignFile, CertSimples cert, int X, int Y, int Pagina, int Rotation, bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-256", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", TipoAssinatura Tipo = TipoAssinatura.Normal, string Cargo = "", string CREACRM = "")
        {
            int                Largura       = 140;
            int                Altura        = 63;
            MemoryStream       ArquivoOrigem = new MemoryStream(File);
            PdfReader          pdfReader     = new PdfReader(ArquivoOrigem);
            MemoryStream       signedPdf     = new MemoryStream();
            StampingProperties osp           = new StampingProperties();

            osp.UseAppendMode();
            PdfSigner   objStamper = new PdfSigner(pdfReader, signedPdf, osp);
            ITSAClient  tsaClient  = null;
            IOcspClient ocspClient = null;

            ConfiguraAparencia(objStamper, cert, X, Y, Largura, Altura, Pagina, Rotation, Contact, Reason, Location, Creator, Tipo, Cargo, CREACRM);

            Org.BouncyCastle.X509.X509Certificate       vert       = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert.Certificado);
            Org.BouncyCastle.X509.X509CertificateParser cp         = new Org.BouncyCastle.X509.X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate[]     Arraychain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) };
            X509CertificateParser objCP = new X509CertificateParser();

            RSACryptoServiceProvider rsa;
            RSACryptoServiceProvider Provider;
            IExternalSignature       externalSignature;

            if (cert.Certificado.PrivateKey is RSACryptoServiceProvider)
            {
                rsa               = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                Provider          = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm);
            }
            else
            {
                RSA rsaTeste = cert.Certificado.GetRSAPrivateKey();

                rsa               = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                Provider          = (RSACryptoServiceProvider)cert.Certificado.PrivateKey;
                externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm);
            }

            if (AddTimeStamper)
            {
                tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass);
            }
            OCSPVerifier ocspVerifier = new OCSPVerifier(null, null);

            ocspClient = new OcspClientBouncyCastle(ocspVerifier);
            if (AplicaPolitica)
            {
                SignaturePolicyInfo spi = getPolitica();
                objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES, spi);
            }
            else
            {
                objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES);
            }

            try
            {
                SignFile = signedPdf.ToArray();
                try
                {
                    signedPdf.Close();
                    signedPdf.Dispose();
                }
                catch { }
            }
            catch (Exception ex)
            {
                SignFile = null;
                throw ex;
            }
            try
            {
                signedPdf.Close();
            }
            catch (Exception ex) { }
            pdfReader.Close();
        }
Beispiel #24
0
        /// <summary>
        /// Read CA private key file from .key or pfx file
        /// Read data from certificate request file .csr
        /// Generate signed certificate request file .cer
        /// </summary>
        /// <param name="signedCERFile"></param>
        /// <param name="privateKeyFile"></param>
        /// <param name="v"></param>
        /// <param name="password"></param>
        private async void GenerateCerFile(string certRequestFile,
                                           string privateKeyFile,
                                           string generateSignedCertificateFile,
                                           string password, string friendlyName,
                                           DateTime startDate, DateTime endDate)
        {
            #region LoadCertificate

            // read public & private key from file
            AsymmetricKeyParameter privateKey = null;
            AsymmetricKeyParameter publicKey  = null;

            System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCertificate = null;
            Org.BouncyCastle.X509.X509Certificate issuerCertificateX509 = null;

            // Ovo NE radi
            //issuerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(
            //        privateKeyFile,
            //        password
            //        );

            // Ovo RADI
            issuerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(
                privateKeyFile,
                password,
                System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
                );

            // This doesn't work for selfsign certificate
            //bool isOK = issuerCertificate.Verify();

            bool     isHasPrivateKey = issuerCertificate.HasPrivateKey;
            DateTime noAfter         = issuerCertificate.NotAfter;
            DateTime noBefore        = issuerCertificate.NotBefore;
            X509ExtensionCollection x509extensions = issuerCertificate.Extensions;

            int errorNum = 0;
            X509CertificateParser parser = new X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate bouncyCertificate = parser.ReadCertificate(issuerCertificate.RawData);
            BasicConstraints basicConstraints = null;
            bool             isCa             = false;
            Asn1OctetString  str = bouncyCertificate.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
            if (str != null)
            {
                basicConstraints = BasicConstraints.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(str));
                if (basicConstraints != null)
                {
                    isCa = basicConstraints.IsCA();
                }
            }

            if (!isCa)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Loaded CA file: " + privateKeyFile + " IS NOT CA authority certificate file!" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            // This doesn't work for selfsign certificate
            //if (!isOK)
            //{
            //    errorNum++;
            //    Brush bckForeground = tbOutputMessageBox.Foreground;
            //    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
            //    tbOutputMessageBox.Text += "File with CA certificate NOT valid." + "\n";
            //    tbOutputMessageBox.Foreground = bckForeground;
            //}
            if (!isHasPrivateKey)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate DOES NOT have a private key." + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            if (noBefore > startDate)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate start date: " + startDate.ToLocalTime() + " DOES NOT valid value. Certificate start date is: " + noBefore.ToLocalTime() + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            if (noAfter < endDate)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate end date: " + endDate.ToLocalTime() + " DOES NOT valid value. Certificate end date is: " + noAfter.ToLocalTime() + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            if (errorNum > 0)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate has error!!!" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;

                return;
            }
            bool isOk = issuerCertificate.Verify();

            AsymmetricCipherKeyPair issuerKeyPairTmp = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);
            privateKey = issuerKeyPairTmp.Private;
            publicKey  = issuerKeyPairTmp.Public;

            issuerCertificateX509 = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(issuerCertificate.GetRawCertData());
            issuerCertificateX509.Verify(publicKey);

            Org.BouncyCastle.X509.X509Certificate x509 = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(issuerCertificate);
            x509.Verify(publicKey);
            x509.CheckValidity(startDate);

            #endregion

            // Read certificate request .csr file
            Pkcs10CertificationRequest cerRequest = null;
            try
            {
                String       input_data = File.ReadAllText(certRequestFile);
                StringReader sr         = new StringReader(input_data);
                PemReader    pr         = new PemReader(sr);
                cerRequest = (Pkcs10CertificationRequest)pr.ReadObject();

                tbOutputMessageBox.Text += "Verify file with certificate request : " + certRequestFile + "\n";
                bool requestIsOK = cerRequest.Verify();
                if (requestIsOK)
                {
                    tbOutputMessageBox.Text += "File with certificate request : " + certRequestFile + " is OK." + "\n";
                }
                else
                {
                    tbOutputMessageBox.Text += "File with certificate request : " + certRequestFile + " NOT valid." + "\n";
                    return;
                }
            }
            catch (Exception ex)
            {
                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR reading certificate request file (.csr)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }

            Org.BouncyCastle.X509.X509Certificate genCert = GenerateSignedCertificate(
                cerRequest,
                x509,
                issuerKeyPairTmp,
                startDate, endDate);

            try
            {
                File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded());
                tbOutputMessageBox.Text += "Certificate file: " + generateSignedCertificateFile + " sucessfully saved." + "\n";

                signedRequestFileNamePath = generateSignedCertificateFile;
                btnContinue.IsEnabled     = true;
            }
            catch (Exception)
            {
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
            }

            #region Public Key
            //try
            //{
            //    var store = new Pkcs12Store();
            //    string friendlyName1 = issuerCertificateX509.SubjectDN.ToString();
            //    var certificateEntry = new X509CertificateEntry(issuerCertificateX509);
            //    store.SetCertificateEntry(friendlyName1, certificateEntry);
            //    store.SetKeyEntry(friendlyName1, new AsymmetricKeyEntry(privateKey), new[] { certificateEntry });

            //    var stream = new MemoryStream();
            //    var random1 = GetSecureRandom();
            //    store.Save(stream, "password".ToCharArray(), random1);

            //    //Verify that the certificate is valid.
            //    var convertedCertificate = new X509Certificate2(stream.ToArray(), "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            //    //Write the file.
            //    File.WriteAllBytes(generateSignedCertificateFile, stream.ToArray());

            //    File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded());

            //    //using (TextWriter tw = new StreamWriter(outputPublicKeyName))
            //    //{
            //    //    PemWriter pw = new PemWriter(tw);
            //    //    pw.WriteObject(subjectKeyPair.Public);
            //    //    tw.Flush();
            //    //}

            //    tbOutputMessageBox.Text += "File with private key: " + generateSignedCertificateFile + " sucessfully generated." + "\n";
            //}
            //catch (Exception ex)
            //{
            //    var metroWindow = (Application.Current.MainWindow as MetroWindow);
            //    await metroWindow.ShowMessageAsync("Info Warning",
            //         "ERROR creating certificate private key file (.key)" + "\n" +
            //         "Error: " + ex.Source + " " + ex.Message,
            //         MessageDialogStyle.Affirmative);
            //    return;
            //}

            //StringBuilder publicKeyStrBuilder = new StringBuilder();
            //PemWriter publicKeyPemWriter = new PemWriter(new StringWriter(publicKeyStrBuilder));
            //publicKeyPemWriter.WriteObject(genCert.GetPublicKey());
            //publicKeyPemWriter.Writer.Flush();

            //string publicKey = publicKeyStrBuilder.ToString();
            //try
            //{
            //    using (TextWriter tw = new StreamWriter(generateSignedCertificateFile))
            //    {
            //        PemWriter pw = new PemWriter(tw);
            //        pw.WriteObject(genCert.GetPublicKey());
            //        tw.Flush();
            //    }

            //    tbOutputMessageBox.Text += "File with private key: " + generateSignedCertificateFile + " sucessfully generated." + "\n";
            //}
            //catch (Exception ex)
            //{
            //    var metroWindow = (Application.Current.MainWindow as MetroWindow);
            //    await metroWindow.ShowMessageAsync("Info Warning",
            //         "ERROR creating certificate private key file (.key)" + "\n" +
            //         "Error: " + ex.Source + " " + ex.Message,
            //         MessageDialogStyle.Affirmative);
            //    return;
            //}
            #endregion Public Key
        }
Beispiel #25
0
        internal void checkKeyUsage(
            int		id,
            byte[]	bytes)
        {
            string dump = "";

            try
            {
                X509Certificate cert = new X509CertificateParser().ReadCertificate(bytes);

                AsymmetricKeyParameter k = cert.GetPublicKey();

                if (cert.GetKeyUsage()[7])
                {
                    Fail("error generating cert - key usage wrong.");
                }

                // Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail(dump + SimpleTest.NewLine + Name + ": "+ id + " failed - exception " + e.Message, e);
            }

        }
Beispiel #26
0
        internal void checkSelfSignedCertificate(
            int     id,
            byte[]  bytes)
        {
            string dump = "";

            try
            {
                X509Certificate cert = new X509CertificateParser().ReadCertificate(bytes);

                AsymmetricKeyParameter k = cert.GetPublicKey();

                cert.Verify(k);
                // Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail(dump + SimpleTest.NewLine + Name + ": "+ id + " failed - exception " + e.Message, e);
            }
        }
Beispiel #27
0
        public void Button3Click(object sender, System.EventArgs e)
        {
            if (inputBox.Text != null)
            {
                string filePDF = inputBox.Text;
                try
                {
                    X509Certificate2 card = GetCertificate();
                    Org.BouncyCastle.X509.X509CertificateParser cp    = new Org.BouncyCastle.X509.X509CertificateParser();
                    Org.BouncyCastle.X509.X509Certificate[]     chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData) };

                    //ricreo il percorso con il nome del novo file

                    string    file      = filePDF.Substring(1 + filePDF.LastIndexOf(@"\")).ToLowerInvariant();
                    string    NuovoFile = filePDF.Substring(0, filePDF.LastIndexOf(@"\") + 1) + file.Substring(0, file.LastIndexOf(".")) + "_firmato.pdf".ToLowerInvariant();
                    PdfReader reader    = new PdfReader(filePDF);


                    PdfStamper             stp = PdfStamper.CreateSignature(reader, new FileStream(NuovoFile, FileMode.Create), '\0', null, multiSigChkBx.Checked);
                    PdfSignatureAppearance sap = stp.SignatureAppearance;

                    if (tsaCbx.Checked)
                    {
                        ITSAClient tsc = new TSAClientBouncyCastle(TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text);
                    }

                    if (SigVisible.Checked)
                    {
                        sap.Reason   = cbRagioneSingolo.Text;
                        sap.Contact  = Contacttext.Text;
                        sap.Location = Locationtext.Text;

                        if (sigImgBox.Image != null)
                        {
                            MemoryStream ms = new MemoryStream();
                            sigImgBox.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                            sap.Image = ms.ToArray() == null ? null : iTextSharp.text.Image.GetInstance(ms.ToArray());
                            ms.Close();
                        }
                        sap.SetVisibleSignature(new iTextSharp.text.Rectangle((float)sigPosX.Value,
                                                                              (float)sigPosY.Value,
                                                                              (float)sigPosX.Value + (float)sigWidth.Value,
                                                                              (float)sigPosY.Value + (float)sigHeight.Value),
                                                Convert.ToInt32(numberOfPagesUpDown.Value),
                                                null);
                    }

                    sap.SignDate = DateTime.Now;
                    sap.SetCrypto(null, chain, null, null);

                    sap.Acro6Layers = true;
                    sap.Render      = PdfSignatureAppearance.SignatureRender.Description;                //.NameAndDescription;
                    PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
                    dic.Date = new PdfDate(sap.SignDate);
                    dic.Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");

                    if (sap.Reason != null)
                    {
                        dic.Reason = sap.Reason;
                    }
                    if (sap.Location != null)
                    {
                        dic.Location = sap.Location;
                    }
                    if (sap.Contact != null)
                    {
                        dic.Contact = sap.Contact;
                    }
                    sap.CryptoDictionary = dic;
                    int contentEstimated          = 15000;
                    Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>();
                    exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
                    sap.PreClose(exc);
                    IDigest      messageDigest = DigestUtilities.GetDigest("SHA256");                //add
                    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);
                        messageDigest.BlockUpdate(buff, 0, read);                         //add
                    }
                    //--------------------------------------------
                    byte[] hash = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(hash, 0);
                    DateTime cal  = DateTime.Now;
                    byte[]   ocsp = null;
                    if (chain.Length >= 2)
                    {
                        String url = PdfPKCS7.GetOCSPURL(chain[0]);
                        if (url != null && url.Length > 0)
                        {
                            ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url);
                            MessageBox.Show(ocsp.ToString());
                        }
                    }

                    //-------------------------------------------------------------------
                    //TEST TIMESTAMP CON BOUNCYCASTLE
                    //-------------------------------------------------------------------

                    /*
                     * TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();
                     * // Dummy request
                     * TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, hash, BigInteger.ValueOf(100));
                     * byte[] reqData = request.GetEncoded();
                     * HttpWebRequest httpReq = (HttpWebRequest) WebRequest.Create("http://localhost:8080/signserver/process?workerId=1");
                     * httpReq.Method = "POST";
                     * httpReq.ContentType = "application/timestamp-query";
                     * httpReq.ContentLength = reqData.Length;
                     * // Write the request content
                     * Stream reqStream = httpReq.GetRequestStream();
                     * reqStream.Write(reqData, 0, reqData.Length);
                     * reqStream.Close();
                     * HttpWebResponse httpResp = (HttpWebResponse) httpReq.GetResponse();
                     * // Read the response
                     * Stream respStream = new BufferedStream(httpResp.GetResponseStream());
                     * TimeStampResponse response = new TimeStampResponse(respStream);
                     * respStream.Close();
                     * //MessageBox.Show(response.TimeStampToken.TimeStampInfo.GenTime.ToString());
                     */
                    //-------------------------------------------------------------------
                    //TEST TIMESTAMP CON BOUNCYCASTLE
                    //-------------------------------------------------------------------

                    //===================================QUI FIRMO
                    byte[] pk;
                    if (tsaCbx.Checked)
                    {
                        pk = SignMsg(ss.ToArray(), card, true, tsaCbx.Checked, TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text);
                    }
                    else
                    {
                        pk = SignMsg(ss.ToArray(), card, true, tsaCbx.Checked, "", "", "");
                    }
                    //--------------------------------------------
                    byte[] outc = new byte[contentEstimated];

                    PdfDictionary dic2 = new PdfDictionary();

                    Array.Copy(pk, 0, outc, 0, pk.Length);

                    dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
                    sap.Close(dic2);
                    MessageBox.Show("File firmato correttamente", "Operazione Completata");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
Beispiel #28
0
        /**
         * we Generate a self signed certificate for the sake of testing - DSA
         */
        internal void checkCreation2()
        {
            //
            // set up the keys
            //
            AsymmetricKeyParameter privKey;
            AsymmetricKeyParameter pubKey;

            try
            {
//				KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA", "SUN");
//				g.initialize(512, new SecureRandom());
//				KeyPair p = g.generateKeyPair();
                IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");
                DsaParametersGenerator dpg = new DsaParametersGenerator();
                dpg.Init(512, 25, new SecureRandom());
                g.Init(new DsaKeyGenerationParameters(new SecureRandom(), dpg.GenerateParameters()));
                AsymmetricCipherKeyPair p = g.GenerateKeyPair();

                privKey = p.Private;
                pubKey = p.Public;
            }
            catch (Exception e)
            {
                Fail("error setting up keys - " + e.ToString());
                return;
            }

            //
            // distinguished name table.
            //
            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            //
            // extensions
            //

            //
            // create the certificate - version 3
            //
            X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, values));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(ord, values));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("SHA1withDSA");

            try
            {
                X509Certificate cert = certGen.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

                // Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail("error setting generating cert - " + e.ToString());
            }

            //
            // create the certificate - version 1
            //
            X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator();

            certGen1.SetSerialNumber(BigInteger.One);
            certGen1.SetIssuerDN(new X509Name(ord, values));
            certGen1.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen1.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen1.SetSubjectDN(new X509Name(ord, values));
            certGen1.SetPublicKey(pubKey);
            certGen1.SetSignatureAlgorithm("SHA1withDSA");

            try
            {
                X509Certificate cert = certGen1.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

                //Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail("error setting generating cert - " + e.ToString());
            }

            //
            // exception test
            //
            try
            {
                certGen.SetPublicKey(dudPublicKey);

                Fail("key without encoding not detected in v1");
            }
            catch (ArgumentException)
            {
                // expected
            }
        }
        /**
         * Use this constructor if you want to verify a signature using
         * the sub-filter adbe.pkcs7.detached or adbe.pkcs7.sha1.
         * @param contentsKey the /Contents key
         * @param tsp set to true if there's a PAdES LTV time stamp.
         * @param provider the provider or <code>null</code> for the default provider
         */
        public PdfPKCS7(byte[] contentsKey, bool tsp)
        {
            isTsp = tsp;
            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(MessageLocalization.GetComposedMessage("can.t.decode.pkcs7signeddata.object"));
            }
            if (!(pkcs is Asn1Sequence)) {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence"));
            }
            Asn1Sequence signedData = (Asn1Sequence)pkcs;
            DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0];
            if (!objId.Id.Equals(SecurityIDs.ID_PKCS7_SIGNED_DATA))
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.signed.data"));
            Asn1Sequence content = (Asn1Sequence)((Asn1TaggedObject)signedData[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[0]).Value.IntValue;

            // the digestAlgorithms
            digestalgos = new Dictionary<string,object>();
            IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();
            while (e.MoveNext())
            {
                Asn1Sequence s = (Asn1Sequence)e.Current;
                DerObjectIdentifier o = (DerObjectIdentifier)s[0];
                digestalgos[o.Id] = null;
            }

            // the certificates and crls
            X509CertificateParser cf = new X509CertificateParser();
            certs = new List<X509Certificate>();
            foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) {
                certs.Add(cc);
            }
            crls = new List<X509Crl>();

            // the possible ID_PKCS7_DATA
            Asn1Sequence rsaData = (Asn1Sequence)content[2];
            if (rsaData.Count > 1) {
                Asn1OctetString rsaDataContent = (Asn1OctetString)((Asn1TaggedObject)rsaData[1]).GetObject();
                RSAdata = rsaDataContent.GetOctets();
            }

            // the signerInfos
            int next = 3;
            while (content[next] is Asn1TaggedObject)
                ++next;
            Asn1Set signerInfos = (Asn1Set)content[next];
            if (signerInfos.Count != 1)
                throw new ArgumentException(MessageLocalization.GetComposedMessage("this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time"));
            Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0];
            // the positions that we care are
            //     0 - version
            //     1 - the signing certificate issuer and serial number
            //     2 - the digest algorithm
            //     3 or 4 - digestEncryptionAlgorithm
            //     4 or 5 - encryptedDigest
            signerversion = ((DerInteger)signerInfo[0]).Value.IntValue;
            // Get the signing certificate
            Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];
            Org.BouncyCastle.Asn1.X509.X509Name issuer = Org.BouncyCastle.Asn1.X509.X509Name.GetInstance(issuerAndSerialNumber[0]);
            BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;
            foreach (X509Certificate cert in certs) {
                if (issuer.Equivalent(cert.IssuerDN) && serialNumber.Equals(cert.SerialNumber)) {
                    signCert = cert;
                    break;
                }
            }
            if (signCert == null) {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.find.signing.certificate.with.serial.1",
                    issuer.ToString() + " / " + serialNumber.ToString(16)));
            }
            CalcSignCertificateChain();
            digestAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
            next = 3;
            if (signerInfo[next] is Asn1TaggedObject) {
                Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
                Asn1Set sseq = Asn1Set.GetInstance(tagsig, false);
                sigAttr = sseq.GetEncoded(Asn1Encodable.Der);

                for (int k = 0; k < sseq.Count; ++k) {
                    Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
                    if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_MESSAGE_DIGEST)) {
                        Asn1Set sset = (Asn1Set)seq2[1];
                        digestAttr = ((DerOctetString)sset[0]).GetOctets();
                    }
                    else if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_ADBE_REVOCATION)) {
                        Asn1Set setout = (Asn1Set)seq2[1];
                        Asn1Sequence seqout = (Asn1Sequence)setout[0];
                        for (int j = 0; j < seqout.Count; ++j) {
                            Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j];
                            if (tg.TagNo == 1) {
                                Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                                FindOcsp(seqin);
                            }
                            if (tg.TagNo == 0) {
                                Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                                FindCRL(seqin);
                            }
                        }
                    }
                }
                if (digestAttr == null)
                    throw new ArgumentException(MessageLocalization.GetComposedMessage("authenticated.attribute.is.missing.the.digest"));
                ++next;
            }
            digestEncryptionAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
            digest = ((Asn1OctetString)signerInfo[next++]).GetOctets();
            if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject)) {
                Asn1TaggedObject taggedObject = (Asn1TaggedObject) signerInfo[next];
                Asn1Set unat = Asn1Set.GetInstance(taggedObject, false);
                Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat);
                Org.BouncyCastle.Asn1.Cms.Attribute ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken];
                if (ts != null && ts.AttrValues.Count > 0) {
                    Asn1Set attributeValues = ts.AttrValues;
                    Asn1Sequence tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]);
                    Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence);
                    this.timeStampToken = new TimeStampToken(contentInfo);
                }
            }
            if (isTsp) {
                Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfoTsp = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(signedData);
                this.timeStampToken = new TimeStampToken(contentInfoTsp);
                TimeStampTokenInfo info = timeStampToken.TimeStampInfo;
                String algOID = info.MessageImprintAlgOid;
                messageDigest = DigestUtilities.GetDigest(algOID);
            }
            else {
                if (RSAdata != null || digestAttr != null) {
                    messageDigest = GetHashClass();
                    encContDigest = GetHashClass();
                }
                sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
                sig.Init(false, signCert.GetPublicKey());
            }
        }
Beispiel #30
0
        /**
         * we Generate a self signed certificate for the sake of testing - SHA224withECDSA
         */
        private void createECCert(
            string				algorithm,
            DerObjectIdentifier	algOid)
        {
            FpCurve curve = new FpCurve(
                new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p)
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16),   // a
                new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16));  // b

            ECDomainParameters spec = new ECDomainParameters(
                curve,
//				curve.DecodePoint(Hex.Decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
                curve.DecodePoint(Hex.Decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n

            ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
//				curve.DecodePoint(Hex.Decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                spec);

//			//
//			// set up the keys
//			//
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;
//
//			KeyFactory fact = KeyFactory.GetInstance("ECDSA");
//
//			privKey = fact.generatePrivate(privKeySpec);
//			pubKey = fact.generatePublic(pubKeySpec);


            //
            // distinguished name table.
            //
            IDictionary attrs = new Hashtable();
            IList order = new ArrayList();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.E, "*****@*****.**");

            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.L);
            order.Add(X509Name.ST);
            order.Add(X509Name.E);

            //
            // create the certificate - version 3
            //
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(order, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(order, attrs));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm(algorithm);


            X509Certificate cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            X509CertificateParser fact = new X509CertificateParser();
            cert = fact.ReadCertificate(cert.GetEncoded());

            //
            // try with point compression turned off
            //
//			((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
            ECPoint q = pubKey.Q.Normalize();
            pubKey = new ECPublicKeyParameters(
                pubKey.AlgorithmName,
                q.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()),
                pubKey.Parameters);

            certGen.SetPublicKey(pubKey);

            cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            cert = fact.ReadCertificate(cert.GetEncoded());

            if (!cert.SigAlgOid.Equals(algOid.ToString()))
            {
                Fail("ECDSA oid incorrect.");
            }

            if (cert.GetSigAlgParams() != null)
            {
                Fail("sig parameters present");
            }

            ISigner sig = SignerUtilities.GetSigner(algorithm);

            sig.Init(false, pubKey);

            byte[] b = cert.GetTbsCertificate();
            sig.BlockUpdate(b, 0, b.Length);

            if (!sig.VerifySignature(cert.GetSignature()))
            {
                Fail("EC certificate signature not mapped correctly.");
            }
            // Console.WriteLine(cert);
        }
Beispiel #31
0
 public void Initialize()
 {
     // TODO lidiar cuando el usuario cancela el caudro de dialogo o se equivoca en la clave del token
     var tempcard = GetCertificate();
     otrosbytes = tempcard.Export(X509ContentType.SerializedCert);
     Card = new X509Certificate2(otrosbytes);
     Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
     Chain = new[] { cp.ReadCertificate(Card.RawData) };
 }
Beispiel #32
0
        private void doTestForgedSignature()
        {
            string cert = "MIIBsDCCAVoCAQYwDQYJKoZIhvcNAQEFBQAwYzELMAkGA1UEBhMCQVUxEzARBgNV"
                + "BAgTClF1ZWVuc2xhbmQxGjAYBgNVBAoTEUNyeXB0U29mdCBQdHkgTHRkMSMwIQYD"
                + "VQQDExpTZXJ2ZXIgdGVzdCBjZXJ0ICg1MTIgYml0KTAeFw0wNjA5MTEyMzU4NTVa"
                + "Fw0wNjEwMTEyMzU4NTVaMGMxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpRdWVlbnNs"
                + "YW5kMRowGAYDVQQKExFDcnlwdFNvZnQgUHR5IEx0ZDEjMCEGA1UEAxMaU2VydmVy"
                + "IHRlc3QgY2VydCAoNTEyIGJpdCkwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAn7PD"
                + "hCeV/xIxUg8V70YRxK2A5jZbD92A12GN4PxyRQk0/lVmRUNMaJdq/qigpd9feP/u"
                + "12S4PwTLb/8q/v657QIDAQABMA0GCSqGSIb3DQEBBQUAA0EAbynCRIlUQgaqyNgU"
                + "DF6P14yRKUtX8akOP2TwStaSiVf/akYqfLFm3UGka5XbPj4rifrZ0/sOoZEEBvHQ"
                + "e20sRA==";

            X509Certificate x509 = new X509CertificateParser().ReadCertificate(Base64.Decode(cert));

            try
            {
                x509.Verify(x509.GetPublicKey());

                Fail("forged RSA signature passed");
            }
            catch (Exception)
            {
                // expected
            }
        }
Beispiel #33
0
        /**
        * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
        * @param contentsKey the /Contents key
        * @param certsKey the /Cert key
        * @param provider the provider or <code>null</code> for the default provider
        */    
        public PdfPKCS7(byte[] contentsKey, byte[] certsKey) {

            X509CertificateParser cf = new X509CertificateParser();
            certs = new ArrayList();
            foreach (X509Certificate cc in cf.ReadCertificates(certsKey)) {
                certs.Add(cc);
            }
            signCerts = certs;
            signCert = (X509Certificate)certs[0];
            crls = new ArrayList();
            Asn1InputStream inp = new Asn1InputStream(new MemoryStream(contentsKey));
            digest = ((DerOctetString)inp.ReadObject()).GetOctets();
            sig = SignerUtilities.GetSigner("SHA1withRSA");
            sig.Init(false, signCert.GetPublicKey());
        }
Beispiel #34
0
        private void doTestNullDerNullCert()
        {
            AsymmetricCipherKeyPair keyPair = GenerateLongFixedKeys();

            AsymmetricKeyParameter pubKey = keyPair.Public;
            AsymmetricKeyParameter privKey = keyPair.Private;

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name("CN=Test"));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name("CN=Test"));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");
            X509Certificate cert = certGen.Generate(privKey);

            X509CertificateStructure certStruct = X509CertificateStructure.GetInstance(
                Asn1Object.FromByteArray(cert.GetEncoded()));

            Asn1Encodable tbsCertificate = certStruct.TbsCertificate;
            AlgorithmIdentifier sig = certStruct.SignatureAlgorithm;

            DerSequence seq = new DerSequence(
                tbsCertificate,
                new AlgorithmIdentifier(sig.Algorithm),
                certStruct.Signature);

            try
            {
                // verify
                byte[] encoded = seq.GetEncoded();
                X509CertificateParser fact = new X509CertificateParser();
                cert = fact.ReadCertificate(encoded);
                cert.Verify(cert.GetPublicKey());
            }
            catch (Exception e)
            {
                Fail("doTestNullDerNull failed - exception " + e.ToString(), e);
            }
        }
Beispiel #35
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[0];
     if (!objId.Id.Equals(ID_PKCS7_SIGNED_DATA))
         throw new ArgumentException("Not a valid PKCS#7 object - not signed data");
     Asn1Sequence content = (Asn1Sequence)((DerTaggedObject)signedData[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[0]).Value.IntValue;
     
     // the digestAlgorithms
     digestalgos = new Hashtable();
     IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();
     while (e.MoveNext())
     {
         Asn1Sequence s = (Asn1Sequence)e.Current;
         DerObjectIdentifier o = (DerObjectIdentifier)s[0];
         digestalgos[o.Id] = null;
     }
     
     // the certificates and crls
     X509CertificateParser cf = new X509CertificateParser();
     certs = new ArrayList();
     foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) {
         certs.Add(cc);
     }
     crls = new ArrayList();
     
     // the possible ID_PKCS7_DATA
     Asn1Sequence rsaData = (Asn1Sequence)content[2];
     if (rsaData.Count > 1) {
         DerOctetString rsaDataContent = (DerOctetString)((DerTaggedObject)rsaData[1]).GetObject();
         RSAdata = rsaDataContent.GetOctets();
     }
     
     // the signerInfos
     int next = 3;
     while (content[next] is DerTaggedObject)
         ++next;
     Asn1Set signerInfos = (Asn1Set)content[next];
     if (signerInfos.Count != 1)
         throw new ArgumentException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time");
     Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[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[0]).Value.IntValue;
     // Get the signing certificate
     Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];
     BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;
     foreach (X509Certificate cert in certs) {                                                            
         if (serialNumber.Equals(cert.SerialNumber)) {
             signCert = cert;                                                                             
             break;                                                                                            
         }                                                                                                
     }
     if (signCert == null) {
         throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16));
     }
     CalcSignCertificateChain();
     digestAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
     next = 3;
     if (signerInfo[next] is Asn1TaggedObject) {
         Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
         Asn1Set sseq = Asn1Set.GetInstance(tagsig, false);
         sigAttr = sseq.GetEncoded(Asn1Encodable.Der);
         
         for (int k = 0; k < sseq.Count; ++k) {
             Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
             if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_MESSAGE_DIGEST)) {
                 Asn1Set sset = (Asn1Set)seq2[1];
                 digestAttr = ((DerOctetString)sset[0]).GetOctets();
             }
             else if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_ADBE_REVOCATION)) {
                 Asn1Set setout = (Asn1Set)seq2[1];
                 Asn1Sequence seqout = (Asn1Sequence)setout[0];
                 for (int j = 0; j < seqout.Count; ++j) {
                     Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j];
                     if (tg.TagNo != 1)
                         continue;
                     Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                     FindOcsp(seqin);
                 }
             }
         }
         if (digestAttr == null)
             throw new ArgumentException("Authenticated attribute is missing the digest.");
         ++next;
     }
     digestEncryptionAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
     digest = ((DerOctetString)signerInfo[next++]).GetOctets();
     if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject)) {
         DerTaggedObject taggedObject = (DerTaggedObject) signerInfo[next];
         Asn1Set unat = Asn1Set.GetInstance(taggedObject, false);
         Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat);
         Org.BouncyCastle.Asn1.Cms.Attribute ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken];
         if (ts != null) {
             Asn1Set attributeValues = ts.AttrValues;
             Asn1Sequence tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]);
             Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence);
             this.timeStampToken = new TimeStampToken(contentInfo);
         }
     }
     if (RSAdata != null || digestAttr != null) {
         messageDigest = GetHashClass();
     }
     sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
     sig.Init(false, signCert.GetPublicKey());
 }
Beispiel #36
0
        public void SignDetached()
        {
            if (lb.Items.Count > 0)
            {
                try
                {
                    X509Certificate2 card = GetCertificate();
                    Org.BouncyCastle.X509.X509CertificateParser cp    = new Org.BouncyCastle.X509.X509CertificateParser();
                    Org.BouncyCastle.X509.X509Certificate[]     chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData) };
                    pb.Minimum = 0;
                    pb.Maximum = lb.Items.Count;
                    pb.Visible = true;

                    foreach (object oFile in lb.Items)
                    {
                        string    filePDF = oFile.ToString();
                        PdfReader reader = new PdfReader(filePDF);
                        int       Pagina = 1;
                        int       posX = 0, posY = 0, Altezza = 0, Larghezza = 0;
                        //ricreo il percorso con il nome del nuovo file
                        string                 file      = filePDF.Substring(1 + filePDF.LastIndexOf(@"\"));
                        string                 NuovoFile = filePDF.Substring(0, filePDF.LastIndexOf(@"\") + 1) + file.Substring(0, file.LastIndexOf(".")) + "_firmato.pdf";
                        PdfStamper             stp       = PdfStamper.CreateSignature(reader, new FileStream(NuovoFile, FileMode.Create), '\0', null, multiSigChkBx.Checked);
                        PdfSignatureAppearance sap       = stp.SignatureAppearance;

                        string nPagine = reader.NumberOfPages.ToString();
                        sap.Reason   = cbRagione.Text + nPagine;
                        sap.Contact  = tbContatto.Text;
                        sap.Location = tbLuogo.Text;
                        if (cbFirmaVisibile.Checked == true) //firma visibile
                        {
                            if (rbNuovaPagina.Checked)       //firma su nuova pagina
                            {
                                Pagina = reader.NumberOfPages + 1;
                                stp.InsertPage(Pagina, reader.GetPageSize(1));
                                iTextSharp.text.Rectangle rect = reader.GetPageSize(Pagina);
                                int w = Convert.ToInt32(rect.Width);
                                int h = Convert.ToInt32(rect.Height);
                                posX      = 20;
                                posY      = h - 120;
                                Larghezza = posX + 100;
                                Altezza   = posY + 100;
                            }
                            else if (rbVecchiaPagina.Checked)   //firma su pagina esistente
                            {
                                int IndiceScelto = lbPosizioneFirma.SelectedIndex;
                                int paginaScelta = (IndiceScelto <= 3) ? 1 : reader.NumberOfPages;
                                iTextSharp.text.Rectangle rect = reader.GetPageSize(paginaScelta);
                                int w = Convert.ToInt32(rect.Width);
                                int h = Convert.ToInt32(rect.Height);
                                Pagina = paginaScelta;

                                /* istruzioni:
                                 *  0 Prima Pagina in Alto a Sinistra
                                 *  1 Prima Pagina in Alto a Destra
                                 *  2 Prima Pagina in Basso a Sinistra
                                 *  3 Prima Pagina in Basso a Destra
                                 *  4 Ultima Pagina in Alto a Sinistra
                                 *  5 Ultima Pagina in Alto a Destra
                                 *  6 Ultima Pagina in Basso a Sinistra
                                 *  7 Ultima Pagina in Basso a Destra
                                 */
                                switch (IndiceScelto)
                                {
                                case 0:
                                default:
                                case 4:
                                    posX      = 20;
                                    posY      = h - 110;
                                    Larghezza = posX + 100;
                                    Altezza   = posY + 100;
                                    break;

                                case 1:
                                case 5:
                                    posX      = w - 110;
                                    posY      = h - 110;
                                    Larghezza = posX + 100;
                                    Altezza   = posY + 100;
                                    break;

                                case 2:
                                case 6:
                                    posX      = 20;
                                    posY      = 20;
                                    Larghezza = posX + 350;
                                    Altezza   = posY + 70;
                                    break;

                                case 3:
                                case 7:
                                    posX      = w - 110;
                                    posY      = 20;
                                    Larghezza = posX + 100;
                                    Altezza   = posY + 100;
                                    break;
                                }
                            }
                            sap.SetVisibleSignature(new iTextSharp.text.Rectangle(posX, posY, Larghezza, Altezza), Pagina, null);
                        }
                        sap.SignDate = DateTime.Now;
                        sap.SetCrypto(null, chain, null, null);

                        sap.Acro6Layers = true;
                        sap.Render      = PdfSignatureAppearance.SignatureRender.Description; //.NameAndDescription;
                        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
                        dic.Date        = new PdfDate(sap.SignDate);
                        dic.Name        = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
                        sap.Layer2Text  = "Firmato Digitalmente da: " + PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
                        sap.Layer2Text += "\r\nData: " + sap.SignDate;
                        sap.Layer2Text += "\r\nRagione: " + sap.Reason;
                        if (sap.Reason != null)
                        {
                            dic.Reason = sap.Reason;
                        }
                        if (sap.Location != null)
                        {
                            dic.Location = sap.Location;
                        }
                        if (sap.Contact != null)
                        {
                            dic.Contact = sap.Contact;
                        }
                        sap.CryptoDictionary = dic;
                        int contentEstimated          = 56000;
                        Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>();
                        exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
                        sap.PreClose(exc);

                        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);
                        }
                        byte[] pk;
                        if (tsaCbx.Checked)                          //ss.ToArray()
                        {
                            pk = SignMsg(ss.ToArray(), card, true, tsaCbx.Checked, TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text);
                        }
                        else
                        {
                            pk = SignMsg(ss.ToArray(), card, true, false, "", "", "");
                        }
                        byte[] outc = new byte[contentEstimated];

                        PdfDictionary dic2 = new PdfDictionary();

                        Array.Copy(pk, 0, outc, 0, pk.Length);

                        dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
                        sap.Close(dic2);
                        //avanzo di 1 la progress bar
                        pb.Increment(1);
                    }
                    MessageBox.Show(pb.Maximum.ToString() + " file firmati correttamente", "Operazione Completata");
                    pb.Visible = false;
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.ToString(), "Messaggio dal Sistema Windows");
                    pb.Visible = false;
                }
            }
        }
Beispiel #37
0
        private static AsymmetricKeyParameter retornaParametrosCertificado(string caminhoCertificado)
        {
            try
            {
                X509Certificate2 chaveCertificada = new X509Certificate2(caminhoCertificado);
                X509CertificateParser parserChaveCertificada = new X509CertificateParser();
                AsymmetricKeyParameter parametrosCertificado = parserChaveCertificada.ReadCertificate(chaveCertificada.GetRawCertData()).GetPublicKey();

                return parametrosCertificado;
            }
            catch (Exception ex)
            {
                throw new excecao.excecao(MSG_CHAVE_INVALIDA);
            }
        }