/// <summary> /// Closes and disposes the in-memory document /// </summary> private void CloseInMemoryDocument() { if (InMemoryDocument != null) { InMemoryDocument.Close(); InMemoryDocument.Dispose(); InMemoryDocument = null; } }
public Guid UploadDocument(Guid userId, string name, string mimeType, Stream document, long length) { byte[] bytes = new byte[length]; document.ReadFill(bytes); var doc = new InMemoryDocument(userId, name, mimeType, bytes); lock (list) list.Add(doc); return doc.Id.DocumentId; }
public string eReceteImzala(string eReceteSourceFilePath, string eReceteDestFilePath, string GelenXML, Boolean DosyayaYaz) { string retSignedXmlPath = null; //Load license from file //LisansHelper.loadFreeLicenseBase64(); //LisansHelper.loadFullTestLicense(); // LisansHelper.loadFreeLicense(); // LisansHelper.loadLicense(); try { // create context with working dir string currentDirectory = Directory.GetCurrentDirectory(); Context context = new Context(currentDirectory); // create signature according to context, // with default type (XADES_BES) XMLSignature signature = new XMLSignature(context); signature.SigningTime = DateTime.Now; if (GelenXML != "") { InMemoryDocument inMMDoc = new InMemoryDocument(System.Text.Encoding.UTF8.GetBytes(GelenXML), "", null, null); signature.addDocument(inMMDoc); } else { // add document as reference, and keep BASE64 version of data // in an <Object tag, in a way that reference points to // that <Object // (embed=true) null signature.addDocument(eReceteSourceFilePath, "text/plain", true); } // bu kismin alternatifi TestEnvelopingSignature dosyasinda var // if (Program.ParamTCKimlikNo != "") if (Program.ParamOto == "1") { SmartCardManagerKimlikNodanSec smc = SmartCardManagerKimlikNodanSec.getInstance(0); // 0 server version // sanirim smc nesnesi getInstance icinde uygun karta gore olusuyor... altta masaustu icin de uygula... 10.12.2015 if (Program.KartOkuyucuYok == 1) { return(null); } ECertificate signingCert = smc.getSignatureCertificate(true, false); //İlk parameter Kart Pin BaseSigner baseSigner = smc.getSigner(Program.PinKodu, signingCert); // "12345" bool validCertificate = isValidCertificate(signingCert); if (!validCertificate) { MesajiIsle("İmza atılmak istenen sertifika geçerli değil." + Program.HataMesaji, 1); return(null); } // add certificate to show who signed the document signature.addKeyInfo(signingCert); //Signer Oluşturma signature.sign(baseSigner); } else { // 1 desktop version // imzalama oncesi kartta instance acma SmartCardManagerKimlikNodanSec smc = SmartCardManagerKimlikNodanSec.getInstance(1); // 1 desktop version // smc nesnesi getInstance icinde uygun karta gore olusacak if (Program.KartOkuyucuYok == 1) { return(null); } ECertificate signingCert = smc.getSignatureCertificate(true, false); //İlk parameter Kart Pin BaseSigner baseSigner = smc.getSigner(Program.PinKodu, signingCert); // "12345" if (baseSigner == null) { return(null); } bool validCertificate = isValidCertificate(signingCert); if (!validCertificate) { MesajiIsle("İmza atılmak istenen sertifika geçerli değil." + Program.HataMesaji, 1); return(null); } if (Program.SertifikaBilgisi != "Sertifika ve Sahiplik Bilgisi: " + signingCert.ToString()) { if (Program.SertifikaBilgisi == "Sertifika ve Sahiplik Bilgisi: ") { MesajiIsle("Akıllı kartı, imza ekranına girmeden evvel takınız." + Program.HataMesaji, 1); return(null); } MesajiIsle("Akıllı kart, imza ekranına girildikten sonra değiştirilmiş, işlemi kart değiştirmeden yapınız." + Program.HataMesaji, 1); return(null); } // add certificate to show who signed the document signature.addKeyInfo(signingCert); //Signer Oluşturma signature.sign(baseSigner); // eski yontem //if (Program.KartOkuyucuYok == 1) return null; //ECertificate signingCert = smc.getSignatureCertificate(true, false); //BaseSigner baseSigner = smc.getSigner(Program.PinKodu, signingCert); // "12345" //bool validCertificate = isValidCertificate(signingCert); //if (!validCertificate) //{ // MesajiIsle("İmza atılmak istenen sertifika geçerli değil." + Program.HataMesaji, 1); // return null; //} //// add certificate to show who signed the document //signature.addKeyInfo(signingCert); ////Signer Oluşturma //signature.sign(baseSigner); } //FileInfo sourceFileInfo = new FileInfo(eReceteSourceFilePath); //string destDirPath = sourceFileInfo.Directory.FullName; if (DosyayaYaz) { retSignedXmlPath = eReceteDestFilePath.Replace(".xml", ".xsig"); FileStream signatureFileStream = new FileStream(retSignedXmlPath, FileMode.Create); signature.write(signatureFileStream); signatureFileStream.Close(); // mesaji main'de button click sonundan buraya aldim if (retSignedXmlPath != null) { // tBoxSignedERecetePath.Text = signedFilePath; MesajiIsle(retSignedXmlPath + " konumunda imzalı E-Reçete oluşturuldu.", 0); } } else { MesajiIsle("E-Reçete imza verisi hazır", 0); } // return retSignedXmlPath; return(signature.Document.OuterXml); } catch (XMLSignatureRuntimeException exc) { // cant create signature MesajiIsle("Hata Oluştu." + exc.Message, 1); } catch (XMLSignatureException exc) { // cant create signature MesajiIsle("Hata Oluştu." + exc.Message, 1); } catch (Exception exc) { // probably couldn't write to the file MesajiIsle("Hata Oluştu." + exc.Message, 1); } // return retSignedXmlPath; return(""); }
public void TestSigProfiles(SignatureParams sigParams, SignatureVerificationResults sigResult) { var ca = new X509Name("CN=ca"); var caKeyPair = CryptoHelpers.GenerateRsaKeyPair(2048); var caCert = CryptoHelpers.GenerateCertificate(ca, ca, caKeyPair.Private, caKeyPair.Public); var notBefore = DateTime.Now; var notAfter = DateTime.Now.AddHours(1); if (!(sigParams.SignatureCertTimeValid ?? true)) { notBefore = DateTime.Now.AddHours(-2); notAfter = DateTime.Now.AddHours(-1); } var signingCertName = new X509Name("CN=singing_cert"); var signingKeyPair = CryptoHelpers.GenerateRsaKeyPair(2048); var signingCert = CryptoHelpers.GenerateCertificate(ca, signingCertName, caKeyPair.Private, signingKeyPair.Public, notBefore, notAfter); var cadesSettings = new CAdESServiceSettings(); if (sigParams.SignatureCertTrusted ?? true) { cadesSettings.TrustedCerts.Add(caCert); } if (sigParams.SignatureCertOCSP ?? true) { var fakeOcsp = unityContainer.Resolve <IOcspSource>() as FakeOnlineOcspSource; fakeOcsp.AddNotRevokedCert(signingCert, caCert); } if (sigParams.OCSPCertTrusted ?? true) { cadesSettings.TrustedCerts.Add(ocspCACert); } if ((sigParams.SignatureCertCRL ?? true)) { var fakeCrl = unityContainer.Resolve <ICrlSource>() as FakeOnlineCrlSource; fakeCrl.AddRevokedCert(!(sigParams.SignatureCertCRL ?? true) ? signingCert : null, caCert, caKeyPair); } if (sigParams.TSSignatureCertTrusted ?? true) { cadesSettings.TrustedCerts.Add(tspCACert); } var cadesService = unityContainer.Resolve <Func <ICAdESServiceSettings, IDocumentSignatureService> >()(cadesSettings); // to be signed var inputData = Encoding.UTF8.GetBytes("anydataanydataanydataanydataanydataanydataanydataanydata"); var inputDocument = new InMemoryDocument(inputData); var signingTime = DateTime.Now; var parameters = new SignatureParameters { SigningCertificate = signingCert, CertificateChain = new X509Certificate[] { signingCert }, SignaturePackaging = SignaturePackaging.DETACHED, SignatureProfile = sigParams.SignatureProfile, SigningDate = signingTime, DigestAlgorithmOID = DigestAlgorithm.SHA256.OID, EncriptionAlgorithmOID = Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.RsaEncryption.Id }; var toBeSignedStream = cadesService.ToBeSigned(inputDocument, parameters); // sign ISigner signer = SignerUtilities.InitSigner(parameters.DigestWithEncriptionOID, true, signingKeyPair.Private, null); toBeSignedStream.Position = 0; toBeSignedStream.Seek(0, SeekOrigin.Begin); var b = Streams.ReadAll(toBeSignedStream); signer.BlockUpdate(b, 0, b.Length); var signatureValue = signer.GenerateSignature(); if (!(sigParams.SignatureValid ?? false)) { signatureValue[0] ^= 1; } // make pkcs7 var signedDocument = cadesService.GetSignedDocument(inputDocument, parameters, signatureValue); // validate var report = cadesService.ValidateDocument(signedDocument, true, inputDocument); var sigInfo = report.SignatureInformationList[0]; Assert.AreEqual(sigResult.SignatureVerification, sigInfo.SignatureVerification.SignatureVerificationResult.IsValid, "Signature value is invalid"); Assert.AreEqual(sigResult.CertPathVerification, sigInfo.CertPathRevocationAnalysis.Summary.IsValid, $"Cert path is invalid: {sigInfo.CertPathRevocationAnalysis.Summary.Description}"); if (sigResult.BESLevel.HasValue) { Assert.AreEqual(sigInfo.SignatureLevelAnalysis.LevelBES.LevelReached.IsValid, sigResult.BESLevel, "BES is not reached"); } if (sigResult.TLevel.HasValue) { Assert.AreEqual(sigResult.TLevel, sigInfo.SignatureLevelAnalysis.LevelT.LevelReached.IsValid, "T is not reached"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelT.SignatureTimestampVerification.All(x => (sigResult.TSignatureVerifications ?? true) && x.SameDigest.IsValid || !(sigResult.TSignatureVerifications ?? true) && !x.SameDigest.IsValid), "T timestamps are not valid"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelT.SignatureTimestampVerification.All(x => (sigResult.TCertPathVerifications ?? true) && x.CertPathVerification.IsValid || !(sigResult.TCertPathVerifications ?? true) && !x.CertPathVerification.IsValid), "T cert paths are not valid"); } if (sigResult.CLevel.HasValue) { Assert.AreEqual(sigResult.CLevel, sigInfo.SignatureLevelAnalysis.LevelC.LevelReached.IsValid, "C is not reached"); Assert.AreEqual(sigResult.CCertRefs, sigInfo.SignatureLevelAnalysis.LevelC.CertificateRefsVerification.IsValid, "C cert refs are not valid"); Assert.AreEqual(sigResult.CRevocationRefs, sigInfo.SignatureLevelAnalysis.LevelC.RevocationRefsVerification.IsValid, "C cert revocations refs are not valid"); } if (sigResult.XLLevel.HasValue) { Assert.AreEqual(sigResult.XLLevel, sigInfo.SignatureLevelAnalysis.LevelXL.LevelReached.IsValid, "XL is not reached"); Assert.AreEqual(sigResult.CCertValues, sigInfo.SignatureLevelAnalysis.LevelXL.CertificateValuesVerification.IsValid, "XL cert values are not valid"); Assert.AreEqual(sigResult.CRevocationRefs, sigInfo.SignatureLevelAnalysis.LevelXL.RevocationValuesVerification.IsValid, "XL cert revocations values are not valid"); } if (sigResult.XType1Level.HasValue) { Assert.AreEqual(sigResult.XType1Level, sigInfo.SignatureLevelAnalysis.LevelX.LevelReached.IsValid, "XType1 is not reached"); Assert.AreEqual(sigResult.CLevel, sigInfo.SignatureLevelAnalysis.LevelC.LevelReached.IsValid, "C is not reached"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelX.SignatureAndRefsTimestampsVerification.All(x => (sigResult.XType1SignatureVerifications ?? true) && x.SameDigest.IsValid || !(sigResult.XType1SignatureVerifications ?? true) && !x.SameDigest.IsValid), "XType1 timestamps are not valid"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelX.SignatureAndRefsTimestampsVerification.All(x => (sigResult.XType1CertPathVerifications ?? true) && x.CertPathVerification.IsValid || !(sigResult.XType1CertPathVerifications ?? true) && !x.CertPathVerification.IsValid), "XType1 cert paths are not valid"); } if (sigResult.XType2Level.HasValue) { Assert.AreEqual(sigResult.XType2Level, sigInfo.SignatureLevelAnalysis.LevelX.LevelReached.IsValid, "XType2 is not reached"); Assert.AreEqual(sigResult.CLevel, sigInfo.SignatureLevelAnalysis.LevelC.LevelReached.IsValid, "C is not reached"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelX.ReferencesTimestampsVerification.All(x => (sigResult.XType2SignatureVerifications ?? true) && x.SameDigest.IsValid || !(sigResult.XType2SignatureVerifications ?? true) && !x.SameDigest.IsValid), "XType2 timestamps are not valid"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelX.ReferencesTimestampsVerification.All(x => (sigResult.XType2CertPathVerifications ?? true) && x.CertPathVerification.IsValid || !(sigResult.XType2CertPathVerifications ?? true) && !x.CertPathVerification.IsValid), "XType2 cert paths are not valid"); } if (sigResult.XLType1Level.HasValue) { Assert.AreEqual(sigResult.XLType1Level, sigInfo.SignatureLevelAnalysis.LevelXL.LevelReached.IsValid, "XLType1 is not reached"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelX.SignatureAndRefsTimestampsVerification.All(x => (sigResult.XType1SignatureVerifications ?? true) && x.SameDigest.IsValid || !(sigResult.XType1SignatureVerifications ?? true) && !x.SameDigest.IsValid), "XType1 timestamps are not valid"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelX.SignatureAndRefsTimestampsVerification.All(x => (sigResult.XType1CertPathVerifications ?? true) && x.CertPathVerification.IsValid || !(sigResult.XType1CertPathVerifications ?? true) && !x.CertPathVerification.IsValid), "XType1 cert paths are not valid"); } if (sigResult.XLType2Level.HasValue) { Assert.AreEqual(sigResult.XLType2Level, sigInfo.SignatureLevelAnalysis.LevelXL.LevelReached.IsValid, "XLType2 is not reached"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelX.ReferencesTimestampsVerification.All(x => (sigResult.XType2SignatureVerifications ?? true) && x.SameDigest.IsValid || !(sigResult.XType2SignatureVerifications ?? true) && !x.SameDigest.IsValid), "XType2 timestamps are not valid"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelX.ReferencesTimestampsVerification.All(x => (sigResult.XType2CertPathVerifications ?? true) && x.CertPathVerification.IsValid || !(sigResult.XType2CertPathVerifications ?? true) && !x.CertPathVerification.IsValid), "XType2 cert paths are not valid"); } if (sigResult.ALevel.HasValue) { Assert.AreEqual(sigResult.ALevel, sigInfo.SignatureLevelAnalysis.LevelA.LevelReached.IsValid, "A is not reached"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelA.ArchiveTimestampsVerification.All(x => (sigResult.ASignatureVerifications ?? true) && x.SameDigest.IsValid || !(sigResult.ASignatureVerifications ?? true) && !x.SameDigest.IsValid), "A timestamps are not valid"); Assert.IsTrue(sigInfo.SignatureLevelAnalysis.LevelA.ArchiveTimestampsVerification.All(x => (sigResult.ACertPathVerifications ?? true) && x.CertPathVerification.IsValid || !(sigResult.ACertPathVerifications ?? true) && !x.CertPathVerification.IsValid), "A cert paths are not valid"); } }