DigitalSignatureTest.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. using ComPDFKit.DigitalSign;
  2. using ComPDFKit.Import;
  3. using ComPDFKit.PDFAnnotation;
  4. using ComPDFKit.PDFAnnotation.Form;
  5. using ComPDFKit.PDFDocument;
  6. using ComPDFKit.PDFPage;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Drawing;
  10. using System.IO;
  11. using System.Xml.Linq;
  12. namespace DigitalSignatureTest
  13. {
  14. internal class DigitalSignatureTest
  15. {
  16. static private string outputPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()))) + "\\Output\\DigitalSignature";
  17. static void Main()
  18. {
  19. #region Preparation work
  20. Console.WriteLine("Running digital signature sample...\n");
  21. SDKLicenseHelper.LicenseVerify();
  22. string certificatePath = "Certificate.pfx";
  23. string password = "ComPDFKit";
  24. if (!Directory.Exists(outputPath))
  25. {
  26. Directory.CreateDirectory(outputPath);
  27. }
  28. #endregion
  29. //Sample 0: Create certificate
  30. GenerateCertificate();
  31. //Sample 1: Create digital signature
  32. CPDFDocument document = CPDFDocument.InitWithFilePath("CommonFivePage.pdf");
  33. CreateDigitalSignature(document, certificatePath, password);
  34. document.Release();
  35. //Sample 2: Verify signature
  36. CPDFDocument signedDoc = CPDFDocument.InitWithFilePath("Signed.pdf");
  37. VerifyDigitalSignature(signedDoc);
  38. //Sample 3: Verify certificate
  39. VerifyCertificate(certificatePath, password);
  40. //Sample 4: Print digital signature info
  41. PrintDigitalSignatureInfo(signedDoc);
  42. //Sample 5: Trust Certificate
  43. TrustCertificate(signedDoc);
  44. //Sample 6: Remove digital signature
  45. RemoveDigitalSignature(signedDoc);
  46. signedDoc.Release();
  47. Console.WriteLine("Done.\n");
  48. Console.ReadLine();
  49. }
  50. /// <summary>
  51. /// this samples shows how to get main properties in digital signature.
  52. /// read API reference to see all of the properties can get
  53. /// </summary>
  54. /// <param name="document"></param>
  55. private static void PrintDigitalSignatureInfo(CPDFDocument document)
  56. {
  57. Console.WriteLine("--------------------");
  58. Console.WriteLine("Print digital signature info.");
  59. foreach (var signature in document.GetSignatureList())
  60. {
  61. signature.VerifySignatureWithDocument(document);
  62. Console.WriteLine("Name: " + signature.Name);
  63. Console.WriteLine("Location: " + signature.Location);
  64. Console.WriteLine("Location: " + signature.Reason);
  65. foreach (var signer in signature.SignerList)
  66. {
  67. Console.WriteLine("Name: " + signer.AuthenDate);
  68. foreach (var certificate in signer.CertificateList)
  69. {
  70. Console.WriteLine("Subject: " + certificate.Subject);
  71. }
  72. }
  73. }
  74. Console.WriteLine("Print digital signature info done.");
  75. Console.WriteLine("--------------------");
  76. }
  77. /// <summary>
  78. /// in the core function "CPDFPKCS12CertHelper.GeneratePKCS12Cert":
  79. ///
  80. /// Generate certificate
  81. ///
  82. /// Password: ComPDFKit
  83. ///
  84. /// info: /C=SG/O=ComPDFKit/D=R&D Department/CN=Alan/emailAddress=xxxx@example.com
  85. ///
  86. /// C=SG: This represents the country code "SG," which typically stands for Singapore.
  87. /// O=ComPDFKit: This is the Organization (O) field, indicating the name of the organization or entity, in this case, "ComPDFKit."
  88. /// D=R&D Department: This is the Department (D) field, indicating the specific department within the organization, in this case, "R&D Department."
  89. /// CN=Alan: This is the Common Name (CN) field, which usually represents the name of the individual or entity. In this case, it is "Alan."
  90. /// emailAddress=xxxx@example.com: Email is xxxx@example.com
  91. ///
  92. /// CPDFCertUsage.CPDFCertUsageAll: Used for both digital signing and data validation simultaneously.
  93. ///
  94. /// is_2048 = true: Enhanced security encryption.
  95. /// </summary>
  96. private static void GenerateCertificate()
  97. {
  98. Console.WriteLine("--------------------");
  99. Console.WriteLine("Create digital signature.");
  100. string info = "/C=SG/O=ComPDFKit/D=R&D Department/CN=Alan/emailAddress=xxxx@example.com";
  101. string password = "ComPDFKit";
  102. if (CPDFPKCS12CertHelper.GeneratePKCS12Cert(info, password, outputPath + "/Certificate.pfx", CPDFCertUsage.CPDFCertUsageAll, true))
  103. {
  104. Console.WriteLine("Generate PKCS12 certificate done.");
  105. }
  106. else
  107. {
  108. Console.WriteLine("Generate PKCS12 certificate failed.");
  109. }
  110. Console.WriteLine("--------------------");
  111. }
  112. /// <summary>
  113. ///
  114. /// Adding a signature is divided into two steps:
  115. /// creating a signature field and filling in the signature.
  116. ///
  117. /// Page Index: 0
  118. /// Rect: CRect(28, 420, 150, 370)
  119. /// Border RGB:{ 0, 0, 0 }
  120. /// Widget Background RGB: { 150, 180, 210 }
  121. ///
  122. /// Text: Grantor Name
  123. /// Content:
  124. /// Name: get grantor name from certificate
  125. /// Date: now(yyyy.mm.dd)
  126. /// Reason: I am the owner of the document.
  127. /// DN: Subject
  128. /// Location: Singapor
  129. /// IsContentAlginLeft: false
  130. /// IsDrawLogo: True
  131. /// LogoBitmap: logo.png
  132. /// text color RGB: { 0, 0, 0 }
  133. /// content color RGB: { 0, 0, 0 }
  134. /// Output file name: document.FileName + "_Signed.pdf"
  135. /// </summary>
  136. private static void CreateDigitalSignature(CPDFDocument document, string certificatePath, string password)
  137. {
  138. Console.WriteLine("--------------------");
  139. Console.WriteLine("Create digital signature.");
  140. CPDFSignatureCertificate certificate = CPDFPKCS12CertHelper.GetCertificateWithPKCS12Path("Certificate.pfx", "ComPDFKit");
  141. CPDFPage page = document.PageAtIndex(0);
  142. CPDFSignatureWidget signatureField = page.CreateWidget(C_WIDGET_TYPE.WIDGET_SIGNATUREFIELDS) as CPDFSignatureWidget;
  143. signatureField.SetRect(new CRect(28, 420, 150, 370));
  144. signatureField.SetWidgetBorderRGBColor(new byte[] { 0, 0, 0 });
  145. signatureField.SetWidgetBgRGBColor(new byte[] { 150, 180, 210 });
  146. CPDFSignatureConfig signatureConfig = new CPDFSignatureConfig
  147. {
  148. Text = GetGrantorFromDictionary(certificate.SubjectDict),
  149. Content =
  150. "Name: " + GetGrantorFromDictionary(certificate.SubjectDict) + "\n" +
  151. "Date: " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss") + "\n" +
  152. "Reason: I am the owner of the document.\n" +
  153. "Location: "+ certificate.SubjectDict["C"] + "\n" +
  154. "DN: " + certificate.Subject + "\n",
  155. IsContentAlginLeft = false,
  156. IsDrawLogo = true,
  157. LogoBitmap = new Bitmap("Logo.png"),
  158. textColor = new float[] { 0, 0, 0 },
  159. contentColor = new float[] { 0, 0, 0 }
  160. };
  161. signatureField.UpdataApWithSignature(signatureConfig);
  162. if (document.WriteSignatureToFilePath(signatureField,
  163. outputPath + "/" + document.FileName + "_Signed.pdf",
  164. certificatePath, password,
  165. "Singapore",
  166. "I am the owner of the document.", CPDFSignaturePermissions.CPDFSignaturePermissionsNone))
  167. {
  168. Console.WriteLine("File saved in " + outputPath + "/" + document.FileName + "_Signed.pdf.");
  169. Console.WriteLine("Create digital signature done.");
  170. }
  171. else
  172. {
  173. Console.WriteLine("Create digital signature failed.");
  174. }
  175. Console.WriteLine("--------------------");
  176. }
  177. /// <summary>
  178. /// Remove digital signature
  179. /// after removed, both of the apperence and data will be removed
  180. /// </summary>
  181. /// <param name="document"></param>
  182. private static void RemoveDigitalSignature(CPDFDocument document)
  183. {
  184. Console.WriteLine("--------------------");
  185. Console.WriteLine("Remove digital signature.");
  186. CPDFSignature signature = document.GetSignatureList()[0];
  187. document.RemoveSignature(signature, true);
  188. string filePath = outputPath + "\\" + document.FileName + "_RemovedSign.pdf";
  189. document.WriteToFilePath(filePath);
  190. Console.WriteLine("File saved in " + filePath);
  191. Console.WriteLine("Remove digital signature done.");
  192. Console.WriteLine("--------------------");
  193. }
  194. /// <summary>
  195. /// There are two steps can help you to trust a certificate.
  196. /// Set "CPDFSignature.SignCertTrustedFolder" as a folder path,
  197. /// then call CPDFSignatureCertificate.AddToTrustedCertificates()
  198. /// </summary>
  199. private static void TrustCertificate(CPDFDocument document)
  200. {
  201. Console.WriteLine("--------------------");
  202. Console.WriteLine("Trust certificate.");
  203. CPDFSignature signature = document.GetSignatureList()[0];
  204. CPDFSignatureCertificate signatureCertificate = signature.SignerList[0].CertificateList[0];
  205. Console.WriteLine("Certificate trusted status: " + signatureCertificate.IsTrusted.ToString());
  206. Console.WriteLine("---Begin trusted---");
  207. string trustedFolder = AppDomain.CurrentDomain.BaseDirectory + @"\TrustedFolder\";
  208. if (!Directory.Exists(trustedFolder))
  209. {
  210. Directory.CreateDirectory(trustedFolder);
  211. }
  212. CPDFSignature.SignCertTrustedFolder = trustedFolder;
  213. if (signatureCertificate.AddToTrustedCertificates())
  214. {
  215. Console.WriteLine("Certificate trusted status: " + signatureCertificate.IsTrusted.ToString());
  216. Console.WriteLine("Trust certificate done.");
  217. }
  218. else
  219. {
  220. Console.WriteLine("Trust certificate failed.");
  221. }
  222. Console.WriteLine("--------------------");
  223. }
  224. /// <summary>
  225. /// Verify certificate
  226. ///
  227. /// To verify the trustworthiness of a certificate,
  228. /// you need to verify that all certificates in the certificate chain are trustworthy.
  229. ///
  230. /// In ComPDFKit,this progess is automatic.
  231. /// You should call the "CPDFSignatureCertificate.CheckCertificateIsTrusted" first.
  232. /// then you can view the "CPDFSignatureCertificate.IsTrusted" property.
  233. /// </summary>
  234. /// <param name="document">A signed document</param>
  235. private static void VerifyCertificate(string certificatePath, string password)
  236. {
  237. Console.WriteLine("--------------------");
  238. Console.WriteLine("Verify certificate.");
  239. CPDFSignatureCertificate certificate = CPDFPKCS12CertHelper.GetCertificateWithPKCS12Path(certificatePath, password);
  240. certificate.CheckCertificateIsTrusted();
  241. if (certificate.IsTrusted)
  242. {
  243. Console.WriteLine("Certificate is trusted");
  244. }
  245. else
  246. {
  247. Console.WriteLine("Certificate is not trusted");
  248. }
  249. Console.WriteLine("Verify certificate done.");
  250. Console.WriteLine("--------------------");
  251. }
  252. /// <summary>
  253. /// Verify digital signature
  254. ///
  255. /// Refresh the validation status before reading the attributes, or else you may obtain inaccurate results.
  256. /// Is the signature verified: indicating whether the document has been tampered with.
  257. /// Is the certificate trusted: referring to the trust status of the certificate.
  258. /// </summary>
  259. private static void VerifyDigitalSignature(CPDFDocument document)
  260. {
  261. Console.WriteLine("--------------------");
  262. Console.WriteLine("Verify digital signature.");
  263. foreach (var signature in document.GetSignatureList())
  264. {
  265. signature.VerifySignatureWithDocument(document);
  266. foreach (var signer in signature.SignerList)
  267. {
  268. Console.WriteLine("Is the certificate trusted: " + signer.IsCertTrusted.ToString());
  269. Console.WriteLine("Is the signature verified: " + signer.IsSignVerified.ToString());
  270. }
  271. }
  272. Console.WriteLine("Verify digital signature done.");
  273. Console.WriteLine("--------------------");
  274. }
  275. public static string GetGrantorFromDictionary(Dictionary<string, string> dictionary)
  276. {
  277. string grantor = string.Empty;
  278. dictionary.TryGetValue("CN", out grantor);
  279. if (string.IsNullOrEmpty(grantor))
  280. {
  281. dictionary.TryGetValue("OU", out grantor);
  282. }
  283. if (string.IsNullOrEmpty(grantor))
  284. {
  285. dictionary.TryGetValue("O", out grantor);
  286. }
  287. if (string.IsNullOrEmpty(grantor))
  288. {
  289. grantor = "Unknown Signer";
  290. }
  291. return grantor;
  292. }
  293. }
  294. }