DigitalSignatureTest.vb 13 KB

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