How to sign data with SignedCMS and signature check






4.33/5 (4 votes)
Shows how to sign a string using a PFX certificate to create a CMS/PCKS#7 signed data. Also, shows how to take the signed data and compare with the original text to check sigh validity.
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.
'Required Imports
Imports System.Security.Cryptography.Pkcs
Imports System.Text
Imports System.Security.Cryptography.X509Certificates
'CONSOLE ENTRY POINT
Sub Main()
'SIGNER PART, TAKE SOME PLAIN TEXT AND SIGN IT
'Simple text to sign
Dim textToSign As String = "hello world"
'Convert to array of bytes
Dim contentInfo As New ContentInfo(Encoding.UTF8.GetBytes(textToSign))
'New signedCMS object to perform the work
Dim signedCms As New SignedCms(contentInfo, True)
'Read the *.PFX file from disk and specifi the password you used to export it
Dim certificateFromFile = _
New X509Certificate2("C:\my certificate.pfx", "The password I Used")
'Signer guy based on the certificate
Dim Signer As CmsSigner = New CmsSigner(certificateFromFile)
'Sign the content and keep it inside signedCMS object
signedCms.ComputeSignature(Signer)
'Encode signed data to extract it
Dim encodedMessage As Byte() = signedCms.Encode()
'To store in a file or Database get the string representation of signed data
Dim signedDataInText = Convert.ToBase64String(encodedMessage)
'SECOND PART, RECEIVE SIGNED DATA AND CHECK WITH THE ORIGINAL MESSAGE
Dim originalTextToSign As String = "hello world"
Dim contentInfo2 As New ContentInfo(Encoding.UTF8.GetBytes(originalTextToSign))
Dim signedCms2 As New SignedCms(contentInfo2, True)
'take signed string representation and convert to byte array to perform decode
Dim encodedMessageFromSender As Byte() = Convert.FromBase64String(signedDataInText)
signedCms2.Decode(encodedMessageFromSender)
'Check the original message against the encrypted hash
'If something is wrong this line will cause an exception
signedCms2.CheckSignature(True)
End Sub
History
- V1 November 2013.