public void SignedDocumentValid() { Keys keys = Keys.Create(); SignedDocument signedDocument = SignedDocument.Create(keys, DocumentConverter.STRING.Get("It's a test with a basic document.")); Assert.IsTrue(signedDocument.Verify()); }
public string createParalelSignature(string eReceteSourceFilePath) { string retSignedXmlPath = null; //Load license from file //LisansHelper.loadFreeLicenseBase64(); LisansHelper.loadLicense(); try { // create context with working dir string currentDirectory = Directory.GetCurrentDirectory(); Context context = new Context(currentDirectory); SignedDocument signatures = new SignedDocument(context); //First Signature XMLSignature signature1 = signatures.createSignature(); signature1.SigningTime = DateTime.Now; signature1.addDocument(eReceteSourceFilePath, null, true); KeyOrSmartCardSignManager keyOrSmartCardSignManager = KeyOrSmartCardSignManager.Instance; ECertificate signingCert = keyOrSmartCardSignManager.getSigningCertificate(); 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 signature1.addKeyInfo(signingCert); BaseSigner smartCardSigner = keyOrSmartCardSignManager.getSigner(signingCert); signature1.sign(smartCardSigner); //Second Signature XMLSignature signature2 = signatures.createSignature(); signature2.SigningTime = DateTime.Now; signature2.addDocument(eReceteSourceFilePath, null, true); signature2.addKeyInfo(signingCert); signature2.sign(smartCardSigner); FileInfo sourceFileInfo = new FileInfo(eReceteSourceFilePath); string destDirPath = sourceFileInfo.Directory.FullName; retSignedXmlPath = destDirPath + "/" + sourceFileInfo.Name.Replace(".xml", "_PARALEL.xsig"); FileStream signatureFileStream = new FileStream(retSignedXmlPath, FileMode.Create); signatures.write(signatureFileStream); signatureFileStream.Close(); return(retSignedXmlPath); } 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); }
public void CreateTransactions() { Keys user1keys = Keys.Create(); Keys user2Keys = Keys.Create(); ISignedTransaction signedTransaction = SignedDocument.Create(user1keys, DocumentConverter.STRING.Get("It's a test with a basic document.")) .ToSignedTransactionRoot() .Add(user1keys, DocumentConverter.STRING.Get("Updated.")) .Add(user2Keys, DocumentConverter.STRING.Get("Add a signature to the document.")); Assert.IsTrue(signedTransaction.Verify()); }
public void CorruptedUser() { Keys keys = Keys.Create(); ISignedDocument signedDocument = SignedDocument.Create(keys, DocumentConverter.STRING.Get("It's a test with a basic document.")); var corruptedDocument = new SignedDocument( document: signedDocument.Document, publicKey: Keys.Create().PublicKey, signature: signedDocument.Signature); Assert.IsTrue(signedDocument.Verify()); Assert.IsFalse(corruptedDocument.Verify()); }
public void SignDocument(PackageId packageId, string documentName, CapturedSignature capturedSignature) { Silanis.ESL.API.Package package = packageService.GetPackage(packageId); foreach (Silanis.ESL.API.Document document in package.Documents) { if (document.Name.Equals(documentName)) { document.Approvals.Clear(); SignedDocument signedDocument = signingService.ConvertToSignedDocument(document); signedDocument.Handdrawn = capturedSignature.Handdrawn; signingService.SignDocument(packageId, signedDocument); } } }
public void ExtractDocumentsOfRoot() { string documentString = "It's a test with a basic document."; Keys user1keys = Keys.Create(); IEnumerable <ISignedDocument> signedDocuments = SignedDocument.Create(user1keys, DocumentConverter.STRING.Get(documentString)) .ToSignedTransactionRoot() .ToEnumerable(); string[] documentStrings = signedDocuments .Select(x => DocumentConverter.STRING.Get(x.Document)) .ToArray(); Assert.IsTrue(signedDocuments.All(x => x.Verify())); Assert.IsTrue(documentStrings.Count() == 1); Assert.AreEqual(documentString, documentStrings.Single()); }
public void CorruptedTransactions() { Keys user1keys = Keys.Create(); Keys user2Keys = Keys.Create(); ISignedDocument signedDocument = SignedDocument.Create(user1keys, DocumentConverter.STRING.Get("It's a test with a basic document.")); ISignedTransaction signedTransaction1 = signedDocument .ToSignedTransactionRoot() .Add(user1keys, DocumentConverter.STRING.Get("Updated.")); ISignedTransaction signedTransaction2 = signedTransaction1 .Add(user2Keys, DocumentConverter.STRING.Get("Add a signature to the document.")); ISignedTransaction corruptedTransaction = new SignedTransaction(signedTransaction1.PreviousSignedTransaction, DocumentConverter.STRING.Get("Replace with a corrupted document"), signedTransaction1.PublicKey, signedTransaction1.Signature); signedTransaction2 = new SignedTransaction(corruptedTransaction, signedTransaction2.Document, signedTransaction2.PublicKey, signedTransaction2.Signature); Assert.IsFalse(signedTransaction2.Verify()); }
internal void SignDocument(PackageId packageId, SignedDocument signedDocument) { string path = template.UrlFor(UrlTemplate.SIGN_DOCUMENT_PATH) .Replace("{packageId}", packageId.Id) .Build(); try { string json = JsonConvert.SerializeObject(signedDocument, settings); restClient.Post(path, json); } catch (OssServerException e) { throw new OssServerException("Could not sign document." + " Exception: " + e.Message, e.ServerError, e); } catch (Exception e) { throw new OssException("Could not sign document." + " Exception: " + e.Message, e); } }
public bool ValidateDocument([FromBody] string Document, [FromBody] string UniqueId) { if (Document == null || UniqueId == null) { return(false); } // calculate the MD5 of the uploaded document string sChecksum = Checksum.CalculateMD5(Convert.FromBase64String(Document)); Blockchain newDocument; // load the associated blockchain if (System.IO.File.Exists( Server.MapPath("~/App_Data/Blockchains/" + UniqueId + ".bc"))) { string bc = System.IO.File.ReadAllText( Server.MapPath("~/App_Data/Blockchains/" + UniqueId + ".bc")); newDocument = JsonConvert.DeserializeObject <Blockchain>(bc); // get the SignedDocument object from the block SignedDocument signedDocument = JsonConvert.DeserializeObject <SignedDocument>(newDocument.GetCurrentBlock().Data); // compare the checksum in the stored block // with the checksum of the uploaded document if (signedDocument.Checksum == sChecksum) { return(true); // document valid } else { return(false); // not valid } } else { return(false); // blockchain doesn't exist } }
public void ExtractSignedDocuments() { string fistDocumentString = "It's a test with a basic document."; Keys user1keys = Keys.Create(); Keys user2Keys = Keys.Create(); IEnumerable <ISignedDocument> signedDocuments = SignedDocument.Create(user1keys, DocumentConverter.STRING.Get(fistDocumentString)) .ToSignedTransactionRoot() .Add(user1keys, DocumentConverter.STRING.Get("Updated.")) .Add(user2Keys, DocumentConverter.STRING.Get("Add a signature to the document.")) .ToEnumerable(); string[] documentStrings = signedDocuments .Select(x => DocumentConverter.STRING.Get(x.Document)) .ToArray(); Assert.IsTrue(signedDocuments.All(x => x.Verify())); Assert.IsTrue(documentStrings.Count() == 3); Assert.AreEqual(fistDocumentString, documentStrings.Last()); }
internal SignedDocument ConvertToSignedDocument(OneSpanSign.API.Document document) { SignedDocument signedDocument = new SignedDocument(); signedDocument.Id = document.Id; signedDocument.Name = document.Name; signedDocument.Description = document.Description; signedDocument.Approvals = document.Approvals; signedDocument.External = document.External; signedDocument.Index = document.Index; signedDocument.Extract = document.Extract; signedDocument.ExtractionTypes = document.ExtractionTypes; signedDocument.Fields = document.Fields; signedDocument.Data = document.Data; signedDocument.SignedHash = document.SignedHash; signedDocument.Pages = document.Pages; signedDocument.Size = document.Size; signedDocument.Status = document.Status; signedDocument.SignerVerificationToken = document.SignerVerificationToken; signedDocument.Tagged = document.Tagged; return(signedDocument); }
/** * Validate function for parallel signatures * @param fileName name of the signature file to be validated */ public static void validateParallel(String fileName) { Context context = new Context(Conn.ROOT_DIR + "efatura\\config\\"); // add external resolver to resolve policies context.addExternalResolver(getPolicyResolver()); List <XMLSignature> xmlSignatures = new List <XMLSignature>(); // get signature as signed document in order to be able to validate parallel ones SignedDocument sd = new SignedDocument(new FileDocument(new FileInfo(fileName)), context); xmlSignatures.AddRange(sd.getRootSignatures()); foreach (var xmlSignature in xmlSignatures) { // no params, use the certificate in key info ValidationResult result = xmlSignature.verify(); Console.WriteLine(result.toXml()); Assert.True(result.getType() == ValidationResultType.VALID, "Cant verify " + fileName); UnsignedSignatureProperties usp = xmlSignature.QualifyingProperties.UnsignedSignatureProperties; if (usp != null) { IList <XMLSignature> counterSignatures = usp.AllCounterSignatures; foreach (XMLSignature counterSignature in counterSignatures) { ValidationResult counterResult = xmlSignature.verify(); Console.WriteLine(counterResult.toXml()); Assert.True(counterResult.getType() == ValidationResultType.VALID, "Cant verify counter signature" + fileName + " : " + counterSignature.Id); } } } }
public SignedDocumentsPage() { NavigationPage.SetHasBackButton(this, false); listView = new CustomListView { ItemsSource = requests, RowHeight = 100, IsPullToRefreshEnabled = true, Margin = new Thickness(Device.OnPlatform(0, 5, 5), Device.OnPlatform(5, 0, 0), 5, 0), HasUnevenRows = true, ItemTemplate = new DataTemplate(() => { Grid gridTitle = new Grid { VerticalOptions = LayoutOptions.FillAndExpand, RowDefinitions = { new RowDefinition { Height = GridLength.Auto } }, ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }, new ColumnDefinition { Width = 80 } } }; Grid gridStatus = new Grid { VerticalOptions = LayoutOptions.FillAndExpand, RowDefinitions = { new RowDefinition { Height = GridLength.Star } }, ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }, new ColumnDefinition { Width = 150 } } }; gridTitle.HorizontalOptions = LayoutOptions.FillAndExpand; Label labelTitle = new Label(); labelTitle.SetBinding(Label.TextProperty, "Title"); labelTitle.HorizontalOptions = LayoutOptions.FillAndExpand; labelTitle.VerticalOptions = LayoutOptions.FillAndExpand; labelTitle.FontSize = 18; labelTitle.LineBreakMode = LineBreakMode.WordWrap; Label labelData = new Label(); labelData.SetBinding(Label.TextProperty, "DateStr"); labelData.HorizontalOptions = LayoutOptions.EndAndExpand; labelData.FontSize = 12; labelData.HorizontalTextAlignment = TextAlignment.End; labelData.TextColor = Color.FromHex("#0A80D0"); labelData.Margin = new Thickness(0, 2, 0, 0); Label labelDescription = new Label(); labelDescription.SetBinding(Label.TextProperty, "Description"); labelDescription.FontSize = 14; labelDescription.HorizontalOptions = LayoutOptions.FillAndExpand; labelDescription.VerticalOptions = LayoutOptions.FillAndExpand; labelDescription.LineBreakMode = LineBreakMode.TailTruncation; Label labelAuthors = new Label(); labelAuthors.SetBinding(Label.TextProperty, "Author"); labelAuthors.TextColor = Color.FromHex("#0A80D0"); labelAuthors.FontSize = 12; labelAuthors.HorizontalOptions = LayoutOptions.FillAndExpand; labelAuthors.VerticalOptions = LayoutOptions.FillAndExpand; labelAuthors.VerticalTextAlignment = TextAlignment.End; labelAuthors.Margin = new Thickness(0, 5, 0, 0); Label labelStatus = new Label(); labelStatus.SetBinding(Label.TextProperty, "Status"); //labelStatus.TextColor = Color.FromHex("#0A80D0"); labelStatus.FontAttributes = FontAttributes.Italic; labelStatus.FontSize = 12; labelStatus.HorizontalOptions = LayoutOptions.FillAndExpand; labelStatus.VerticalOptions = LayoutOptions.FillAndExpand; labelStatus.HorizontalTextAlignment = TextAlignment.End; labelStatus.VerticalTextAlignment = TextAlignment.End; labelStatus.Margin = new Thickness(0, 5, 0, 0); gridTitle.Children.Add(labelTitle, 0, 0); gridTitle.Children.Add(labelData, 1, 0); gridTitle.HorizontalOptions = LayoutOptions.FillAndExpand; gridTitle.VerticalOptions = LayoutOptions.FillAndExpand; gridStatus.Children.Add(labelAuthors, 0, 0); gridStatus.Children.Add(labelStatus, 1, 0); gridStatus.VerticalOptions = LayoutOptions.FillAndExpand; gridStatus.HorizontalOptions = LayoutOptions.FillAndExpand; var vc = new ViewCell { View = new StackLayout { VerticalOptions = LayoutOptions.CenterAndExpand, Padding = new Thickness(Device.OnPlatform(10, 0, 0), 5), Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { new StackLayout { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.FillAndExpand, Spacing = 0, Children = { gridTitle, labelDescription, gridStatus } } } } }; return(vc); }) }; Label labelEmpty = new Label(); labelEmpty.Text = AppResources.NO_REQUESTS; labelEmpty.HorizontalOptions = LayoutOptions.FillAndExpand; labelEmpty.VerticalOptions = LayoutOptions.Start; labelEmpty.Margin = new Thickness(20); labelEmpty.HorizontalTextAlignment = TextAlignment.Center; labelEmpty.FontSize = 16; this.Title = AppResources.FINISHED_REQUESTS; var view = new StackLayout { Orientation = StackOrientation.Vertical, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { labelEmpty, listView } }; this.Content = view; requests.CollectionChanged += (sender, e) => { Device.BeginInvokeOnMainThread(() => { labelEmpty.IsVisible = requests.Count == 0; view.ForceLayout(); }); }; Action refreshSignatures = async() => { try { listView.IsRefreshing = true; await LoadSignatureRequests(0); listView.IsRefreshing = false; } catch (Exception e) { listView.IsRefreshing = false; Device.BeginInvokeOnMainThread(() => { DialogHelper.ShowAlertOK(AppResources.APP_TITLE, AppResources.ERROR_UNABLE_TO_REACH_REQUEST_LIST_API); }); } }; listView.RefreshCommand = new Command(refreshSignatures); listView.ItemSelected += async delegate(object sender, SelectedItemChangedEventArgs e) { SignedDocument signedDocument = (SignedDocument)e.SelectedItem; ((ListView)sender).SelectedItem = null; if (signedDocument == null) { return; } if (signedDocument.Documents.Count > 1) { var childPage = new ChildDocumentPage(signedDocument, false); await Navigation.PushAsync(childPage); await childPage.PageClosedTask; } else { try { Document doc = signedDocument.Documents.First(); using (var progress = DialogHelper.ShowProgress(AppResources.LOADING_DOCUMENT)) { await doc.LoadXmlDocument(); } SignaturePage assinarPage = new SignaturePage(doc.Title, signedDocument, doc, false); await Navigation.PushAsync(assinarPage); await assinarPage.PageClosedTask; } catch (Exception ex) { UserDialogs.Instance.Alert(AppResources.DOCUMENT_LOADING_FAILED, AppResources.APP_TITLE, AppResources.OK); } } }; listView.ItemAppearing += async(sender, e) => { var selected = e.Item as SignedDocument; if (requests.MoreAvailable && requests.ToList().Last() == selected) { await LoadSignatureRequests(requests.CurrentPage + 1); } }; bool showingActionSheet = false; listView.LongClicked += async(sender, e) => { if (showingActionSheet) { return; } SignedDocument selected = (SignedDocument)e.Item; List <string> buttons = new List <string> { AppResources.DOCUMENT_METADATA }; if (selected.AttachmentCount > 0) { buttons.Add(AppResources.ATTACHMENTS); } Dictionary <string, InboxMessageAction> dictActions = selected.Actions. Where(a => AppResources.ResourceManager.GetString(a.Name) != null). ToDictionary(x => AppResources.ResourceManager.GetString(x.Name), x => x); if (dictActions.Keys.Count > 0) { buttons.AddRange(dictActions.Keys); } showingActionSheet = true; var selectedActionName = await this.DisplayActionSheet(AppResources.ACTIONS, AppResources.CANCEL, null, buttons.ToArray()); showingActionSheet = false; if (string.IsNullOrEmpty(selectedActionName)) { return; } if (selectedActionName == AppResources.ATTACHMENTS) { await Navigation.PushAsync(new AttachmentsPage(selected)); } else if (selectedActionName == AppResources.DOCUMENT_METADATA) { await Navigation.PushAsync(new DocumentInfo(selected)); } else if (dictActions.ContainsKey(selectedActionName)) { var action = dictActions[selectedActionName]; if (action != null) { await actionController.ExecuteAction(action, async() => await LoadSignatureRequests(0)); } } }; Device.BeginInvokeOnMainThread(() => { LoadSignatureRequests(0); }); }
/// <summary> /// /// </summary> /// <param name="fileDoc"></param> /// <returns></returns> public static bool VerifyPadesSignature(DocsPaVO.documento.FileDocumento fileDoc) { SignedDocument si = new SignedDocument(); VerifyTimeStamp verifyTimeStamp = new VerifyTimeStamp(); string padesSignAlgorithm = null; dpaItextSharp.text.pdf.PdfReader pdfReader = null; try { pdfReader = new dpaItextSharp.text.pdf.PdfReader(fileDoc.content); } catch { return(false); } dpaItextSharp.text.pdf.AcroFields af = pdfReader.AcroFields; List <string> signNames = af.GetSignatureNames().Cast <string>().ToList <string>(); if (signNames.Count == 0) //Firma non è presente { return(false); } List <DocsPaVO.documento.SignerInfo> siList = new List <DocsPaVO.documento.SignerInfo>(); bool verResult = true; foreach (string name in signNames) { List <DocsPaVO.documento.TSInfo> tsLst = new List <DocsPaVO.documento.TSInfo>(); dpaItextSharp.text.pdf.PdfPKCS7 pk = af.VerifySignature(name); try { padesSignAlgorithm = "PADES " + pk.GetHashAlgorithm(); } catch (Exception exalg) { padesSignAlgorithm = "PADES : errore ricavando l'algo Hash:" + exalg.Message; } byte[] cert = pk.SigningCertificate.GetEncoded(); DocsPaVO.documento.SignerInfo sinfo = si.GetCertSignersInfo(cert); sinfo.SignatureAlgorithm = padesSignAlgorithm; sinfo.SigningTime = pk.SignDate; if (verResult) //fino a che è true verifica { verResult = pk.Verify(); } if (pk.TimeStampToken != null) { //Ricavo il certificato ICollection certsColl = pk.TimeStampToken.GetCertificates("COLLECTION").GetMatches(null); DocsPaVO.documento.TSInfo timeStamp = verifyTimeStamp.getTSCertInfo(certsColl); timeStamp.TSdateTime = pk.TimeStampToken.TimeStampInfo.GenTime.ToLocalTime(); timeStamp.TSserialNumber = pk.TimeStampToken.TimeStampInfo.SerialNumber.ToString(); timeStamp.TSimprint = Convert.ToBase64String(pk.TimeStampToken.TimeStampInfo.TstInfo.MessageImprint.GetEncoded()); timeStamp.TSType = DocsPaVO.documento.TsType.PADES; tsLst.Add(timeStamp); } if (tsLst.Count > 0) { sinfo.SignatureTimeStampInfo = tsLst.ToArray(); } siList.Add(sinfo); } DocsPaVO.documento.VerifySignatureResult result = new DocsPaVO.documento.VerifySignatureResult(); if (verResult) { result.StatusCode = 0; result.StatusDescription = "La Verifica OK, ma senza controllo CRL"; } else { result.StatusCode = -1; result.StatusDescription = "La Verifica di almeno un firmatario e Fallita"; } List <DocsPaVO.documento.PKCS7Document> pkcsDocs = new List <DocsPaVO.documento.PKCS7Document>(); if ((fileDoc.signatureResult != null) && (fileDoc.signatureResult.PKCS7Documents != null) && (fileDoc.signatureResult.PKCS7Documents.Length > 0)) { foreach (DocsPaVO.documento.PKCS7Document docs in fileDoc.signatureResult.PKCS7Documents) { pkcsDocs.Add(docs); } } pkcsDocs.Add(new DocsPaVO.documento.PKCS7Document { SignersInfo = siList.ToArray(), SignAlgorithm = padesSignAlgorithm, DocumentFileName = fileDoc.nomeOriginale, SignHash = "Non Disponibile per la firma PADES", SignatureType = DocsPaVO.documento.SignType.PADES }); result.PKCS7Documents = pkcsDocs.ToArray(); result.FinalDocumentName = fileDoc.name; fileDoc.signatureResult = result; return(false); }
public ActionResult StoreDocument( [FromBody] string Document, [FromBody] string UniqueId, [FromBody] string SignerName) { byte[] bPDF; // create temporary ServerTextControl using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl()) { tx.Create(); // load the document tx.Load(Convert.FromBase64String(Document), TXTextControl.BinaryStreamType.InternalUnicodeFormat); TXTextControl.SaveSettings saveSettings = new TXTextControl.SaveSettings() { CreatorApplication = "TX Text Control Sample Application", }; // save the document as PDF tx.Save(out bPDF, TXTextControl.BinaryStreamType.AdobePDF, saveSettings); } // calculate the MD5 checksum of the binary data // and store in SignedDocument object SignedDocument document = new SignedDocument() { Checksum = Checksum.CalculateMD5(bPDF) }; // define a Blockchain object Blockchain bcDocument; // if the blockchain exists, load it if (System.IO.File.Exists( Server.MapPath("~/App_Data/Blockchains/" + UniqueId + ".bc"))) { string bc = System.IO.File.ReadAllText( Server.MapPath("~/App_Data/Blockchains/" + UniqueId + ".bc")); bcDocument = JsonConvert.DeserializeObject <Blockchain>(bc); } else { bcDocument = new Blockchain(true); // otherwise create a new blockchain } // add a new block to the blockchain and store the SignedDocument object bcDocument.AddBlock(new Block(DateTime.Now, null, JsonConvert.SerializeObject(document))); // store the blockchain as a file System.IO.File.WriteAllText( Server.MapPath("~/App_Data/Blockchains/" + UniqueId + ".bc"), JsonConvert.SerializeObject(bcDocument)); // create and return a view model with the PDF and the unique document ID StoredDocument storedDocument = new StoredDocument() { PDF = Convert.ToBase64String(bPDF), DocumentId = UniqueId }; return(new JsonResult() { Data = storedDocument, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }