DigitalSignatureTest.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. /// in the core function "CPDFPKCS12CertHelper.GeneratePKCS12Cert":
  52. ///
  53. /// Generate certificate
  54. ///
  55. /// Password: ComPDFKit
  56. ///
  57. /// info: /C=SG/O=ComPDFKit/D=R&D Department/CN=Alan/emailAddress=xxxx@example.com
  58. ///
  59. /// C=SG: This represents the country code "SG," which typically stands for Singapore.
  60. /// O=ComPDFKit: This is the Organization (O) field, indicating the name of the organization or entity, in this case, "ComPDFKit."
  61. /// D=R&D Department: This is the Department (D) field, indicating the specific department within the organization, in this case, "R&D Department."
  62. /// 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."
  63. /// emailAddress=xxxx@example.com: Email is xxxx@example.com
  64. ///
  65. /// CPDFCertUsage.CPDFCertUsageAll: Used for both digital signing and data validation simultaneously.
  66. ///
  67. /// is_2048 = true: Enhanced security encryption.
  68. /// </summary>
  69. private static void GenerateCertificate()
  70. {
  71. Console.WriteLine("--------------------");
  72. Console.WriteLine("Generate certificate signature.");
  73. string info = "/C=SG/O=ComPDFKit/D=R&D Department/CN=Alan/emailAddress=xxxx@example.com";
  74. string password = "ComPDFKit";
  75. string filePath = outputPath + "\\Certificate.pfx";
  76. if (CPDFPKCS12CertHelper.GeneratePKCS12Cert(info, password, filePath, CPDFCertUsage.CPDFCertUsageAll, true))
  77. {
  78. Console.WriteLine("File saved in " + filePath);
  79. Console.WriteLine("Generate PKCS12 certificate done.");
  80. }
  81. else
  82. {
  83. Console.WriteLine("Generate PKCS12 certificate failed.");
  84. }
  85. Console.WriteLine("--------------------");
  86. }
  87. /// <summary>
  88. ///
  89. /// Adding a signature is divided into two steps:
  90. /// creating a signature field and filling in the signature.
  91. ///
  92. /// Page Index: 0
  93. /// Rect: CRect(28, 420, 150, 370)
  94. /// Border RGB:{ 0, 0, 0 }
  95. /// Widget Background RGB: { 150, 180, 210 }
  96. ///
  97. /// Text: Grantor Name
  98. /// Content:
  99. /// Name: get grantor name from certificate
  100. /// Date: now(yyyy.mm.dd)
  101. /// Reason: I am the owner of the document.
  102. /// DN: Subject
  103. /// Location: Singapor
  104. /// IsContentAlignLeft: false
  105. /// IsDrawLogo: True
  106. /// LogoBitmap: logo.png
  107. /// text color RGB: { 0, 0, 0 }
  108. /// content color RGB: { 0, 0, 0 }
  109. /// Output file name: document.FileName + "_Signed.pdf"
  110. /// </summary>
  111. private static void CreateDigitalSignature(CPDFDocument document, string certificatePath, string password)
  112. {
  113. Console.WriteLine("--------------------");
  114. Console.WriteLine("Create digital signature.");
  115. CPDFSignatureCertificate certificate = CPDFPKCS12CertHelper.GetCertificateWithPKCS12Path("Certificate.pfx", "ComPDFKit");
  116. CPDFPage page = document.PageAtIndex(0);
  117. CPDFSignatureWidget signatureField = page.CreateWidget(C_WIDGET_TYPE.WIDGET_SIGNATUREFIELDS) as CPDFSignatureWidget;
  118. signatureField.SetRect(new CRect(28, 420, 150, 370));
  119. signatureField.SetWidgetBorderRGBColor(new byte[] { 0, 0, 0 });
  120. signatureField.SetWidgetBgRGBColor(new byte[] { 150, 180, 210 });
  121. signatureField.UpdateAp();
  122. string name = GetGrantorFromDictionary(certificate.SubjectDict) + "\n";
  123. string date = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss");
  124. string reason = "I am the owner of the document.";
  125. string location = certificate.SubjectDict["C"];
  126. string DN = certificate.Subject;
  127. CPDFSignatureConfig signatureConfig = new CPDFSignatureConfig
  128. {
  129. Text = GetGrantorFromDictionary(certificate.SubjectDict),
  130. Content =
  131. "Name: " + name + "\n" +
  132. "Date: " + date + "\n" +
  133. "Reason: " + reason + " \n" +
  134. "Location: " + location + "\n" +
  135. "DN: " + DN + "\n",
  136. IsContentAlignLeft = false,
  137. IsDrawLogo = true,
  138. LogoBitmap = new Bitmap("Logo.png"),
  139. TextColor = new float[] { 0, 0, 0 },
  140. ContentColor = new float[] { 0, 0, 0 }
  141. };
  142. string filePath = outputPath + "\\" + document.FileName + "_Signed.pdf";
  143. signatureField.UpdataApWithSignature(signatureConfig);
  144. if (document.WriteSignatureToFilePath(signatureField,
  145. filePath,
  146. certificatePath, password,
  147. location,
  148. reason, CPDFSignaturePermissions.CPDFSignaturePermissionsNone))
  149. {
  150. Console.WriteLine("File saved in " + filePath);
  151. Console.WriteLine("Create digital signature done.");
  152. }
  153. else
  154. {
  155. Console.WriteLine("Create digital signature failed.");
  156. }
  157. Console.WriteLine("--------------------");
  158. }
  159. /// <summary>
  160. /// Remove digital signature
  161. /// You can choose if you want to remove the appearance
  162. /// </summary>
  163. /// <param name="document"></param>
  164. private static void RemoveDigitalSignature(CPDFDocument document)
  165. {
  166. Console.WriteLine("--------------------");
  167. Console.WriteLine("Remove digital signature.");
  168. CPDFSignature signature = document.GetSignatureList()[0];
  169. document.RemoveSignature(signature, true);
  170. string filePath = outputPath + "\\" + document.FileName + "_RemovedSign.pdf";
  171. document.WriteToFilePath(filePath);
  172. Console.WriteLine("File saved in " + filePath);
  173. Console.WriteLine("Remove digital signature done.");
  174. Console.WriteLine("--------------------");
  175. }
  176. /// <summary>
  177. /// There are two steps can help you to trust a certificate.
  178. /// Set your trust path as a folder path,
  179. /// then add your certificate to the trust path.
  180. /// </summary>
  181. private static void TrustCertificate(CPDFDocument document)
  182. {
  183. Console.WriteLine("--------------------");
  184. Console.WriteLine("Trust certificate.");
  185. CPDFSignature signature = document.GetSignatureList()[0];
  186. CPDFSignatureCertificate signatureCertificate = signature.SignerList[0].CertificateList[0];
  187. Console.WriteLine("Certificate trusted status: " + signatureCertificate.IsTrusted.ToString());
  188. Console.WriteLine("---Begin trusted---");
  189. string trustedFolder = AppDomain.CurrentDomain.BaseDirectory + @"\TrustedFolder\";
  190. if (!Directory.Exists(trustedFolder))
  191. {
  192. Directory.CreateDirectory(trustedFolder);
  193. }
  194. CPDFSignature.SignCertTrustedFolder = trustedFolder;
  195. if (signatureCertificate.AddToTrustedCertificates())
  196. {
  197. Console.WriteLine("Certificate trusted status: " + signatureCertificate.IsTrusted.ToString());
  198. Console.WriteLine("Trust certificate done.");
  199. }
  200. else
  201. {
  202. Console.WriteLine("Trust certificate failed.");
  203. }
  204. Console.WriteLine("--------------------");
  205. }
  206. /// <summary>
  207. /// Verify certificate
  208. ///
  209. /// To verify the trustworthiness of a certificate,
  210. /// you need to verify that all certificates in the certificate chain are trustworthy.
  211. ///
  212. /// In ComPDFKit,this progess is automatic.
  213. /// You should call the "CPDFSignatureCertificate.CheckCertificateIsTrusted" first.
  214. /// then you can view the "CPDFSignatureCertificate.IsTrusted" property.
  215. /// </summary>
  216. /// <param name="document">A signed document</param>
  217. private static void VerifyCertificate(string certificatePath, string password)
  218. {
  219. Console.WriteLine("--------------------");
  220. Console.WriteLine("Verify certificate.");
  221. CPDFSignatureCertificate certificate = CPDFPKCS12CertHelper.GetCertificateWithPKCS12Path(certificatePath, password);
  222. certificate.CheckCertificateIsTrusted();
  223. if (certificate.IsTrusted)
  224. {
  225. Console.WriteLine("Certificate is trusted");
  226. }
  227. else
  228. {
  229. Console.WriteLine("Certificate is not trusted");
  230. }
  231. Console.WriteLine("Verify certificate done.");
  232. Console.WriteLine("--------------------");
  233. }
  234. /// <summary>
  235. /// Verify digital signature
  236. ///
  237. /// Refresh the validation status before reading the attributes, or else you may obtain inaccurate results.
  238. /// Is the signature verified: indicating whether the document has been tampered with.
  239. /// Is the certificate trusted: referring to the trust status of the certificate.
  240. /// </summary>
  241. private static void VerifyDigitalSignature(CPDFDocument document)
  242. {
  243. Console.WriteLine("--------------------");
  244. Console.WriteLine("Verify digital signature.");
  245. foreach (var signature in document.GetSignatureList())
  246. {
  247. signature.VerifySignatureWithDocument(document);
  248. foreach (var signer in signature.SignerList)
  249. {
  250. Console.WriteLine("Is the certificate trusted: " + signer.IsCertTrusted.ToString());
  251. Console.WriteLine("Is the signature verified: " + signer.IsSignVerified.ToString());
  252. if (signer.IsCertTrusted && signer.IsSignVerified)
  253. {
  254. // Signature is valid and the certificate is trusted
  255. // Perform corresponding actions
  256. }
  257. else if (!signer.IsCertTrusted && signer.IsSignVerified)
  258. {
  259. // Signature is valid but the certificate is not trusted
  260. // Perform corresponding actions
  261. }
  262. else
  263. {
  264. // Signature is invalid
  265. // Perform corresponding actions
  266. }
  267. }
  268. }
  269. Console.WriteLine("Verify digital signature done.");
  270. Console.WriteLine("--------------------");
  271. }
  272. public static string GetGrantorFromDictionary(Dictionary<string, string> dictionary)
  273. {
  274. string grantor = string.Empty;
  275. dictionary.TryGetValue("CN", out grantor);
  276. if (string.IsNullOrEmpty(grantor))
  277. {
  278. dictionary.TryGetValue("OU", out grantor);
  279. }
  280. if (string.IsNullOrEmpty(grantor))
  281. {
  282. dictionary.TryGetValue("O", out grantor);
  283. }
  284. if (string.IsNullOrEmpty(grantor))
  285. {
  286. grantor = "Unknown Signer";
  287. }
  288. return grantor;
  289. }
  290. /// <summary>
  291. /// this samples shows how to get main properties in digital signature.
  292. /// read API reference to see all of the properties can get
  293. /// </summary>
  294. /// <param name="document"></param>
  295. private static void PrintDigitalSignatureInfo(CPDFDocument document)
  296. {
  297. Console.WriteLine("--------------------");
  298. Console.WriteLine("Print digital signature info.");
  299. foreach (var signature in document.GetSignatureList())
  300. {
  301. signature.VerifySignatureWithDocument(document);
  302. Console.WriteLine("Name: " + signature.Name);
  303. Console.WriteLine("Location: " + signature.Location);
  304. Console.WriteLine("Reason: " + signature.Reason);
  305. foreach (var signer in signature.SignerList)
  306. {
  307. Console.WriteLine("Date: " + signer.AuthenDate);
  308. foreach (var certificate in signer.CertificateList)
  309. {
  310. Console.WriteLine("Subject: " + certificate.Subject);
  311. }
  312. }
  313. }
  314. Console.WriteLine("Print digital signature info done.");
  315. Console.WriteLine("--------------------");
  316. }
  317. }
  318. }