DigitalSignatureTest.vb 13 KB

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