Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added document signing-in #1

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 86 additions & 61 deletions DocumentSigner.cs
Original file line number Diff line number Diff line change
@@ -1,87 +1,112 @@
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.Configuration;
using iTextSharp.text.pdf;
using Org.BouncyCastle.Security;
using X509Certificate = Org.BouncyCastle.X509.X509Certificate;
using iTextSharp.text.pdf.security;
using System.Text;


namespace DesktopDocumentSigner
{
internal class DocumentSigner
{
private string location = "Location";
private const string FIELD_NAME = "Digitally signed";
private string _certificateThumbprint;
private string _encoded_file;
private string _documentName;
private string _location;
private PdfReader _inputPdf;
private readonly iTextSharp.text.Rectangle PAGE_RECT = new iTextSharp.text.Rectangle(375, 565, 575, 715);
private BaseFont _base_font;
private byte[] file;

private MemoryStream SignDocument(byte[] file, string document_name)
public DocumentSigner(string certificateThumbprint, string encodedFile, string documentName, string location)
{
_certificateThumbprint = certificateThumbprint;
_encoded_file = encodedFile;
_documentName = documentName;
_location = location;
file = Convert.FromBase64String(_encoded_file);
_inputPdf = new PdfReader(file);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
_base_font = BaseFont.CreateFont("OpenSans-Regular.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}

X509Certificate2 certificate = GetCertificateFromStore();
if (certificate != null)
public static X509Certificate2? GetCertificateFromStore(string certificateThumbprint)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var certificate2Collection = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
if (certificate2Collection.Count == 0)
{
var arialBaseFont = BaseFont.CreateFont("ArialCE.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

IList<X509Certificate> chain = new List<X509Certificate>();
PdfReader inputPdf = new PdfReader(file);
using (MemoryStream signedPdf = new MemoryStream())
return null;
}
else
{
foreach (X509Certificate2 certificate in certificate2Collection)
{
IExternalSignature externalSignature = new X509Certificate2Signature(certificate, "SHA-256");
PdfStamper pdfStamper = PdfStamper.CreateSignature(inputPdf, signedPdf, '\0');
PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
pdfStamper.AcroFields.AddSubstitutionFont(arialBaseFont);
signatureAppearance.Layer2Font = new iTextSharp.text.Font(arialBaseFont, 12f);
signatureAppearance.Location = location;
if (document_name.Contains("DRIVER_CALL"))
if (certificate.HasPrivateKey && certificate.Thumbprint.ToLower() == certificateThumbprint)
{
try
{
signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(350, 50, 550, 200), inputPdf.NumberOfPages - 1, "Digitally signed");
}
catch (ArgumentException e)
{
return new MemoryStream(file);
}
return certificate;
}
else if (document_name.Contains("ORDER_WITH_EIF"))
{
try
{
signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(375, 565, 575, 715), 1, "Digitally signed");
}
catch (ArgumentException e)
{
Console.WriteLine($"Dokument {document_name} již byl podepsán, vrácen beze změny ({DateTime.Now}).");
return new MemoryStream(file);
}
}
else
{
try
{
signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(350, 50, 550, 200), inputPdf.NumberOfPages, "Digitally signed");
}
catch (ArgumentException e)
{
Console.WriteLine($"Dokument {document_name} již byl podepsán, vrácen beze změny ({DateTime.Now}).");
return new MemoryStream(file);
}

}
signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
chain.Add(DotNetUtilities.FromX509Certificate(certificate));
MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
inputPdf.Close();
pdfStamper.Close();

Console.WriteLine($"Dokument {document_name} byl podepsán ({DateTime.Now}).");
return signedPdf;
}
}
return new MemoryStream();
store.Close();
return null;
}

private int CalculatePage()
{
if (_documentName.Contains("ORDER_WITH_EIF"))
{
return 1;
}
else
{
return _inputPdf.NumberOfPages;
}
}

private X509Certificate2 GetCertificateFromStore()
public SignatureResult SignDocument()
{
throw new NotImplementedException();
X509Certificate2? certificate = GetCertificateFromStore(_certificateThumbprint);
if (certificate != null)
{
string resultText = "";
IList<X509Certificate> chain = new List<X509Certificate>();
MemoryStream signedPdf = new MemoryStream();
IExternalSignature externalSignature = new X509Certificate2Signature(certificate, "SHA-256");
PdfStamper pdfStamper = PdfStamper.CreateSignature(_inputPdf, signedPdf, '\0');
PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
pdfStamper.AcroFields.AddSubstitutionFont(_base_font);
signatureAppearance.Layer2Font = new iTextSharp.text.Font(_base_font, 12f);
signatureAppearance.Location = _location;
try
{
signatureAppearance.SetVisibleSignature(PAGE_RECT, CalculatePage(), FIELD_NAME);
}
catch (ArgumentException e)
{
resultText = $"Dokument {_documentName} již byl podepsán, vrácen beze změny ({DateTime.Now}).";
signedPdf = new MemoryStream(file);
}
signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
chain.Add(DotNetUtilities.FromX509Certificate(certificate));
MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
_inputPdf.Close();
pdfStamper.Close();
string signedPDF_base64 = Convert.ToBase64String(signedPdf.ToArray());
SignatureResult signatureResult = new SignatureResult{
ResultText = resultText,
SignedDocumentBase64 = signedPDF_base64

};
return signatureResult;
}
else
{
return new SignatureResult{ ResultText = $"Dokument {_documentName} není možné podepsat." };
}
}
}
}
7 changes: 2 additions & 5 deletions MainPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,6 @@
Style="{StaticResource Headline}"
SemanticProperties.HeadingLevel="Level1" />

<Label
Text="Waiting for Documents"
Style="{StaticResource SubHeadline}"
SemanticProperties.HeadingLevel="Level2" />

<CollectionView
x:Name="LogCollection"
ItemsSource="{Binding LogEntries}"
Expand Down Expand Up @@ -61,8 +56,10 @@

<Button
Text="Save"
x:Name="Save"
FontSize="16"
Padding="10"
Clicked="Save_Clicked"
/>
</HorizontalStackLayout>

Expand Down
162 changes: 159 additions & 3 deletions MainPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,178 @@
using System.Collections.ObjectModel;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Org.BouncyCastle.Bcpg;

namespace DesktopDocumentSigner
{
public partial class MainPage : ContentPage
{
int count = 0;
public ObservableCollection<string> LogEntries { get; set; }
private static string _filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "settings.json");
private Settings? settings;
private const string _listenOn = "http://127.0.0.1:8080/";
private static HttpListener _httpListener = new HttpListener();

public MainPage()
{
InitializeComponent();
LogEntries = new ObservableCollection<string>
{
"App started",
"No documents detected",
"Ready for new document"
"App started"
};
BindingContext = this;
LoadSettings();
StartHttpServer();
}

private async void StartHttpServer()
{
_httpListener.Prefixes.Add(_listenOn);

try
{
_httpListener.Start();

while (true)
{
var context = await _httpListener.GetContextAsync();
HandleRequest(context);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}

private void HandleRequest(HttpListenerContext context)
{
try
{
var request = context.Request;
var response = context.Response;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST");
context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization");

if (request.HttpMethod == "POST")
{
HandlePostRequest(request, response);
}
else
{
HandleDefaultRequest(response);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error handling request: {ex.Message}");
}
}

private void HandleDefaultRequest(HttpListenerResponse response)
{
string responseString = "Pink OK!";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;

using (var output = response.OutputStream)
{
output.Write(buffer, 0, buffer.Length);
}

}

private void HandlePostRequest(HttpListenerRequest request, HttpListenerResponse response)
{
try
{
using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
{
var requestBody = reader.ReadToEnd();
var parsedData = JsonSerializer.Deserialize<Dictionary<string, string>>(requestBody);

if (parsedData is not null && settings is not null)
{
var signedFilesCollection = new Dictionary<string, string>();

foreach (var kvp in parsedData)
{
string documentName = kvp.Key;
string value = kvp.Value;

DocumentSigner documentSigner = new DocumentSigner(settings.CertificateHash, value, documentName, settings.SignatureLocation);
SignatureResult signatureResult = documentSigner.SignDocument();
signedFilesCollection.Add(documentName, signatureResult.SignedDocumentBase64);
LogEntries.Insert(0, signatureResult.ResultText);
}

response.StatusCode = (int)HttpStatusCode.OK;
response.ContentType = "application/json";
var responseJson = JsonSerializer.Serialize(signedFilesCollection);

using (var writer = new StreamWriter(response.OutputStream))
{
writer.Write(responseJson);
}
}
else
{
response.StatusCode = (int)HttpStatusCode.BadRequest;
}
}
}
catch (Exception ex)
{
response.StatusCode = (int)HttpStatusCode.InternalServerError;
using (var writer = new StreamWriter(response.OutputStream))
{
writer.Write(JsonSerializer.Serialize(new { error = ex.Message }));
}
}
}

private void LoadSettings()
{
if (File.Exists(_filePath))
{
var json = File.ReadAllText(_filePath);
settings = JsonSerializer.Deserialize<Settings>(json);

CertificateHashEntry.Text = settings.CertificateHash;
LocationEntry.Text = settings.SignatureLocation;
}
}

private void Save_Clicked(object sender, EventArgs e)
{
var settings = new Settings
{
CertificateHash = CertificateHashEntry.Text,
SignatureLocation = LocationEntry.Text
};

var json = JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true });
X509Certificate2? certificate = DocumentSigner.GetCertificateFromStore(settings.CertificateHash);

if (certificate == null)
{
DisplayAlert("Error", $"Certificate with fingerprint {settings.CertificateHash} was not found.", "OK");
return;
}

try
{
File.WriteAllText(_filePath, json);
LogEntries.Insert(0, "Configuration Saved");
}
catch (Exception ex)
{
DisplayAlert("Error", $"An error occurred while saving settings: {ex.Message}", "OK");
}
}
}

Expand Down
Loading