DigitalSignatureTest.cs 15 KB

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