internal Boolean ValidateServerCertificate( Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors ) { log.Info("Validating certificate"); var foundPins = new List <String>(); foreach (X509ChainElement c in chain.ChainElements) { var certParser = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate cert = certParser.ReadCertificate(c.Certificate.RawData); Org.BouncyCastle.Asn1.X509.X509CertificateStructure certStruct = cert.CertificateStructure; String peerPin = Fingerprint(certStruct); log.Info("Peer pin: " + peerPin); foundPins.Add(peerPin); if (this.Matches(peerPin)) { return(true); } } return(false); }
public static bool SignPDF(X509Certificate2 signature, string sourceDocument, string destinationPath) { if (signature == null) { return(false); } PdfReader reader = new PdfReader(sourceDocument); using (FileStream fout = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite)) { using (PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0')) { // digital signature var pk = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(signature.PrivateKey).Private; IExternalSignature es = new PrivateKeySignature(pk, "SHA-256"); Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new[] { cp.ReadCertificate(signature.RawData) }; try { MakeSignature.SignDetached(stamper.SignatureAppearance, es, chain, null, null, null, 0, CryptoStandard.CMS); } catch (CryptographicException ex) { return(false); } stamper.Close(); } } return(true); }
// https://git.itextsupport.com/projects/I5N/repos/itextsharp/browse/src/core/iTextSharp/text/pdf/security public static void Test(System.Security.Cryptography.X509Certificates.X509Certificate2 cert) { Org.BouncyCastle.X509.X509CertificateParser parser = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate bouncyCertificate = parser.ReadCertificate(cert.RawData); string algorithm = DigestAlgorithms.GetDigest(bouncyCertificate.SigAlgOid); X509Certificate2Signature signature = new X509Certificate2Signature(cert, algorithm); }
/// <summary> /// Sign /// </summary> /// <param name="input">The input.</param> /// <param name="output">The output.</param> /// <param name="certificate">The certificate.</param> public override void Sign(Stream input, Stream output, X509Certificate2 certificate) { CheckInputOutputAndCertificate(input, output, certificate); PdfReader reader = null; try { reader = new PdfReader(input); using (var stamper = PdfStamper.CreateSignature(reader, output, '\0', null, true)) { var cp = new Org.BouncyCastle.X509.X509CertificateParser(); var chain = new[] { cp.ReadCertificate(certificate.RawData) }; var sig = stamper.SignatureAppearance; SetSigPosition(sig, reader.AcroFields.GetSignatureNames().Count); SetSigText(sig, chain); SetSigCryptoFromX509(sig, certificate, chain); } } finally { if (reader != null) { reader.Close(); } } }
public static XadesObject GetXadesObject(SigningKeyProvider provider, XadesInfo xadesInfo, string signatureid) { XadesObject xadesObject = new XadesObject(); xadesObject.QualifyingProperties.Target = String.Format("#{0}", signatureid); xadesObject.QualifyingProperties.SignedProperties.Id = String.Format("{0}-signedprops", signatureid); SignedSignatureProperties signedSignatureProperties = xadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties; var x509CertificateParser = new Org.BouncyCastle.X509.X509CertificateParser(); X509Certificate bouncyCert = x509CertificateParser.ReadCertificate(Convert.FromBase64String(xadesInfo.RawPK)); var cert = new Cert { IssuerSerial = { X509IssuerName = GetOidRepresentation(bouncyCert.IssuerDN.ToString()), X509SerialNumber = bouncyCert.SerialNumber.ToString() } }; cert.CertDigest.DigestMethod.Algorithm = provider.DigestMethod; var rawCertData = Convert.FromBase64String(xadesInfo.RawPK); var pkHash = HashAlgorithm.Create(provider.HashAlgorithmName); var hashValue = pkHash.ComputeHash(rawCertData); cert.CertDigest.DigestValue = hashValue; signedSignatureProperties.SigningCertificate.CertCollection.Add(cert); signedSignatureProperties.SigningTime = GetSigningTimeOffset(xadesInfo.SigningDateTimeUTC, xadesInfo.TimeZoneOffsetMinutes); return(xadesObject); }
private void VerifySignature(byte[] DataToSign, byte[] signature) { // verify signature WriteText("start verify signature"); // get public key from seal certificate var p = new Org.BouncyCastle.X509.X509CertificateParser(); var x509 = p.ReadCertificate(seal_cert); // return value of signature is juse r and s buffers appended // for bouncycastle VerifySignature to work we need an ASN1 Sequence int len = signature.Length / 2; BigInteger sssrVal = new BigInteger(signature, 0, len); BigInteger rVal = new BigInteger(1, signature, 0, len); BigInteger sssVal = new BigInteger(signature, len, len); BigInteger sVal = new BigInteger(1, signature, len, len); DerSequence seq = new DerSequence(new DerInteger(rVal), new DerInteger(sVal)); var signatureAsSequence = seq.GetDerEncoded(); // actual verify ISigner signer = SignerUtilities.GetSigner("SHA256withECDSA"); signer.Init(false, x509.GetPublicKey()); signer.BlockUpdate(DataToSign, 0, DataToSign.Length); bool result = signer.VerifySignature(signatureAsSequence); WriteText("signature verification = " + result.ToString()); }
public static XadesObject GetXadesObject(XadesInfo xadesInfo, string signatureid) { XadesObject xadesObject = new XadesObject(); xadesObject.QualifyingProperties.Target = String.Format("#{0}", signatureid); xadesObject.QualifyingProperties.SignedProperties.Id = String.Format("{0}-signedprops", signatureid); SignedSignatureProperties signedSignatureProperties = xadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties; var x509CertificateParser = new Org.BouncyCastle.X509.X509CertificateParser(); X509Certificate bouncyCert = x509CertificateParser.ReadCertificate(Convert.FromBase64String(xadesInfo.RawPK)); var cert = new Cert { IssuerSerial = { X509IssuerName = GetOidRepresentation(bouncyCert.IssuerDN.ToString()), X509SerialNumber = bouncyCert.SerialNumber.ToString() } }; cert.CertDigest.DigestMethod.Algorithm = CPSignedXml.XmlDsigGost3411UrlObsolete; var rawCertData = Convert.FromBase64String(xadesInfo.RawPK); var pkHash = HashAlgorithm.Create("GOST3411"); var hashValue = pkHash.ComputeHash(rawCertData); cert.CertDigest.DigestValue = hashValue; signedSignatureProperties.SigningCertificate.CertCollection.Add(cert); signedSignatureProperties.SigningTime = xadesInfo.SigningDateTimeUTC.AddMinutes(xadesInfo.TimeZoneOffsetMinutes); return xadesObject; }
public static void CertificateToDerPem(Org.BouncyCastle.X509.X509Certificate caSsl) { System.Security.Cryptography.X509Certificates.X509Certificate inputCert1 = null; inputCert1 = Org.BouncyCastle.Security.DotNetUtilities.ToX509Certificate(caSsl); System.Security.Cryptography.X509Certificates.X509Certificate2 inputCert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(inputCert1); string pemOrDerFile = "foo.derpem"; string foo = CerGenerator.ToPem(caSsl.GetEncoded()); System.IO.File.WriteAllText(pemOrDerFile, foo, System.Text.Encoding.ASCII); Org.BouncyCastle.X509.X509CertificateParser kpp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate cert = kpp.ReadCertificate(System.IO.File.OpenRead(pemOrDerFile)); System.Console.WriteLine(cert); System.Security.Cryptography.X509Certificates.X509Certificate dotCert1 = null; dotCert1 = Org.BouncyCastle.Security.DotNetUtilities.ToX509Certificate(cert); System.Security.Cryptography.X509Certificates.X509Certificate2 dotCert = new System.Security.Cryptography.X509Certificates.X509Certificate2(dotCert1); System.Console.WriteLine(dotCert.PublicKey); System.Console.WriteLine(dotCert.PrivateKey); }
public static byte[] SignPDFBytes(X509Certificate2 signatureCert, byte[] pdf) { byte[] result; MemoryStream ms = new MemoryStream(); PdfReader reader = new PdfReader(pdf); using (PdfStamper signer = PdfStamper.CreateSignature(reader, ms, '\0')) { // digital signature var pk = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(signatureCert.PrivateKey).Private; IExternalSignature es = new PrivateKeySignature(pk, "SHA-256"); Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new[] { cp.ReadCertificate(signatureCert.RawData) }; try { MakeSignature.SignDetached(signer.SignatureAppearance, es, chain, null, null, null, 0, CryptoStandard.CMS); result = ms.ToArray(); } catch (CryptographicException ex) { throw; } signer.Close(); } return(result); }
public string Validate(byte[] tsr) { AppendLog("TimeStamp validating..."); Org.BouncyCastle.Tsp.TimeStampToken token; try { token = new Org.BouncyCastle.Tsp.TimeStampToken(new CmsSignedData(tsr)); } catch (Exception e) { AppendLog(e.Message); return("Invalid tsr"); } try { var certParser = new Org.BouncyCastle.X509.X509CertificateParser(); var bouncyCert = certParser.ReadCertificate(_authorityCert.GetRawCertData()); token.Validate(bouncyCert); return("Valid timestamp"); } catch (Exception e) { AppendLog(e.Message); return(e is TspValidationException || e is TspException ? e.Message : "Validation error"); } }
public static void CreateSignature(System.Security.Cryptography.X509Certificates.X509Certificate2 mycert) { // https://www.programcreek.com/java-api-examples/?api=org.bouncycastle.x509.X509V3CertificateGenerator // https://forums.asp.net/t/2154987.aspx?Create+Self+Signed+Certificate+programatically+uisng+C+ // System.Security.Cryptography.X509Certificates.X509Certificate2.CreateFromCertFile() // https://overcoder.net/q/429916/bouncycastle-privatekey-to-x509%D1%81%D0%B5%D1%80%D1%82%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%822-privatekey // https://www.csharpcodi.com/csharp-examples/Org.BouncyCastle.X509.X509Certificate.GetPublicKey()/ Org.BouncyCastle.Crypto.AsymmetricKeyParameter Akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(mycert.PrivateKey).Private; // if(mycert.HasPrivateKey) Org.BouncyCastle.Crypto.AsymmetricKeyParameter bouncyCastlePrivateKey = TransformRSAPrivateKey(mycert.PrivateKey); Org.BouncyCastle.X509.X509CertificateParser certParser = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate bouncyCertificate = certParser.ReadCertificate(mycert.GetRawCertData()); Org.BouncyCastle.Crypto.AsymmetricKeyParameter pubKey = bouncyCertificate.GetPublicKey(); Org.BouncyCastle.Crypto.IDigest algorithm = Org.BouncyCastle.Security.DigestUtilities.GetDigest(bouncyCertificate.SigAlgOid); // X509Certificate2Signature signature = new X509Certificate2Signature(mycert, algorithm); // https://github.com/kusl/itextsharp/blob/master/tags/iTextSharp_5_4_5/src/core/iTextSharp/text/pdf/security/X509Certificate2Signature.cs // Sign // PemReader pem = new PemReader(); // pem.ReadPemObject().Headers // RSACryptoServiceProvider rsa = pem.ReadPrivateKeyFromFile("PrivateKey.pem"); }
public void sign(X509Certificate2 cert, String filename, String imageName, String output) { 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"); PdfReader pdfReader = new PdfReader(filename); FileStream signedPdf = new FileStream(output, FileMode.Create); PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0'); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; Image img = Image.GetInstance(imageName); img.Alignment = iTextSharp.text.Image.UNDERLYING; signatureAppearance.SignatureGraphic = img; signatureAppearance.Acro6Layers = true; int x = Convert.ToInt32(xTextBox.Text); int y = Convert.ToInt32(yTextBox.Text); int w = Convert.ToInt32(widthTextBox.Text); int h = Convert.ToInt32(heightTextBox.Text); signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(x, y, w, h), pdfReader.NumberOfPages, "Signature"); signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS); }
/// <summary> /// Verify that CA certificate signed end entity certificate /// </summary> /// <param name="caCertData">DER encoded CA certificate</param> /// <param name="eeCertData">DER encoded end entity certificate</param> /// <returns>True if CA certificate signed end entity certificate; false otherwise</returns> private bool CaCertSignedEndEntityCert(byte[] caCertData, byte[] eeCertData) { var certParser = new Org.BouncyCastle.X509.X509CertificateParser(); var caCert = certParser.ReadCertificate(caCertData); var eeCert = certParser.ReadCertificate(eeCertData); try { eeCert.Verify(caCert.GetPublicKey()); return(true); } catch (Org.BouncyCastle.Security.InvalidKeyException) { return(false); } }
public void Sign(string inputPath, string outPath, string imagePath, bool visible = true) { X509Store store = new X509Store(StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, X509SelectionFlag.SingleSelection); X509Certificate2 cert = sel[0]; 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"); PdfReader pdfReader = new PdfReader(inputPath); var signedPdf = new FileStream(outPath, FileMode.Create); var pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0'); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; if (imagePath != null && imagePath != string.Empty) { signatureAppearance.SignatureGraphic = Image.GetInstance(imagePath); } signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 250, 150), pdfReader.NumberOfPages, "Signature"); signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS); Process.Start(outPath); }
/// <summary> /// /// </summary> /// <param name="inputPath"></param> /// <param name="outputPath"></param> /// <param name="cert"></param> /// <param name="caCerts"></param> /// <param name="signatureSettings"></param> public static void Sign(string inputPath, string outputPath, X509Certificate2 cert, ICollection<X509Certificate2> caCerts, SignatureSettings signatureSettings) { var cp = new Org.BouncyCastle.X509.X509CertificateParser(); var chain = new List<Org.BouncyCastle.X509.X509Certificate> { cp.ReadCertificate(cert.RawData) }; chain.AddRange(caCerts.Select(caCert => cp.ReadCertificate(caCert.RawData))); IExternalSignature pk = new X509Certificate2Signature(cert, DigestAlgorithms.SHA1); IList<ICrlClient> crlList = new List<ICrlClient>(); crlList.Add(new CrlClientOnline()); var signed = SignDocument(inputPath, chain, pk, CryptoStandard.CMS, signatureSettings.Reason, signatureSettings.Location, crlList, null, signatureSettings.TsaClient, 0); File.WriteAllBytes(outputPath, signed); AddLtv(signed, outputPath, signatureSettings.OcspClient, crlList.First()); }
private static Org.BouncyCastle.X509.X509Certificate[] GetChainBouncyCastle(X509Certificate2 cer) { Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); var cerRawData = cer.RawData; var certificates = cp.ReadCertificate(cerRawData); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { certificates }; return(chain); }
} // End Function CreatePfxBytes private static Org.BouncyCastle.X509.X509Certificate PemStringToX509(string pemString) { Org.BouncyCastle.X509.X509Certificate cert = null; Org.BouncyCastle.X509.X509CertificateParser kpp = new Org.BouncyCastle.X509.X509CertificateParser(); using (System.IO.Stream pemStream = new StringStream(pemString)) { cert = kpp.ReadCertificate(pemStream); } // End Using pemStream return(cert); } // End Function PemStringToX509
public ICollection <Org.BouncyCastle.X509.X509Certificate> CadeiaCertificadoTempo() { var certificadoTempoArquivo = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "brycert.cer"); var certificadoTempo = new X509Certificate2(certificadoTempoArquivo); var cp = new Org.BouncyCastle.X509.X509CertificateParser(); var chain = new[] { cp.ReadCertificate(certificadoTempo.RawData) }; Log.Application.DebugFormat("Cadeia de certificação obtida com sucesso."); return(chain); }
public static string GetPemPublicKey(X509Certificate2 cert) { var x509CertificateParser = new Org.BouncyCastle.X509.X509CertificateParser(); var bcCert = x509CertificateParser.ReadCertificate(cert.RawData); var asymmetricKeyParameter = bcCert.GetPublicKey(); var stringWrite = new StringWriter(); var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(stringWrite); pemWriter.WriteObject(asymmetricKeyParameter); stringWrite.Close(); return(stringWrite.ToString()); }
private Org.BouncyCastle.X509.X509Certificate[] GetCertChain(X509Certificate2 cert) { Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); X509Chain ch = new X509Chain(); //ch.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; ch.Build(cert); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[ch.ChainElements.Count]; for (int idx = 0; idx < ch.ChainElements.Count; idx++) { X509ChainElement chElem = ch.ChainElements[idx]; chain[idx] = cp.ReadCertificate(chElem.Certificate.RawData); } return(chain); }
public ICollection <Org.BouncyCastle.X509.X509Certificate> CadeiaCertificadoTempo() { var certificadoTempoArquivo = Path.Combine(Aplicacao.Caminho, "brycert.cer"); var certificadoTempo = new X509Certificate2(certificadoTempoArquivo); var cp = new Org.BouncyCastle.X509.X509CertificateParser(); var chain = new[] { cp.ReadCertificate(certificadoTempo.RawData) }; Console.WriteLine("Cadeia de certificação obtida com sucesso."); return(chain); }
} // End Sub GenerateRootCertificate public static void BouncyCert() { string pemOrDerFile = ""; Org.BouncyCastle.X509.X509CertificateParser kpp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate cert = kpp.ReadCertificate(System.IO.File.OpenRead(pemOrDerFile)); Org.BouncyCastle.Security.DotNetUtilities.ToX509Certificate(cert); System.Security.Cryptography.X509Certificates.X509Certificate msCert = Org.BouncyCastle.Security.DotNetUtilities.ToX509Certificate(cert); System.Security.Cryptography.X509Certificates.X509Certificate2 ms2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(msCert); Org.BouncyCastle.Pkcs.AsymmetricKeyEntry keyEntry = null; //store.GetKey(alias); Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = keyEntry.Key; ms2.PrivateKey = Org.BouncyCastle.Security.DotNetUtilities.ToRSA((Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)keyEntry.Key); }
private static XadesObject GetXadesObject(XadesInfo xadesInfo, string signatureid) { var xadesObject = new XadesObject { QualifyingProperties = { Target = $"#{signatureid}", SignedProperties = { Id = $"{signatureid}-signedprops" } } }; var signedSignatureProperties = xadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties; var x509CertificateParser = new Org.BouncyCastle.X509.X509CertificateParser(); var bouncyCert = x509CertificateParser.ReadCertificate(Convert.FromBase64String(xadesInfo.RawPk)); var x509IssuerDn = GetOidRepresentation(bouncyCert.IssuerDN.ToString()); x509IssuerDn = IssuerNamePatcher(x509IssuerDn); var cert = new Cert { IssuerSerial = { X509IssuerName = x509IssuerDn, X509SerialNumber = bouncyCert.SerialNumber.ToString() } }; #pragma warning disable 612 cert.CertDigest.DigestMethod.Algorithm = CPSignedXml.XmlDsigGost3411UrlObsolete; #pragma warning restore 612 var rawCertData = Convert.FromBase64String(xadesInfo.RawPk); var pkHash = HashAlgorithm.Create("GOST3411"); if (pkHash != null) { var hashValue = pkHash.ComputeHash(rawCertData); cert.CertDigest.DigestValue = hashValue; } signedSignatureProperties.SigningCertificate.CertCollection.Add(cert); signedSignatureProperties.SigningTime = xadesInfo.SigningDateTimeUtc.AddMinutes(xadesInfo.TimeZoneOffsetMinutes); return(xadesObject); }
/// <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 Org.BouncyCastle.X509.X509Certificate ToBouncyCastleObject(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } Org.BouncyCastle.X509.X509CertificateParser _x509CertificateParser = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate bcCert = _x509CertificateParser.ReadCertificate(data); if (bcCert == null) { throw new CryptographicException("Cannot find the requested object."); } return(bcCert); }
} // End Sub SelfSignSslCertificate public static Org.BouncyCastle.X509.X509Certificate ReadCertificate(string pemLocation) { Org.BouncyCastle.X509.X509Certificate bouncyCertificate = null; Org.BouncyCastle.X509.X509CertificateParser certParser = new Org.BouncyCastle.X509.X509CertificateParser(); // Org.BouncyCastle.X509.X509Certificate bouncyCertificate = certParser.ReadCertificate(mycert.GetRawCertData()); using (System.IO.Stream fs = System.IO.File.OpenRead(pemLocation)) { bouncyCertificate = certParser.ReadCertificate(fs); } // End Using fs // Org.BouncyCastle.Crypto.AsymmetricKeyParameter pubKey = bouncyCertificate.GetPublicKey(); return(bouncyCertificate); } // End Function ReadCertificate
public static void TestParser() { string pfxLocation = @"D:\lol\certificate.pfx"; pfxLocation = @"D:\username\Desktop\DesktopArchiv\20180329_Desktop\CORMailService\CORMailService\CORMailService\CORMailService_TemporaryKey.pfx"; System.Security.Cryptography.X509Certificates.X509Certificate2 certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(pfxLocation); // Private Key if (!certificate.HasPrivateKey) { throw new System.IO.InvalidDataException("no private key in pfx file."); } // System.Security.Cryptography.AsymmetricAlgorithm rsa = certificate.PrivateKey; X509CertificateStore xs = new X509CertificateStore(); xs.Import(pfxLocation); foreach (Org.BouncyCastle.X509.X509Certificate thisCert in xs.Certificates) { System.Console.WriteLine(thisCert); thisCert.GetPublicKey(); // Org.BouncyCastle.Crypto.ISigner signer = Org.BouncyCastle.Security.SignerUtilities.GetSigner(Sdk.SIGNATURE_ALGORITHM); } Org.BouncyCastle.X509.X509CertificateParser certParser = new Org.BouncyCastle.X509.X509CertificateParser(); using (System.IO.Stream fs = System.IO.File.OpenRead(pfxLocation)) { certParser.ReadCertificate(fs); } System.Console.WriteLine(certParser); }
private static IExternalSignature ResolveExternalSignatureFromCertStore(X509Certificate2 cert, bool allowInvalidCertificate, out ICollection <Org.BouncyCastle.X509.X509Certificate> chain) { try { X509Certificate2 signatureCert = new X509Certificate2(cert); Org.BouncyCastle.X509.X509Certificate bcCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert); chain = new List <Org.BouncyCastle.X509.X509Certificate> { bcCert }; var parser = new Org.BouncyCastle.X509.X509CertificateParser(); var bouncyCertificate = parser.ReadCertificate(cert.GetRawCertData()); var algorithm = DigestAlgorithms.GetDigest(bouncyCertificate.SigAlgOid); return(new X509Certificate2Signature(signatureCert, algorithm)); } catch (Exception) { throw; } }
public static void AssinaComToken(Stream File, out byte[] SignFile, CertSimples cert, float X, float 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-1", 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 = 155; int Altura = 63; Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) }; IExternalSignature externalSignature = new X509Certificate2Signature(cert.Certificado, MyDigestAlgorithm); PdfReader pdfReader = new PdfReader(File); MemoryStream signedPdf = new MemoryStream(); //cria a assinatura //PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', "temp" + signedPdf, true); string path = System.AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', path + DateTime.Now.ToString("hhMMddHHmmss") + ".pdf", true); Bitmap bmp = Graphic.ConfiguraBMP(cert, out Altura, Tipo); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; ConfiguraAparenciaAssinatura(signatureAppearance, Reason, Contact, Location, Creator, bmp, Altura, Largura, X, Y, Rotation, Pagina, pdfReader); TSAClientBouncyCastle tsaClient = null; if (AddTimeStamper) { tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass, TSAClientBouncyCastle.DEFAULTTOKENSIZE, MyDigestAlgorithm); } IOcspClient ocspClient = new OcspClientBouncyCastle(); List <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(new CrlClientOnline(chain)); if (AplicaPolitica) { SignaturePolicyInfo spi = PoliticaDaAssinatura(); MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES, spi); } else { MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES); } try { SignFile = signedPdf.ToArray(); //SignFile = INB.Assinador.Helper.Funcoes.ToByteArray(teste); //MemoryStream teste = (MemoryStream)signatureAppearance.TempFile; //signedPdf.Flush(); //SignFile // SignFile = new MemoryStream(ArquivoAssinado); // signedPdf.CopyTo(); try { signedPdf.Close(); signedPdf.Dispose(); } catch { } } catch (Exception ex) { SignFile = null; throw ex; } try { signedPdf.Close(); } catch (Exception ex) {} pdfReader.Close(); try { pdfReader.Dispose(); } catch { } }
private Org.BouncyCastle.X509.X509Certificate[] __makeChain() { Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); return(new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) }); }
static void Main(string[] args) { Document pdfDoc = new Document(); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream("../../testingC.pdf", FileMode.OpenOrCreate)); pdfDoc.Open(); pdfDoc.Add(new Paragraph("Some data")); PdfContentByte cb = writer.DirectContent; cb.MoveTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height / 2); cb.LineTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height); cb.Stroke(); PdfSignature sig = new PdfSignature(new PdfName("testname"), new PdfName("subfiltertest")); pdfDoc.Close(); PdfReader reader = new PdfReader("../../testingC.pdf"); using (FileStream fout = new FileStream("../../testingC signed.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite)) { // appearance PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0', "test", false); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = "testing"; appearance.Location = "here"; appearance.SignDate = DateTime.Now.Date; appearance.SetVisibleSignature(new Rectangle(10, 10, 10 + 200, 10 + 100), 1, null); // Custom text and background image appearance.Image = Image.GetInstance("../../../asd.png"); appearance.ImageScale = 0.6f; appearance.Image.Alignment = 300; appearance.Acro6Layers = true; StringBuilder buf = new StringBuilder(); buf.Append("Digitally Signed by "); String name = "SDL"; buf.Append(name).Append('\n'); buf.Append("Date: ").Append(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss zzz")); string text = buf.ToString(); appearance.Layer2Text = text; //get store var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); //get store certificates by thumbprint (collection of 1 certificate) string thumbprint = "dd 8d 50 24 c3 e2 c9 ce 53 40 81 18 16 ca de 57 f5 44 a7 77"; thumbprint = thumbprint.Replace(" ", ""); thumbprint = thumbprint.ToUpper(); var certs = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); //get certificate raw data to parse to a bouncycastle certificate var bytecert = certs[0].RawData; //parse certificate var parser = new Org.BouncyCastle.X509.X509CertificateParser(); var cert = parser.ReadCertificate(bytecert); //create collection for SignDetached method List <Org.BouncyCastle.X509.X509Certificate> chain = new List <Org.BouncyCastle.X509.X509Certificate> { cert }; //get password from certificate in bouncycastle format var rsa = (RSACryptoServiceProvider)(certs[0].PrivateKey); var es = new PrivateKeySignature(DotNetUtilities.GetRsaKeyPair(rsa).Private, "SHA-256"); //sign the document MakeSignature.SignDetached(appearance, es, chain, null, null, null, 0, CryptoStandard.CMS); stamper.Close(); var x = certs[0].Export(X509ContentType.Pfx, "123456"); File.WriteAllBytes("../../test.pfx", x); } }
//public static void AssinaComToken_OLD(string FileName, string SignFileName, X509Certificate2 cert, float X, float Y, int Pagina, double Escala, bool SeloCargo = false, bool SeloCREA = false, bool SeloCRM = false, string Cargo = "", string CREACRM = "", bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-1", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", bool SeloCertifico = false) //{ // string SourcePdfFileName = FileName; // string DestPdfFileName = SignFileName; // int Largura = 155; // int Altura = 63; // 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, MyDigestAlgorithm); // PdfReader pdfReader = new PdfReader(SourcePdfFileName); // FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create, FileAccess.ReadWrite); //the output pdf file // //cria a assinatura // PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', "temp" + signedPdf, true); // PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; // Bitmap bmp = INB.Assinador.Helper.Graphic.ConfiguraBMP(cert, SeloCargo, SeloCREA, SeloCRM, Cargo, CREACRM, out Altura, SeloCertifico); // //CONFIGURA A APARÊNCIA DO SELO DA ASSINATURA. // ConfiguraAparenciaAssinatura(signatureAppearance, Reason, Contact, Location, Creator, bmp, Altura, Largura, X, Y, Escala, Pagina, pdfReader); // //ADICIONA O CARIMBO DO TEMPO. // TSAClientBouncyCastle tsaClient = null; // if (AddTimeStamper) // { // //urlTimeStamper = http://timestamp.globalsign.com/scripts/timestamp.dll // //urlTimeStamper = "http://timestamp.apple.com/ts01"; // tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass, TSAClientBouncyCastle.DEFAULTTOKENSIZE, MyDigestAlgorithm); // } // IOcspClient ocspClient = new OcspClientBouncyCastle(); // List<ICrlClient> crlList = new List<ICrlClient>(); // crlList.Add(new CrlClientOnline(chain)); // //Nota 2: O hash da política de assinatura no atributo id-aa-ets-sigPolicyId da assinatura deve ser o hash interno que está na própria PA e não o hash da PA que se encontra publicada na LPA. // if (AplicaPolitica) // { // SignaturePolicyInfo spi = PoliticaDaAssinatura(); // MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES, spi); // } // else // { // MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES); // } // try { signedPdf.Flush(); } // catch { } // try { signedPdf.Close(); } catch { }; // pdfReader.Close(); // try { // pdfReader.Dispose(); // } // catch { } //} public static void AssinaComToken(string FileName, string SignFileName, CertSimples cert, float X, float 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-1", 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 = 155; int Altura = 63; Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) }; //IExternalSignature externalSignature = new X509Certificate2Signature(cert.Certificado, MyDigestAlgorithm); RSACryptoServiceProvider rsa; RSACryptoServiceProvider Provider; IExternalSignature externalSignature = null; if (cert.Certificado.PrivateKey is RSACryptoServiceProvider) { rsa = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; Provider = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm); } else { rsa = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; Provider = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm); } PdfReader pdfReader = new PdfReader(SourcePdfFileName); FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create, FileAccess.ReadWrite); //the output pdf file string path = System.AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; //cria a assinatura PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', path + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf", true); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; Bitmap bmp = INB.Assinador.Model.Graphic.ConfiguraBMP(cert, out Altura, Tipo); //CONFIGURA A APARÊNCIA DO SELO DA ASSINATURA. ConfiguraAparenciaAssinatura(signatureAppearance, Reason, Contact, Location, Creator, bmp, Altura, Largura, X, Y, Rotation, Pagina, pdfReader); //ADICIONA O CARIMBO DO TEMPO. TSAClientBouncyCastle tsaClient = null; if (AddTimeStamper) { //urlTimeStamper = http://timestamp.globalsign.com/scripts/timestamp.dll //urlTimeStamper = "http://timestamp.apple.com/ts01"; tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass, TSAClientBouncyCastle.DEFAULTTOKENSIZE, MyDigestAlgorithm); } IOcspClient ocspClient = new OcspClientBouncyCastle(); List <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(new CrlClientOnline(chain)); //Nota 2: O hash da política de assinatura no atributo id-aa-ets-sigPolicyId da assinatura deve ser o hash interno que está na própria PA e não o hash da PA que se encontra publicada na LPA. if (AplicaPolitica) { SignaturePolicyInfo spi = PoliticaDaAssinatura(); MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES, spi); } else { MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES); } try { signedPdf.Flush(); } catch { } try { signedPdf.Close(); } catch { }; pdfReader.Close(); try { pdfReader.Dispose(); } catch { } }
public void Assinar(string caminhoDocSemAssinatura, string caminhoDocAssinado) { try { X509Store store = new X509Store(StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(store.Certificates, "Assinatura Digital", "Escolha uma assinatura abaixo:", X509SelectionFlag.SingleSelection); X509Certificate2 cert = sel[0]; Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) }; //Console.Write("ANTES"); //IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA-1"); //Console.Write("aqui"); //Get Cert Chain IList <Org.BouncyCastle.X509.X509Certificate> signatureChain = new List <Org.BouncyCastle.X509.X509Certificate>(); X509Chain x509chain = new X509Chain(); x509chain.Build(cert); foreach (X509ChainElement x509ChainElement in x509chain.ChainElements) { signatureChain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate)); } using (var reader = new PdfReader(caminhoDocSemAssinatura)) using (var writer = new FileStream(caminhoDocAssinado, FileMode.Create, FileAccess.Write)) using (var stamper = PdfStamper.CreateSignature(reader, writer, '\0', null, true)) { PdfSignatureAppearance signature = stamper.SignatureAppearance; signature.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED; signature.Reason = "Hospital Austa"; signature.ReasonCaption = "Tipo de Assinatura: "; //Console.Write("ANTES"); //Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair key = DotNetUtilities.GetKeyPair(cert.PrivateKey); //Console.Write("ANTES2"); // var signatureKey = new PrivateKeySignature(cert.PrivateKey, "SHA256"); //Console.Write("depois"); var parser = new Org.BouncyCastle.X509.X509CertificateParser(); var bouncyCertificate = parser.ReadCertificate(cert.RawData); var algorithm = DigestAlgorithms.GetDigest(bouncyCertificate.SigAlgOid); var signatureKey = new X509Certificate2Signature(cert, algorithm); //signatureChain = cert; var standard = CryptoStandard.CADES; signature.SignatureGraphic = Image.GetInstance(@"\\192.168.10.27\a3\certificado.jpg"); signature.SetVisibleSignature(new Rectangle(100, 100, 250, 150), reader.NumberOfPages, "Signature"); signature.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; MakeSignature.SignDetached(signature, signatureKey, signatureChain, null, null, null, 0, CryptoStandard.CMS); } } catch (Exception ex) { throw new Exception(ex.Message); } /*signatureAppearance.SignatureGraphic = Image.GetInstance(pathToSignatureImage); * signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 250, 150), pdfReader.NumberOfPages, "Signature"); * signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; * * MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);*/ }