Recently, I recorded a Spanish video about how to encrypt/sign information using certificates and I thought it would be nice to write also a post about it. The thing is that when I tried to post it I received an alert about having a post with the same title, I already wrote the post Encrypting with Certificates more than two years ago :(, so while I try to figure out why I have this memory leak in my brain I will write only the missed part: how sign data using X509 certificates.
Since we already have in the previous post the code to load certificates we will focus on two methods Sign and VerifyHash.
The idea behind these two methods is the next:
We have one party A who needs to send a message to B. B wants to be sure that the messaged received has not been modified by a third party C. To do that, A will create a digital signature that will be sent together with the message. To generate the signature A needs to compute a hash of the message, this hash is then used with method “Sign”. Once A has the signature he can transmit the message and the signature to B.
When B receives the message and the signature, B needs to verify the hash. So, B computes again a hash of the received message and uses the method VerifyHash, which will return true if the message has not been modified. The next code shows you an example on how to call both methods.
This piece of code using the rest of methods mentioned shows you how we can verify a message has not been altered during the transmission. If you comment the line 18th and uncomment the 19th you will see that after message has been altered the hash cannot be validated anymore. These short methods are one the basis of security when we try to guarantee information is not being altered from origin to destine. We have used a very basic message, but imagine you have an online shop and you don´t want people can alter from the message the number of items that will be delivered after you have authorized a payment.
Checking similar methods like SignData and VerifyData will be left as an exercise for the reader.