Digitally Signing Files and Checking Signatures

21 Nov

In a nutshell, 

digital signature is a value that can be appended to electronic data to prove that it was created by someone who possesses a specific private key. Public-key algorithms can also be used to form digital signatures. Digital signatures authenticate the identity of a sender and help protect the integrity of data.

That’s all they do, protect data integrity. When you sign a file, you or someone else can later verify the signature with your public key and check if the data was tampered with or modified in any way.

The digital signature does not protect the secrecy of the data in any way. The data is visible to anyone with access to the file. To protect the secrecy of the data, you need to encrypt the file.

The setting could be like this, you sign a file, send the public key and signature to your receiver separately, when they receive the file, they verify the signature. If its a bank cheque, and the signature is wrong, then you know someone did something with the cheque.

That being said, today I wrote two methods for signing and verifying the digital signature of a file. Let me explain a little bit on how it works. When you sign data, a public key and a signature are created. You must store these somewhere (prefarably as a file) and use them later to verify the signature of the data you signed.

I compiled the two methods to a small windows application that you can use to  sign and verify signatures. 

form_run

The .NET Framework makes digital signing of files so easy by providing two classes for generating and verifying digital signatures: DSACryptoServiceProvider and RSACryptoServiceProvider, both contained in the System.Security.Cryptography namespace. They use different algorithms but provide the same functionality.

To generate a digital signature for a file, we need to perform the following steps:
1. Create the digital signature algorithm object.(In this case we’ll use DSACryptoServiceProvider)
2. Store the data to be signed in a byte array.
3. Call the SignData method and store the signature.
4. Export the public key.

In real settings you are required to store the Signature and Public key separately, but for brevity, in this sample I will store them in the same file, and perform some string manipulation in reading them separately from the file.

Here is the source code for the first method that signs the data. It takes two arguments, a path for the data to be signed, and the path for exporting the digital signature. (If you don’t provide this, the file will be saved in the application’s primary directory (where you run it from).

Public Sub SignFile(ByVal FilePath As String, ByVal KeyPath As String)

        ' Signing Step 1: Create the digital signature algorithm object
        Dim signer As DSACryptoServiceProvider = New DSACryptoServiceProvider

        ' Signing Step 2: Store the data to be signed in a byte array.
        Dim file As FileStream = New FileStream(FilePath, FileMode.Open, FileAccess.Read)
        Dim reader As BinaryReader = New BinaryReader(file)
        Dim data As Byte() = reader.ReadBytes(CType(file.Length, Integer))

        ' Signing Step 3: Call the SignData method and create the signature
        Dim signature As Byte() = signer.SignData(data)

        ' Signing Step 4: Export the public key
        ' Save the public key and the Signature in a file. 

        Using sr As New StreamWriter(KeyPath)
            sr.Write(signer.ToXmlString(False))
            sr.WriteLine()
            sr.Write("Signature:" & System.Convert.ToBase64String(signature))
        End Using
        reader.Close()
        file.Close()
    End Sub

I trust that the code is self explanatory.

To verify the digital signature, we need to perform the following steps:
1. Create the digital signature algorithm object.(We use the same DSACryptoServiceProvider)
2. Import the signature and public key.
3. Store the data to be verified in a byte array.
4. Call the VerifyData method.

Below is the sourcecode for the signature verification method.
This one too takes a path for the file to be verified, and a path for the location of the digital signature file. It then verifies the signature, returning true if the signature is verified and false if otherwise.

Public Function VerifySignature(ByVal FilePath As String, ByVal KeyPath As String) As Boolean

        ' Verifying Step 1: Create the digital signature algorithm object
        Dim verifier As DSACryptoServiceProvider = New DSACryptoServiceProvider

        ' Verifying Step 2: Import the signature and public key.
        Dim publicKey As String = Nothing
        Dim signSource As String = Nothing

        Using sr As New StreamReader(KeyPath)
            For Each line As String In sr.ReadLine
                If Not line.StartsWith("Signature:") Then
                    publicKey += line
                Else
                    Exit For
                End If
            Next line
            signSource = sr.ReadToEnd
        End Using
        Dim res As String = signSource.Remove(0, 10)

        Dim signature As Byte() = System.Convert.FromBase64String(res)

        verifier.FromXmlString(publicKey)

        ' Verifying Step 3: Store the data to be verified in a byte array
        Dim file As FileStream = New FileStream(FilePath, FileMode.Open, FileAccess.Read)
        Dim reader As BinaryReader = New BinaryReader(file)
        Dim data As Byte() = reader.ReadBytes(CType(file.Length, Integer))

        ' Verifying Step 4: Call the VerifyData method
        If verifier.VerifyData(data, signature) Then
            Return True
        Else
            Return False
        End If
        reader.Close()
        file.Close()
    End Function
End Class

One important thing, do not forget to include the following libraries in your project.

  • System.Security.Cryptography
  • System.IO
  • System.Text.Encoding
  • System.Xml
  • System.Text

Those are the two  main important methods that I used in the small windows application. You can download the full sourcecode for the windows form as a text file here.

And please reserve your comments on the UI design, I know it isn’t that sleek.

verification

A few notes: The issue of digital signatures is broad and can not be covered in the scope of this post. I also understand that I did not explain all the bits and bytes of the code, but I hope it is understandanle. In case you need any further explanation, please feel free to contact me via: n i c l i v e @ g m a i l dot com, or through here.

Till next time, yours truly.

About these ads

One Response to “Digitally Signing Files and Checking Signatures”

  1. www.getjealous.com May 23, 2013 at 10:25 pm #

    Every weekend i used to pay a quick visit this web page, for the reason that
    i want enjoyment, for the reason that this this web site conations genuinely fastidious funny stuff too.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: