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"); } }
/// <summary> /// Converts raw certificate data to the instance of BouncyCastle X509Certificate class /// </summary> /// <param name="data">Raw certificate data</param> /// <returns>Instance of BouncyCastle X509Certificate class</returns> public static BCX509.X509Certificate ToBouncyCastleObject(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } BCX509.X509Certificate bcCert = _x509CertificateParser.ReadCertificate(data); if (bcCert == null) { throw new CryptographicException("Cannot find the requested object."); } return(bcCert); }
/// <summary> /// Converts raw certificate data to the instance of BouncyCastle X509Certificate class /// </summary> /// <param name="data">Raw certificate data</param> /// <returns>Instance of BouncyCastle X509Certificate class</returns> public static BCX509.X509Certificate ToBouncyCastleObject(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } BCX509.X509Certificate bcCert = _x509CertificateParser.ReadCertificate(data); if (bcCert == null) { throw new Exception("Provided data do not represent X.509 certificate"); } return(bcCert); }
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; }
/// <summary> /// Signs a PDF document using iTextSharp library /// </summary> /// <param name="sourceDocument">The path of the source pdf document which is to be signed</param> /// <param name="reason">String describing the reason for signing, would be embedded as part of the signature</param> /// <param name="location">Location where the document was signed, would be embedded as part of the signature</param> public static byte[] SignPdfFile(byte[] sourceDocument, string reason, string location) { var cert = DigitalSignature.GetStoreCertificate(); var cp = new Org.BouncyCastle.X509.X509CertificateParser(); var pdfCert = cp.ReadCertificate(cert.RawData); var certChain = new[] { pdfCert }; // reader and stamper PdfReader reader = new PdfReader(sourceDocument); using (MemoryStream fout = new MemoryStream()) { using (PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0')) { // appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; var rect = reader.GetPageSize(1); appearance.SetVisibleSignature(new Rectangle(rect.Width - 128, rect.Height - 78, rect.Width - 10, rect.Height - 20), 1, null); // digital signature IExternalSignature es = new X509Certificate2Signature(cert, "SHA1"); MakeSignature.SignDetached(appearance, es, certChain, null, null, null, 0, CryptoStandard.CMS); stamper.Close(); } return(fout.ToArray()); } }
/// <summary> /// Load a certificate from an OpenSSL style file (PEM or DER) /// </summary> /// <param name="file">The file to load</param> /// <returns>The certificate, null if the file wasn't a certificate</returns> public static X509Certificate2 LoadCertFromOpenSslFile(string file) { X509Certificate2 ret = null; try { using (Stream stm = File.OpenRead(file)) { X509.X509CertificateParser parser = new X509.X509CertificateParser(); X509.X509Certificate cert = parser.ReadCertificate(stm); if (cert != null) { ret = new X509Certificate2(cert.GetEncoded(), (string)null, X509KeyStorageFlags.Exportable); } else { throw new CryptographicException("Invalid OpenSSL Certificate"); } } } catch (CertificateException ex) { throw new CryptographicException(ex.Message, ex); } return(ret); }
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(); } } }
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; }
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 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> /// 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); }
/// <summary> /// RSA解密 /// </summary> /// <param name="pCerFilePath">cer证书文件路径</param> /// <param name="pDecryptContent">需要解密的内容</param> /// <returns></returns> public static byte[] RSADecrypt(string pCerFilePath, byte[] pDecryptContent) { using (FileStream fs = new FileStream(pCerFilePath, FileMode.Open)) { Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(fs) }; IAsymmetricBlockCipher eng = new Pkcs1Encoding(new RsaEngine()); eng.Init(false, chain[0].GetPublicKey()); var result = eng.ProcessBlock(pDecryptContent, 0, pDecryptContent.Length); // return(result); } }
static public string GetIssuerFields(byte[] cert, string field) { Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert) }; if (chain[0] != null) { return(PdfPKCS7.GetIssuerFields(chain[0]).GetField(field)); } return(string.Empty); }
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; }
public static void AddCertificate(byte[] certData) { try { var parser = new Org.BouncyCastle.X509.X509CertificateParser(); var cert = parser.ReadCertificate(certData); if (cert != null) { EB.Debug.Log("Adding cert " + cert.SubjectDN.ToString()); _validCerts.Add(Encoding.ToBase64String(cert.GetEncoded())); } } catch (System.Exception ex) { EB.Debug.LogError("Failed to load certificate! " + ex); } }
/// <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); } }
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(); }
static X509Certificate DecodeCertificate (IDataRecord reader, X509CertificateParser parser, int column, ref byte[] buffer) { int nread = ReadBinaryBlob (reader, column, ref buffer); using (var memory = new MemoryStream (buffer, 0, nread, false)) { return parser.ReadCertificate (memory); } }
public static RawRegisterResponse FromBase64(String rawDataBase64) { byte[] bytes = Utils.Base64StringToByteArray(rawDataBase64); Stream stream = new MemoryStream(bytes); BinaryReader binaryReader = new BinaryReader(stream); try { byte reservedByte = binaryReader.ReadByte(); if (reservedByte != RegistrationReservedByteValue) { throw new U2fException(String.Format("Incorrect value of reserved byte. Expected: {0}. Was: {1}", RegistrationReservedByteValue, reservedByte)); } byte[] publicKey = binaryReader.ReadBytes(65); byte[] keyHandle = binaryReader.ReadBytes(binaryReader.ReadByte()); X509CertificateParser x509CertificateParser = new X509CertificateParser(); X509Certificate attestationCertificate = x509CertificateParser.ReadCertificate(stream); int size = (int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position); byte[] signature = binaryReader.ReadBytes(size); RawRegisterResponse rawRegisterResponse = new RawRegisterResponse( publicKey, keyHandle, attestationCertificate, signature); return rawRegisterResponse; } catch (CertificateException e) { throw new U2fException("Error when parsing attestation certificate", e); } finally { stream.Dispose(); binaryReader.Dispose(); } }
public string CertificateToString(Certificate cert) { var certParser = new X509CertificateParser(); var x509 = certParser.ReadCertificate(cert.certificate.data); return x509.ToString(); }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsRecipient"/> class. /// </summary> /// <remarks> /// <para>Creates a new <see cref="CmsRecipient"/>, loading the certificate from the specified stream.</para> /// <para>The initial value of the <see cref="EncryptionAlgorithms"/> property will be set to /// the Triple-DES encryption algorithm, which should be safe to assume for all modern /// S/MIME v3.x client implementations.</para> /// </remarks> /// <param name="stream">The stream containing the recipient's certificate.</param> /// <param name="recipientIdentifierType">The recipient identifier type.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public CmsRecipient (Stream stream, SubjectIdentifierType recipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber) { if (stream == null) throw new ArgumentNullException (nameof (stream)); if (recipientIdentifierType == SubjectIdentifierType.IssuerAndSerialNumber) RecipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber; else RecipientIdentifierType = SubjectIdentifierType.SubjectKeyIdentifier; var parser = new X509CertificateParser (); EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.TripleDes }; RecipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber; Certificate = parser.ReadCertificate (stream); }
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(); }
/// <summary> /// Validate a certificate against its AIA OCSP. /// </summary> /// <param name="cert"></param> /// <param name="aia"></param> /// <returns></returns> CertStatus Validate(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, AIA aia) { string hash = ComputeSHA1(System.Text.ASCIIEncoding.ASCII.GetBytes(aia.Issuer)); string filePath = IssuerCachedFolder + hash; //Check if aki is cached if (!IsIssuerCached(aia.Issuer)) { Download(aia.Issuer, filePath); if (!IsIssuerCached(aia.Issuer)) { return(CertStatus.Unknown(CertStatus.BadIssuer)); } } var issuerTemp = new System.Security.Cryptography.X509Certificates.X509Certificate2(filePath); var certParser = new Org.BouncyCastle.X509.X509CertificateParser(); var issuer = certParser.ReadCertificate(issuerTemp.RawData); var cert2Validate = certParser.ReadCertificate(cert.RawData); var id = new Org.BouncyCastle.Ocsp.CertificateID( Org.BouncyCastle.Ocsp.CertificateID.HashSha1, issuer, cert2Validate.SerialNumber); byte[] reqEnc = GenerateOCSPRequest(id, cert2Validate); byte[] resp = GetOCSPResponse(aia.Ocsp, reqEnc); //Extract the response OcspResp ocspResponse = new OcspResp(resp); BasicOcspResp basicOCSPResponse = (BasicOcspResp)ocspResponse.GetResponseObject(); SingleResp singResp = basicOCSPResponse.Responses[0]; //Validate ID var expectedId = singResp.GetCertID(); if (!expectedId.SerialNumber.Equals(id.SerialNumber)) { return(CertStatus.Unknown(CertStatus.BadSerial)); } if (!Org.BouncyCastle.Utilities.Arrays.AreEqual(expectedId.GetIssuerNameHash(), id.GetIssuerNameHash())) { return(CertStatus.Unknown(CertStatus.IssuerNotMatch)); } //Extract Status var certificateStatus = singResp.GetCertStatus(); if (certificateStatus == null) { return(CertStatus.Good); } if (certificateStatus is Org.BouncyCastle.Ocsp.RevokedStatus) { int revocationReason = ((Org.BouncyCastle.Ocsp.RevokedStatus)certificateStatus).RevocationReason; var revocationDate = ((Org.BouncyCastle.Ocsp.RevokedStatus)certificateStatus).RevocationTime; return(CertStatus.Revoked(revocationDate.ToString("o"), revocationReason)); } if (certificateStatus is Org.BouncyCastle.Ocsp.UnknownStatus) { return(CertStatus.Unknown()); } return(CertStatus.Unknown()); }
// metodo principal para el procesamiento de pdfs (firma digital adjuntos metadatos) public string SignPdf( SignRenderingMode signRenderingMode, Funciones.Archivos.Pdf.Dtos.PdfSign.PdfSignRequestDto jsonToProcess, string path) { try { //var json = File.ReadAllText(path); //var jsonToProcess = JsonConvert //.DeserializeObject<Funciones.Archivos.Pdf.Dtos.PdfSign.PdfSignRequestDto>(json.Replace("<EOF>", "")); _target = jsonToProcess.outPath; _fs = GetPdfStreamFormUrlOrBase64(jsonToProcess.dataUriBase64PdfToSign); // conversor de certificados var objCP = new BcX509.X509CertificateParser(); var crlList = new List <ICrlClient>(); // buscar el certificado por numero serial var certificate = SearchCertificate(jsonToProcess.certificateSerialNumber); if (certificate == null) { return("No se encontraron certificados para el serial: " + jsonToProcess.certificateSerialNumber); } // definicion del certificado operable var objChain = new BcX509.X509Certificate[] { objCP.ReadCertificate(certificate.RawData) }; crlList.Add(new CrlClientOnline(objChain)); //TODO: habilitar la estampa cronologica (Error) (verificar tsa Timestamping Authority) // agregamos la estampa cronologica #region estampa cronologica ITSAClient tsaClient = null; IOcspClient ocspClient = null; if (jsonToProcess.addTimeStamp) { ocspClient = new OcspClientBouncyCastle(); //CertificateUtil.getTSAURL(Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(certificate)); tsaClient = new TSAClientBouncyCastle(jsonToProcess.urlTSA); } #endregion estampa cronologica // cargue del pdf al lector de itextsharp var _pdfReader = new PdfReader(_fs); // cargue an memoria del pdf using (var _wfs = new MemoryStream()) { // creacion de la firma a partir del lector itextsharp y el pdf en memoria using (var objStamper = PdfStamper.CreateSignature(_pdfReader, _wfs, '\0', null, true)) { // Procesar adjuntos var attachmentIndex = 1; (jsonToProcess.dataUriBase64ListOfPdfToAttach as List <FileToAttachDto>).ForEach( (item) => { //TODO: verificar si no se va a necesitar if (!item.pathOrDataUriBase64.StartsWith("data:")) { var pfs = PdfFileSpecification.FileEmbedded(objStamper.Writer, item.fileDescription, attachmentIndex + "_" + item.fileDescription + ".pdf", null, true); objStamper.Writer.AddFileAttachment("Adjunto número: " + attachmentIndex, pfs); } else { try { var x = StreamToByteArray(GetPdfStreamFormUrlOrBase64(item.pathOrDataUriBase64)); var pfs = PdfFileSpecification.FileEmbedded( objStamper.Writer, item.fileDescription + ".pdf", item.fileDescription + ".pdf", x, true, item.mimeType, null ); objStamper.Writer.AddFileAttachment("Adjunto número: " + attachmentIndex, pfs); //.AddFileAttachment("adjunto número: " + attachmentIndex, x, "adjunto_" + attachmentIndex + ".pdf", "adjunto " + attachmentIndex); } catch (Exception exce) { Console.WriteLine(exce.StackTrace); } } attachmentIndex++; }); // definicion de la apariencia de la firma var signatureAppearance = objStamper.SignatureAppearance; // definicion del enum itextsharp a partir del enum parametro local var mode = Enum.Parse(typeof(RenderingMode), signRenderingMode.ToString()); signatureAppearance.SignatureRenderingMode = (RenderingMode)mode; signatureAppearance.Reason = jsonToProcess.reasonToSign; signatureAppearance.Location = jsonToProcess.locationDescription; // agregar marca visual de firma digital #region agregar marca visual firma digital if (jsonToProcess.addVisibleSignMark) { // definicion de imagen desde ruta o base64 signatureAppearance.SignatureGraphic = GetImageFormUrlOrBase64(jsonToProcess.dataUriBase64SignImage); // definicion de la firma digital visible signatureAppearance.SetVisibleSignature( new Rectangle(jsonToProcess.visibleSignMarkWidth, jsonToProcess.visibleSignMarkHeight, jsonToProcess.xVisibleSignMarkPosition, jsonToProcess.yVisibleSignMarkPosition), _pdfReader.NumberOfPages, jsonToProcess.visibleSignText); } #endregion agregar marca visual firma digital // Agregar propiedades extendidas objStamper.MoreInfo = (jsonToProcess.metadata as List <MetadataDto>).ToDictionary(x => x.key, x => x.value); //TODO: verificar si no es necesario la utilizacion de XMP manual (actualmente funciona) #region xmp implementacion manual /* objStamper.Writer.CreateXmpMetadata(); * var xmp = objStamper.Writer.XmpMetadata; * * * //XMP metadatos * IXmpMeta xmp; * using (var stream = File.OpenRead(@"C:\Users\danie\OneDrive\Escritorio\xmpMetadata.xml")) * xmp = XmpMetaFactory.Parse(stream); * * foreach (var property in xmp.Properties) * { * Console.WriteLine($"Path={property.Path} Namespace={property.Namespace} Value={property.Value}"); * } * * var serializeOptions = new SerializeOptions(); * serializeOptions.UsePlainXmp = true; * var newMetadata = XmpMetaFactory.SerializeToBuffer(xmp, serializeOptions); * objStamper.XmpMetadata = newMetadata;*/ #endregion xmp implementacion manual // Firmar digitalmente var externalSignature = new X509Certificate2Signature(certificate, jsonToProcess.certificateHashAlgorithm); MakeSignature.SignDetached(signatureAppearance, externalSignature, objChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS); } var pdfFileTocreate = jsonToProcess.outPath.Replace("json", "pdf"); System.IO.File.WriteAllBytes(pdfFileTocreate, _wfs.ToArray()); Process.Start(pdfFileTocreate); return(Convert.ToBase64String(_wfs.ToArray())); } } catch (Exception exce) { WriteToFile(exce.StackTrace); WriteToFile(exce.Message); return(exce.Message); } }
/// <summary> /// Формирование сигнатуры для серверной подписи /// </summary> /// <param name="alg"></param> /// <param name="data"></param> /// <param name="detached"></param> /// <returns></returns> public static byte[] ComputeSignature(Gost3410 alg, byte[] data, bool detached = true) { var certBytes = alg.ContainerCertificateRaw; var _x509CertificateParser = new BCX509.X509CertificateParser(); var bcCert = _x509CertificateParser.ReadCertificate(certBytes); ICollection <BCX509.X509Certificate> certPath = new List <BCX509.X509Certificate>(); certPath.Add(bcCert); IDigest digest; string hashOid; string signOid; if (GostCryptoConfig.ProviderType == ProviderTypes.CryptoPro256) { digest = new GOST3411_2012_256Digest(); signOid = Constants.OID_GR3410_12_256; hashOid = Constants.OID_GR3411_12_256; } else if (GostCryptoConfig.ProviderType == ProviderTypes.CryptoPro512) { digest = new GOST3411_2012_512Digest(); signOid = Constants.OID_GR3410_12_512; hashOid = Constants.OID_GR3411_12_512; } else { digest = new Gost3411Digest(); signOid = Constants.OID_GR3410_2001; hashOid = Constants.OID_GR3411_2001; } byte[] dataHash = ComputeDigest(digest, data); // Construct SignerInfo.signedAttrs Asn1EncodableVector signedAttributesVector = new Asn1EncodableVector(); // Add PKCS#9 contentType signed attribute signedAttributesVector.Add( new Org.BouncyCastle.Asn1.Cms.Attribute( new DerObjectIdentifier(Constants.szOID_RSA_contentType), new DerSet(new DerObjectIdentifier(Constants.szOID_RSA_data)))); // Add PKCS#9 messageDigest signed attribute signedAttributesVector.Add( new Org.BouncyCastle.Asn1.Cms.Attribute( new DerObjectIdentifier(Constants.szOID_RSA_messageDigest), new DerSet(new DerOctetString(dataHash)))); // Add PKCS#9 signingTime signed attribute signedAttributesVector.Add( new Org.BouncyCastle.Asn1.Cms.Attribute( new DerObjectIdentifier(Constants.szOID_RSA_signingTime), new DerSet(new Org.BouncyCastle.Asn1.Cms.Time(new DerUtcTime(DateTime.UtcNow))))); DerSet signedAttributes = new DerSet(signedAttributesVector); byte[] pkcs1Digest = ComputeDigest(digest, signedAttributes.GetDerEncoded()); //byte[] pkcs1DigestInfo = CreateDigestInfo(pkcs1Digest, hashOid); var formatter = new GostSignatureFormatter(alg); var signature = formatter.CreateSignature(pkcs1Digest); // Construct SignerInfo SignerInfo signerInfo = new SignerInfo( new SignerIdentifier(new IssuerAndSerialNumber(bcCert.IssuerDN, bcCert.SerialNumber)), new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null), signedAttributes, new AlgorithmIdentifier(new DerObjectIdentifier(signOid), null), new DerOctetString(signature), null); // Construct SignedData.digestAlgorithms Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector(); digestAlgorithmsVector.Add(new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null)); // Construct SignedData.encapContentInfo ContentInfo encapContentInfo = new ContentInfo( new DerObjectIdentifier(Constants.szOID_RSA_data), (detached) ? null : new DerOctetString(data)); // Construct SignedData.certificates Asn1EncodableVector certificatesVector = new Asn1EncodableVector(); foreach (BCX509.X509Certificate cert in certPath) { certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded()))); } // Construct SignedData.signerInfos Asn1EncodableVector signerInfosVector = new Asn1EncodableVector(); signerInfosVector.Add(signerInfo.ToAsn1Object()); // Construct SignedData SignedData signedData = new SignedData( new DerSet(digestAlgorithmsVector), encapContentInfo, new BerSet(certificatesVector), null, new DerSet(signerInfosVector)); // Construct top level ContentInfo ContentInfo contentInfo = new ContentInfo( new DerObjectIdentifier(Constants.szOID_RSA_signedData), signedData); return(contentInfo.GetDerEncoded()); }
/** * 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."); } }
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); } }
// : base("X.509") /** * Creates a CertPath of the specified type. * This constructor is protected because most users should use * a CertificateFactory to create CertPaths. * * @param type the standard name of the type of Certificatesin this path **/ public PkixCertPath( Stream inStream, String encoding) { try { if (encoding.ToUpper().Equals("PkiPath".ToUpper())) { Asn1InputStream derInStream = new Asn1InputStream(inStream); Asn1Object derObject = derInStream.ReadObject(); if (!(derObject is Asn1Sequence)) { throw new CertificateException( "input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath"); } IEnumerator e = ((Asn1Sequence)derObject).GetEnumerator(); Stream certInStream; MemoryStream outStream; DerOutputStream derOutStream; certificates = new ArrayList(); while (e.MoveNext()) { outStream = new MemoryStream(); derOutStream = new DerOutputStream(outStream); derOutStream.WriteObject((Asn1Encodable)e.Current); derOutStream.Close(); certInStream = new MemoryStream(outStream.ToArray(), false); certificates.Insert(0, new X509CertificateParser().ReadCertificate(certInStream)); } } else if (encoding.ToUpper().Equals("PKCS7") || encoding.ToUpper().Equals("PEM")) { inStream = new BufferedStream(inStream); certificates = new ArrayList(); X509CertificateParser certParser = new X509CertificateParser(); X509Certificate cert = null; while ((cert = certParser.ReadCertificate(inStream)) != null) { certificates.Add(cert); } } else { throw new CertificateException("unsupported encoding: " + encoding); } } catch (IOException ex) { throw new CertificateException( "IOException throw while decoding CertPath:\n" + ex.ToString()); } this.certificates = SortCerts(certificates); }
private void btnSign_Click(object sender, EventArgs e) { try { // Set wait cursor this.Cursor = Cursors.WaitCursor; Application.DoEvents(); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); // Get signature certificate for current citizen X509Certificate2Collection certsToShow = store.Certificates.Find(X509FindType.FindBySubjectName, "Assinatura", false); X509Certificate2Collection certs = certsToShow.Find(X509FindType.FindBySubjectName, "BI" + txtIdNumber.Text, false); if (certs.Count <= 0) { MessageBox.Show("Certificate not found.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } var cert = certs[0]; if (cert != null) { // Sign every file found on listbox foreach (string file in lbFilesToSign.Items) { try { // Get source folder and source filename string sourceFolder = Path.GetDirectoryName(file); string filename = Path.GetFileName(file); lblStatus.Text = "A assinar o file " + filename; // Create "Signed" sub-folder if doesn't exists string signedFolder = Path.Combine(sourceFolder, "Signed"); if (!Directory.Exists(signedFolder)) { Directory.CreateDirectory(signedFolder); } // Generate destination path for signed file var signedFile = signedFolder + "/" + filename; // Convert X509Certificate2 to X509Certificate X509CertificateParser certParse = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { certParse.ReadCertificate(cert.RawData) }; // Reader and stamper PdfReader pdfReader = new PdfReader(file); Stream signedPdf = new FileStream(signedFile, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', null, cbMultiSign.Checked); // Appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.SignatureCreator = "PDF Signer 1.0"; if (txtReason.Text != "") { appearance.Reason = txtReason.Text; } if (txtLocation.Text != "") { appearance.Location = txtLocation.Text; } // Timestamp TSAClientBouncyCastle tsc = null; if (cbSignWithTSA.Checked == true) { tsc = new TSAClientBouncyCastle("http://ts.cartaodecidadao.pt/tsa/server", "", ""); } // Digital signature X509Certificate2Signature externalSignature = new X509Certificate2Signature(cert, "SHA-1"); MakeSignature.SignDetached(appearance, externalSignature, chain, null, null, tsc, 0, CryptoStandard.CMS); stamper.Close(); } catch (System.IO.IOException) { MessageBox.Show("File not found", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } // Remove all files from listbox lbFilesToSign.Items.Clear(); btnRemoveFile.Enabled = false; btnSignNow.Enabled = false; MessageBox.Show("You have successfully signed the document(s)", "Success!"); } else { MessageBox.Show("Certificate not found.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } catch (System.Security.Cryptography.CryptographicException) { } catch (System.Net.WebException) { MessageBox.Show("You must have an internet connection to use timestamp server.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception) { MessageBox.Show("Oops.. Something wrong.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } finally { // Set default cursor this.Cursor = Cursors.Default; if (lblStatus.Text.Contains("A assinar o file")) { lblStatus.Text = "Card Inserted."; } } }
private void doTestCertWithBaseCertificateID() { IX509AttributeCertificate attrCert = new X509V2AttributeCertificate(certWithBaseCertificateID); X509CertificateParser fact = new X509CertificateParser(); X509Certificate cert = fact.ReadCertificate(holderCertWithBaseCertificateID); AttributeCertificateHolder holder = attrCert.Holder; if (holder.GetEntityNames() != null) { Fail("entity names set when none expected"); } if (!holder.SerialNumber.Equals(cert.SerialNumber)) { Fail("holder serial number doesn't Match"); } if (!holder.GetIssuer()[0].Equivalent(cert.IssuerDN)) { Fail("holder issuer doesn't Match"); } if (!holder.Match(cert)) { Fail("holder not matching holder certificate"); } if (!holder.Equals(holder.Clone())) { Fail("holder clone test failed"); } if (!attrCert.Issuer.Equals(attrCert.Issuer.Clone())) { Fail("issuer clone test failed"); } equalityAndHashCodeTest(attrCert, certWithBaseCertificateID); }
static IEnumerable<Org.BouncyCastle.X509.X509Certificate> BuildCertificateChainBC(byte[] primary, IEnumerable<byte[]> additional) { X509CertificateParser parser = new X509CertificateParser(); PkixCertPathBuilder builder = new PkixCertPathBuilder(); // Separate root from itermediate var intermediateCerts = new List<Org.BouncyCastle.X509.X509Certificate>(); HashSet rootCerts = new HashSet(); foreach (byte[] cert in additional) { var x509Cert = parser.ReadCertificate(cert); // Separate root and subordinate certificates if (x509Cert.IssuerDN.Equivalent(x509Cert.SubjectDN)) rootCerts.Add(new TrustAnchor(x509Cert, null)); else intermediateCerts.Add(x509Cert); } // Create chain for this certificate X509CertStoreSelector holder = new X509CertStoreSelector(); holder.Certificate = parser.ReadCertificate(primary); // WITHOUT THIS LINE BUILDER CANNOT BEGIN BUILDING THE CHAIN intermediateCerts.Add(holder.Certificate); PkixBuilderParameters builderParams = new PkixBuilderParameters(rootCerts, holder); builderParams.IsRevocationEnabled = false; X509CollectionStoreParameters intermediateStoreParameters = new X509CollectionStoreParameters(intermediateCerts); builderParams.AddStore(X509StoreFactory.Create( "Certificate/Collection", intermediateStoreParameters)); PkixCertPathBuilderResult result = builder.Build(builderParams); return result.CertPath.Certificates.Cast<Org.BouncyCastle.X509.X509Certificate>(); }
private void doTestGenerateWithPrincipal() { X509CertificateParser fact = new X509CertificateParser(); X509Certificate iCert = fact.ReadCertificate(signCert); // // a sample key pair. // RsaKeyParameters pubKey = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); // // set up the keys // // PrivateKey privKey; // PublicKey pubKey; // // KeyFactory kFact = KeyFactory.getInstance("RSA"); // // privKey = kFact.generatePrivate(RSA_PRIVATE_KEY_SPEC); // pubKey = kFact.generatePublic(pubKeySpec); AsymmetricKeyParameter privKey = RSA_PRIVATE_KEY_SPEC; X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator(); // the actual attributes GeneralName roleName = new GeneralName(GeneralName.Rfc822Name, "DAU123456789"); // roleSyntax OID: 2.5.24.72 X509Attribute attributes = new X509Attribute("2.5.24.72", new DerSequence(roleName)); gen.AddAttribute(attributes); gen.SetHolder(new AttributeCertificateHolder(iCert.SubjectDN)); 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"); IX509AttributeCertificate aCert = gen.Generate(privKey); aCert.CheckValidity(); aCert.Verify(pubKey); AttributeCertificateHolder holder = aCert.Holder; if (holder.GetEntityNames() == null) { Fail("entity names not set when expected"); } if (holder.SerialNumber != null) { Fail("holder serial number found when none expected"); } if (holder.GetIssuer() != null) { Fail("holder issuer found when none expected"); } if (!holder.Match(iCert)) { Fail("generated holder not matching holder certificate"); } X509Certificate sCert = fact.ReadCertificate(holderCertWithBaseCertificateID); if (holder.Match(sCert)) { Fail("principal generated holder matching wrong certificate"); } equalityAndHashCodeTest(aCert, aCert.GetEncoded()); }
public static X509Certificate ParseCertificate(byte[] encodedDerCertificate) { var parser = new X509CertificateParser(); return parser.ReadCertificate(encodedDerCertificate); }
public override void PerformTest() { IX509AttributeCertificate aCert = new X509V2AttributeCertificate(attrCert); X509CertificateParser fact = new X509CertificateParser(); X509Certificate sCert = fact.ReadCertificate(signCert); aCert.Verify(sCert.GetPublicKey()); // // search test // IList list = new ArrayList(); list.Add(sCert); // CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); // CertStore store = CertStore.getInstance("Collection", ccsp); IX509Store store = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(list)); ArrayList certs = new ArrayList( // store.getCertificates(aCert.getIssuer())); store.GetMatches(aCert.Issuer)); if (certs.Count != 1 || !certs.Contains(sCert)) { Fail("sCert not found by issuer"); } X509Attribute[] attrs = aCert.GetAttributes("1.3.6.1.4.1.6760.8.1.1"); if (attrs == null || attrs.Length != 1) { Fail("attribute not found"); } // // reencode test // aCert = new X509V2AttributeCertificate(aCert.GetEncoded()); aCert.Verify(sCert.GetPublicKey()); IX509AttributeCertificate saCert = new X509V2AttributeCertificate(aCert.GetEncoded()); if (!aCert.NotAfter.Equals(saCert.NotAfter)) { Fail("failed date comparison"); } // base generator test // // a sample key pair. // RsaKeyParameters pubKey = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); AsymmetricKeyParameter privKey = RSA_PRIVATE_KEY_SPEC; // // set up the keys // // PrivateKey privKey; // PublicKey pubKey; // // KeyFactory kFact = KeyFactory.getInstance("RSA"); // // privKey = kFact.generatePrivate(privKeySpec); // pubKey = kFact.generatePublic(pubKeySpec); X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator(); gen.AddAttribute(attrs[0]); gen.SetHolder(aCert.Holder); gen.SetIssuer(aCert.Issuer); gen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); gen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); gen.SetSerialNumber(aCert.SerialNumber); gen.SetSignatureAlgorithm("SHA1WithRSAEncryption"); aCert = gen.Generate(privKey); aCert.CheckValidity(); aCert.Verify(pubKey); // as the issuer is the same this should still work (even though it is not // technically correct certs = new ArrayList( // store.getCertificates(aCert.Issuer)); store.GetMatches(aCert.Issuer)); if (certs.Count != 1 || !certs.Contains(sCert)) { Fail("sCert not found by issuer"); } attrs = aCert.GetAttributes("1.3.6.1.4.1.6760.8.1.1"); if (attrs == null || attrs.Length != 1) { Fail("attribute not found"); } // // reencode test // aCert = new X509V2AttributeCertificate(aCert.GetEncoded()); aCert.Verify(pubKey); AttributeCertificateIssuer issuer = aCert.Issuer; X509Name[] principals = issuer.GetPrincipals(); // // test holder // AttributeCertificateHolder holder = aCert.Holder; if (holder.GetEntityNames() == null) { Fail("entity names not set"); } if (holder.SerialNumber != null) { Fail("holder serial number set when none expected"); } if (holder.GetIssuer() != null) { Fail("holder issuer set when none expected"); } principals = holder.GetEntityNames(); string ps = principals[0].ToString(); // TODO Check that this is a good enough test // if (!ps.Equals("C=US, O=vt, OU=Class 2, OU=Virginia Tech User, CN=Markus Lorch (mlorch), [email protected]")) if (!principals[0].Equivalent(new X509Name("C=US, O=vt, OU=Class 2, OU=Virginia Tech User, CN=Markus Lorch (mlorch), [email protected]"))) { Fail("principal[0] for entity names don't Match"); } // // extension test // gen.AddExtension("1.1", true, new DerOctetString(new byte[10])); gen.AddExtension("2.2", false, new DerOctetString(new byte[20])); aCert = gen.Generate(privKey); ISet exts = aCert.GetCriticalExtensionOids(); if (exts.Count != 1 || !exts.Contains("1.1")) { Fail("critical extension test failed"); } exts = aCert.GetNonCriticalExtensionOids(); if (exts.Count != 1 || !exts.Contains("2.2")) { Fail("non-critical extension test failed"); } Asn1OctetString extString = aCert.GetExtensionValue(new DerObjectIdentifier("1.1")); Asn1Encodable extValue = X509ExtensionUtilities.FromExtensionValue(extString); if (!extValue.Equals(new DerOctetString(new byte[10]))) { Fail("wrong extension value found for 1.1"); } doTestCertWithBaseCertificateID(); doTestGenerateWithCert(); doTestGenerateWithPrincipal(); }
private void AddCertsFromSet( IList certs, Asn1Set certSet) { X509CertificateParser cf = new X509CertificateParser(); foreach (Asn1Encodable ae in certSet) { try { Asn1Object obj = ae.ToAsn1Object(); if (obj is Asn1Sequence) { // TODO Build certificate directly from sequence? certs.Add(cf.ReadCertificate(obj.GetEncoded())); } } catch (Exception ex) { throw new CmsException("can't re-encode certificate!", ex); } } }
public 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()); } } }
static void PKCS7() { GostCryptoConfig.ProviderType = ProviderTypes.VipNet; Config.InitCommon(); BCX509.X509Certificate bcCert = null; using (var g = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm()) { bool detached = false; byte[] data = File.ReadAllBytes("test.xml"); var certBytes = g.ContainerCertificateRaw; BCX509.X509CertificateParser _x509CertificateParser = new BCX509.X509CertificateParser(); bcCert = _x509CertificateParser.ReadCertificate(certBytes); ICollection <BCX509.X509Certificate> certPath = new List <BCX509.X509Certificate>(); certPath.Add(bcCert); IDigest digest = new Gost3411Digest(); string hashOid = GostCryptoConfig.DefaultHashOid; byte[] dataHash = ComputeDigest(digest, data); // Construct SignerInfo.signedAttrs Asn1EncodableVector signedAttributesVector = new Asn1EncodableVector(); // Add PKCS#9 contentType signed attribute signedAttributesVector.Add( new Org.BouncyCastle.Asn1.Cms.Attribute( new DerObjectIdentifier("1.2.840.113549.1.9.3"), new DerSet(new DerObjectIdentifier("1.2.840.113549.1.7.1")))); // Add PKCS#9 messageDigest signed attribute signedAttributesVector.Add( new Org.BouncyCastle.Asn1.Cms.Attribute( new DerObjectIdentifier("1.2.840.113549.1.9.4"), new DerSet(new DerOctetString(dataHash)))); // Add PKCS#9 signingTime signed attribute signedAttributesVector.Add( new Org.BouncyCastle.Asn1.Cms.Attribute( new DerObjectIdentifier("1.2.840.113549.1.9.5"), new DerSet(new Org.BouncyCastle.Asn1.Cms.Time(new DerUtcTime(DateTime.UtcNow))))); DerSet signedAttributes = new DerSet(signedAttributesVector); byte[] pkcs1Digest = ComputeDigest(digest, signedAttributes.GetDerEncoded()); byte[] pkcs1DigestInfo = CreateDigestInfo(pkcs1Digest, hashOid); // hash //var signature = g.CreateSignature(hash); var formatter = new GostSignatureFormatter(g); var signature = formatter.CreateSignature(pkcs1Digest); // Construct SignerInfo SignerInfo signerInfo = new SignerInfo( new SignerIdentifier(new IssuerAndSerialNumber(bcCert.IssuerDN, bcCert.SerialNumber)), new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null), signedAttributes, new AlgorithmIdentifier(new DerObjectIdentifier(GostCryptoConfig.DefaultSignOid), null), new DerOctetString(signature), null); // Construct SignedData.digestAlgorithms Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector(); digestAlgorithmsVector.Add(new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null)); // Construct SignedData.encapContentInfo ContentInfo encapContentInfo = new ContentInfo( new DerObjectIdentifier("1.2.840.113549.1.7.1"), (detached) ? null : new DerOctetString(data)); // Construct SignedData.certificates Asn1EncodableVector certificatesVector = new Asn1EncodableVector(); foreach (BCX509.X509Certificate cert in certPath) { certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded()))); } // Construct SignedData.signerInfos Asn1EncodableVector signerInfosVector = new Asn1EncodableVector(); signerInfosVector.Add(signerInfo.ToAsn1Object()); // Construct SignedData SignedData signedData = new SignedData( new DerSet(digestAlgorithmsVector), encapContentInfo, new BerSet(certificatesVector), null, new DerSet(signerInfosVector)); // Construct top level ContentInfo ContentInfo contentInfo = new ContentInfo( new DerObjectIdentifier("1.2.840.113549.1.7.2"), signedData); var res = contentInfo.GetDerEncoded(); File.WriteAllBytes("test.p7", res); CmsSignedData cms = new CmsSignedData(res); var certStore = cms.GetCertificates("Collection"); SignerInformationStore signers = cms.GetSignerInfos(); var it = signers.GetSigners().GetEnumerator(); it.MoveNext(); var signer = it.Current as SignerInformation; var b = signer.Verify(bcCert); } }
static public Org.BouncyCastle.X509.X509Certificate[] LoadCertificate(byte[] raw) { Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(raw) }; return(chain); }
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) }; }
public override void PerformTest() { X509CertificateParser certParser = new X509CertificateParser(); X509CrlParser crlParser = new X509CrlParser(); 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); // Testing CollectionCertStore generation from List IList certList = new ArrayList(); certList.Add(rootCert); certList.Add(interCert); certList.Add(finalCert); IX509Store certStore = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); // set default to be the same as for SUN X500 name X509Name.DefaultReverse = true; // Searching for rootCert by subjectDN X509CertStoreSelector targetConstraints = new X509CertStoreSelector(); targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert); IList certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by subjectDN"); } // Searching for rootCert by subjectDN encoded as byte targetConstraints = new X509CertStoreSelector(); targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by encoded subjectDN"); } X509Name.DefaultReverse = false; // Searching for rootCert by public key encoded as byte targetConstraints = new X509CertStoreSelector(); targetConstraints.SubjectPublicKey = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rootCert.GetPublicKey()); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 1 || !certs.Contains(rootCert)) { Fail("rootCert not found by encoded public key"); } // Searching for interCert by issuerDN targetConstraints = new X509CertStoreSelector(); targetConstraints.Issuer = PrincipalUtilities.GetSubjectX509Principal(rootCert); certs = new ArrayList(certStore.GetMatches(targetConstraints)); if (certs.Count != 2) { Fail("did not found 2 certs"); } if (!certs.Contains(rootCert)) { Fail("rootCert not found"); } if (!certs.Contains(interCert)) { Fail("interCert not found"); } // Searching for rootCrl by issuerDN IList crlList = new ArrayList(); crlList.Add(rootCrl); crlList.Add(interCrl); IX509Store store = X509StoreFactory.Create( "CRL/Collection", new X509CollectionStoreParameters(crlList)); X509CrlStoreSelector targetConstraintsCRL = new X509CrlStoreSelector(); ArrayList issuers = new ArrayList(); issuers.Add(rootCrl.IssuerDN); targetConstraintsCRL.Issuers = issuers; IList crls = new ArrayList(store.GetMatches(targetConstraintsCRL)); if (crls.Count != 1 || !crls.Contains(rootCrl)) { Fail("rootCrl not found"); } crls = new ArrayList(certStore.GetMatches(targetConstraintsCRL)); if (crls.Count != 0) { Fail("error using wrong selector (CRL)"); } certs = new ArrayList(store.GetMatches(targetConstraints)); if (certs.Count != 0) { Fail("error using wrong selector (certs)"); } // Searching for attribute certificates X509V2AttributeCertificate attrCert = new X509V2AttributeCertificate(AttrCertTest.attrCert); IX509AttributeCertificate attrCert2 = new X509V2AttributeCertificate(AttrCertTest.certWithBaseCertificateID); IList attrList = new ArrayList(); attrList.Add(attrCert); attrList.Add(attrCert2); store = X509StoreFactory.Create( "AttributeCertificate/Collection", new X509CollectionStoreParameters(attrList)); X509AttrCertStoreSelector attrSelector = new X509AttrCertStoreSelector(); attrSelector.Holder = attrCert.Holder; if (!attrSelector.Holder.Equals(attrCert.Holder)) { Fail("holder get not correct"); } IList attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on holder"); } attrSelector.Holder = attrCert2.Holder; if (attrSelector.Holder.Equals(attrCert.Holder)) { Fail("holder get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert2)) { Fail("attrCert2 not found on holder"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.Issuer = attrCert.Issuer; if (!attrSelector.Issuer.Equals(attrCert.Issuer)) { Fail("issuer get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on issuer"); } attrSelector.Issuer = attrCert2.Issuer; if (attrSelector.Issuer.Equals(attrCert.Issuer)) { Fail("issuer get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert2)) { Fail("attrCert2 not found on issuer"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCert = attrCert; if (!attrSelector.AttributeCert.Equals(attrCert)) { Fail("attrCert get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on attrCert"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.SerialNumber = attrCert.SerialNumber; if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber)) { Fail("serial number get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on serial number"); } attrSelector = (X509AttrCertStoreSelector)attrSelector.Clone(); if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber)) { Fail("serial number get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on serial number"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore); if (attrSelector.AttributeCertificateValid.Value != attrCert.NotBefore) { Fail("valid get not correct"); } attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 1 || !attrs.Contains(attrCert)) { Fail("attrCert not found on valid"); } attrSelector = new X509AttrCertStoreSelector(); attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore.AddMilliseconds(-100)); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on before"); } attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotAfter.AddMilliseconds(100)); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on after"); } attrSelector.SerialNumber = BigInteger.ValueOf(10000); attrs = new ArrayList(store.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("attrCert found on wrong serial number"); } attrSelector.AttributeCert = null; attrSelector.AttributeCertificateValid = null; attrSelector.Holder = null; attrSelector.Issuer = null; attrSelector.SerialNumber = null; if (attrSelector.AttributeCert != null) { Fail("null attrCert"); } if (attrSelector.AttributeCertificateValid != null) { Fail("null attrCertValid"); } if (attrSelector.Holder != null) { Fail("null attrCert holder"); } if (attrSelector.Issuer != null) { Fail("null attrCert issuer"); } if (attrSelector.SerialNumber != null) { Fail("null attrCert serial"); } attrs = new ArrayList(certStore.GetMatches(attrSelector)); if (attrs.Count != 0) { Fail("error using wrong selector (attrs)"); } certPairTest(); }
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); } }
public override void PerformTest() { 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 x509Certs = new ArrayList(); x509Certs.Add(rootCert); x509Certs.Add(interCert); x509Certs.Add(finalCert); IList x509Crls = new ArrayList(); x509Crls.Add(rootCrl); x509Crls.Add(interCrl); // CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); // CertStore store = CertStore.GetInstance("Collection", ccsp); // X509CollectionStoreParameters ccsp = new X509CollectionStoreParameters(list); IX509Store x509CertStore = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(x509Certs)); IX509Store x509CrlStore = X509StoreFactory.Create( "CRL/Collection", new X509CollectionStoreParameters(x509Crls)); // 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); //validating path IList certchain = new ArrayList(); certchain.Add(finalCert); certchain.Add(interCert); // CertPath cp = CertificateFactory.GetInstance("X.509").GenerateCertPath(certchain); PkixCertPath cp = new PkixCertPath(certchain); ISet trust = new HashSet(); trust.Add(new TrustAnchor(rootCert, null)); // CertPathValidator cpv = CertPathValidator.GetInstance("PKIX"); PkixCertPathValidator cpv = new PkixCertPathValidator(); PkixParameters param = new PkixParameters(trust); param.AddStore(x509CertStore); param.AddStore(x509CrlStore); param.Date = new DateTimeObject(validDate); MyChecker checker = new MyChecker(); param.AddCertPathChecker(checker); PkixCertPathValidatorResult result = (PkixCertPathValidatorResult) cpv.Validate(cp, param); PkixPolicyNode policyTree = result.PolicyTree; AsymmetricKeyParameter subjectPublicKey = result.SubjectPublicKey; if (checker.GetCount() != 2) { Fail("checker not evaluated for each certificate"); } if (!subjectPublicKey.Equals(finalCert.GetPublicKey())) { Fail("wrong public key returned"); } // // invalid path containing a valid one test // try { // initialise CertStore rootCert = certParser.ReadCertificate(AC_RAIZ_ICPBRASIL); interCert = certParser.ReadCertificate(AC_PR); finalCert = certParser.ReadCertificate(schefer); x509Certs = new ArrayList(); x509Certs.Add(rootCert); x509Certs.Add(interCert); x509Certs.Add(finalCert); // ccsp = new CollectionCertStoreParameters(list); // store = CertStore.GetInstance("Collection", ccsp); // ccsp = new X509CollectionStoreParameters(list); x509CertStore = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(x509Certs)); // NB: Month is 1-based in .NET validDate = new DateTime(2004,3,21,2,21,10).ToUniversalTime(); //validating path certchain = new ArrayList(); certchain.Add(finalCert); certchain.Add(interCert); // cp = CertificateFactory.GetInstance("X.509").GenerateCertPath(certchain); cp = new PkixCertPath(certchain); trust = new HashSet(); trust.Add(new TrustAnchor(rootCert, null)); // cpv = CertPathValidator.GetInstance("PKIX"); cpv = new PkixCertPathValidator(); param = new PkixParameters(trust); param.AddStore(x509CertStore); param.IsRevocationEnabled = false; param.Date = new DateTimeObject(validDate); result =(PkixCertPathValidatorResult) cpv.Validate(cp, param); policyTree = result.PolicyTree; subjectPublicKey = result.SubjectPublicKey; Fail("Invalid path validated"); } catch (Exception e) { if (e is PkixCertPathValidatorException && e.Message.StartsWith("Could not validate certificate signature.")) { return; } Fail("unexpected exception", e); } }
/** * 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); }
/// <summary> /// Gets a list of all certificates suitable for the given key usage. /// </summary> /// <returns>The matching certificates.</returns> /// <param name="keyUsage">The key usage.</param> /// <exception cref="System.ObjectDisposedException"> /// The keychain has been disposed. /// </exception> public IList<X509Certificate> GetCertificates(CssmKeyUse keyUsage) { if (disposed) throw new ObjectDisposedException ("SecKeychain"); var parser = new X509CertificateParser (); var certs = new List<X509Certificate> (); IntPtr searchRef, itemRef, certRef; OSStatus status; status = SecIdentitySearchCreate (Handle, keyUsage, out searchRef); if (status != OSStatus.Ok) return certs; while (SecIdentitySearchCopyNext (searchRef, out itemRef) == OSStatus.Ok) { if (SecIdentityCopyCertificate (itemRef, out certRef) == OSStatus.Ok) { using (var data = new CFData (SecCertificateCopyData (certRef), true)) { var rawData = data.GetBuffer (); try { certs.Add (parser.ReadCertificate (rawData)); } catch (CertificateException ex) { Debug.WriteLine ("Failed to parse X509 certificate from keychain: {0}", ex); } } } CFRelease (itemRef); } CFRelease (searchRef); return certs; }
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); } }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsRecipient"/> class. /// </summary> /// <remarks> /// <para>Creates a new <see cref="CmsRecipient"/>, loading the certificate from the specified file.</para> /// <para>The initial value of the <see cref="EncryptionAlgorithms"/> property will be set to /// the Triple-DES encryption algorithm, which should be safe to assume for all modern /// S/MIME v3.x client implementations.</para> /// </remarks> /// <param name="fileName">The file containing the recipient's certificate.</param> /// <param name="recipientIdentifierType">The recipient identifier type.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="fileName"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="fileName"/> is a zero-length string, contains only white space, or /// contains one or more invalid characters as defined by /// <see cref="System.IO.Path.InvalidPathChars"/>. /// </exception> /// <exception cref="System.IO.DirectoryNotFoundException"> /// <paramref name="fileName"/> is an invalid file path. /// </exception> /// <exception cref="System.IO.FileNotFoundException"> /// The specified file path could not be found. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// The user does not have access to read the specified file. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public CmsRecipient (string fileName, SubjectIdentifierType recipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber) { if (fileName == null) throw new ArgumentNullException (nameof (fileName)); var parser = new X509CertificateParser (); if (recipientIdentifierType == SubjectIdentifierType.IssuerAndSerialNumber) RecipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber; else RecipientIdentifierType = SubjectIdentifierType.SubjectKeyIdentifier; EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.TripleDes }; RecipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber; using (var stream = File.OpenRead (fileName)) Certificate = parser.ReadCertificate (stream); }
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; } } }
public void SignWithThisCert(X509Certificate2 cert, Stream Archivo, string URLDocumento) { string DestPdfFileName = URLDocumento; Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) }; IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA-1"); Archivo.Flush(); // Don't know if this is necessary Archivo.Position = 0; PdfReader pdfReader = new PdfReader(Archivo); FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create); //the output pdf file PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0'); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; //here set signatureAppearance at your will signatureAppearance.Reason = ConfigurationManager.AppSettings["firma_RazonInversionista"].ToString(); signatureAppearance.Location = ConfigurationManager.AppSettings["firma_Ubicacion"].ToString(); signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS); //MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CADES); signedPdf.Close(); //signedPdf = new FileStream(DestPdfFileName, FileMode.Open); //return signedPdf; }