/// <summary> /// verify data signature with public key /// </summary> /// <param name="macdata">source data</param> /// <param name="mac">signature string</param> /// <param name="pkInfo">public key</param> /// <returns>verify result</returns> public static bool VerifyData(string macdata, string mac, string pkInfo) { byte[] data = Encoding.UTF8.GetBytes(macdata); byte[] signature = Convert.FromBase64String(mac); string pub; if (!pkInfo.Contains("CERTIFICATE") && !pkInfo.Contains("PUBLIC KEY")) { pub = ReadPK(pkInfo); } else { pub = pkInfo; } Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters ecdsaPublicKey = null; if (pub.Contains("CERTIFICATE")) { Org.BouncyCastle.X509.X509Certificate cert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(Encoding.UTF8.GetBytes(pub)); ecdsaPublicKey = (Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters)cert.GetPublicKey(); } else if (pub.Contains("PUBLIC KEY")) { TextReader ptr = new StringReader(pub); Org.BouncyCastle.OpenSsl.PemReader pem = new Org.BouncyCastle.OpenSsl.PemReader(ptr); ecdsaPublicKey = (Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters)pem.ReadObject(); } string curveName = "P-256"; var nistCurve = Org.BouncyCastle.Asn1.Nist.NistNamedCurves.GetByName(curveName); return(nistCurve.Verify(ecdsaPublicKey, data, signature)); }
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 async Task InitializeAsync() { ReceiverCertificates = await ReceiverCertificates.Load().ConfigureAwait(false); var cb = new ContainerBuilder(); cb.RegisterType <MyHttpClientFactory>().AsImplementedInterfaces(); cb.RegisterType <DrvExtraValidatorFactory>().As <IDrvDsvExtra14ValidatorFactory>(); cb.RegisterType <MyRequestMessageValidator>().As <IRequestMessageValidator>(); cb.RegisterType <RequestClient>().AsSelf() .WithParameter( (pi, ctx) => pi.ParameterType == typeof(AbsenderOnlineversand), (pi, ctx) => CustomerData.Sender) .WithParameter( (pi, ctx) => pi.ParameterType == typeof(Firma), (pi, ctx) => CustomerData.Company) .WithParameter( (pi, ctx) => pi.Name == "isTest" && pi.ParameterType == typeof(bool), (pi, ctx) => true) .WithParameter( (pi, ctx) => pi.ParameterType == typeof(IExtraEncryptionHandler), (pi, ctx) => { var receiverCert = ReceiverCertificates.Certificates[CustomerData.DsrvBn]; var senderPkcsStore = new Pkcs12Store(new MemoryStream(CustomerData.SenderCertificate.Export(X509ContentType.Pkcs12)), new char[0]); var receiverCertBc = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(receiverCert.RawData); var encryption = new BouncyCastlePkcs7EncryptionHandler(senderPkcsStore, receiverCertBc); return(encryption); }); Container = cb.Build(); }
private void sign(X509Certificate2 cert, String imput, String output) { string SourcePdfFileName = imput; string DestPdfFileName = output; string requerente = ""; 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(SourcePdfFileName); FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create); //the output pdf file PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0'); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; requerente = cert.Subject.Replace("CN=", "").Replace("OU=", "").Replace("DC=", "").Replace("O=", "").Replace("C=", ""); signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(250, 30, 550, 80), 1, "Signature"); signatureAppearance.Layer2Text = "Assinado de forma digital por " + requerente + Environment.NewLine + "Dados:" + DateTime.Now; string pathImage = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "assinatura.png"); var image = iTextSharp.text.Image.GetInstance(pathImage); signatureAppearance.SignatureGraphic = image; //signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; //signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS); }
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); }
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"); } }
/// <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 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 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); }
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); }
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 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; }
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); }
/// <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(); } } }
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 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); }
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); }
/// <summary> /// Initialisiert eine neue Instanz der <see cref="Pkcs7EncryptionHandler"/> Klasse. /// </summary> /// <param name="senderCertificate">Das X509-Zertifikat des Absenders (PKCS#12)</param> /// <param name="receiverCertificate">Das X509-Zertifikat des Empfängers</param> /// <param name="oldSenderCertificates">Die abgelaufenen X509-Zertifikate des Absenders</param> public Pkcs7EncryptionHandler(X509Certificate2 senderCertificate, X509Certificate2 receiverCertificate, IEnumerable<X509Certificate2> oldSenderCertificates = null) { #if NET45 _encryptionHandler = new NativePkcs7EncryptionHandler(senderCertificate, receiverCertificate, oldSenderCertificates); #else var senderCert = new Pkcs12Store(new MemoryStream(senderCertificate.Export(X509ContentType.Pkcs12)), new char[0]); var receiverCert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(receiverCertificate.RawData); var oldSenderCerts = oldSenderCertificates?.Select(cert => new Pkcs12Store(new MemoryStream(cert.Export(X509ContentType.Pkcs12)), new char[0])); _encryptionHandler = new BouncyCastlePkcs7EncryptionHandler(senderCert, receiverCert, oldSenderCerts); #endif }
/// <summary> /// Create a X509Certificate2 with a private key by combining /// the new certificate with a private key from an RSA key. /// </summary> public static X509Certificate2 CreateCertificateWithPrivateKey( X509Certificate2 certificate, RSA privatekey) { using (var cfrg = new CertificateFactoryRandomGenerator()) { var random = new Org.BouncyCastle.Security.SecureRandom(cfrg); Org.BouncyCastle.X509.X509Certificate x509 = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(certificate.RawData); return(CreateCertificateWithPrivateKey(x509, certificate.FriendlyName, GetPrivateKeyParameter(privatekey), random)); } }
} // 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
/// <summary> /// Returns if a self signed certificate is properly signed. /// </summary> private static bool IsSignatureValid(X509Certificate2 cert) { Org.BouncyCastle.X509.X509Certificate bcCert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(cert.RawData); try { bcCert.Verify(bcCert.GetPublicKey()); } catch { return(false); } return(true); }
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); }
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); }
} // 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); }
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 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); }
/// <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); } }
/// <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()); }
/// <summary> /// Imports the certificate(s) from the specified stream. /// </summary> /// <remarks> /// Imports the certificate(s) from the specified stream. /// </remarks> /// <param name="stream">The stream to import.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred reading the stream. /// </exception> public void Import(System.IO.Stream stream) { if (stream == null) { throw new System.ArgumentNullException(nameof(stream)); } Org.BouncyCastle.X509.X509CertificateParser parser = new Org.BouncyCastle.X509.X509CertificateParser(); foreach (Org.BouncyCastle.X509.X509Certificate certificate in parser.ReadCertificates(stream)) { if (unique.Add(certificate)) { certs.Add(certificate); } } }
} // 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); }