Introduction
This article shows the simple way to create a PCKS#7 signature and check it back later. Useful to secure string data to store it in a file or database. Also, shows how to take the signed data and verify against the original content in order to check sign validity.
Using the code
Be sure to have a certificate exported to a .PFX file and the password
required to extract it the info.
Imports System.Security.Cryptography.Pkcs
Imports System.Text
Imports System.Security.Cryptography.X509Certificates
Sub Main()
Dim textToSign As String = "hello world"
Dim contentInfo As New ContentInfo(Encoding.UTF8.GetBytes(textToSign))
Dim signedCms As New SignedCms(contentInfo, True)
Dim certificateFromFile = _
New X509Certificate2("C:\my certificate.pfx", "The password I Used")
Dim Signer As CmsSigner = New CmsSigner(certificateFromFile)
signedCms.ComputeSignature(Signer)
Dim encodedMessage As Byte() = signedCms.Encode()
Dim signedDataInText = Convert.ToBase64String(encodedMessage)
Dim originalTextToSign As String = "hello world"
Dim contentInfo2 As New ContentInfo(Encoding.UTF8.GetBytes(originalTextToSign))
Dim signedCms2 As New SignedCms(contentInfo2, True)
Dim encodedMessageFromSender As Byte() = Convert.FromBase64String(signedDataInText)
signedCms2.Decode(encodedMessageFromSender)
signedCms2.CheckSignature(True)
End Sub
History