Digital Signatures

Introduction

Digital signatures are used to verify identity of the sender and ensure data integrity. They are often used along with public key encryption.

How Digital Signature work

In Part 1 we mentioned how digital signatures work.

  1. Sender applies hash algorithm to the data being sent and creates a message digest. Message digest is compact representation of the data being sent.
  2. Sender then encrypts the message digest with the private key to get a digital signature
  3. Sender sends the data over a secure channel
  4. Receiver receives the data and decrypts the digital signature using public key and retrieves the message digest
  5. Receiver applies the same hash algorithm as the sender to the data and creates a new message digest
  6. If sender’s digest and receiver’s digest match then it means that the message really came from the said sender.

Related classes

.NET Framework provides classes RSACryptoServiceProvider, RSAPKCS1SignatureFormatter and RSAPKCS1SignatureDeformatter that allow you create and verify digital signatures. All of them reside in System.Security.Cryptography namespace.

Example

In this example we will be creating a class called DigitalSignatureHelper that allows us to generate digital signatures and verify signatures. Note in order to run this example you need MD5HashHelper that we developed in the previous part

DigitalSignatureHelper.cs

Let’s understand the code step-by-step.

  1. We create a class called DigitalSignatureHelper with two private variables and two methods.
  2. The class level variables m_private and m_public are of type RSAParameters and are used to store public and private key information.
  3. The method CreateSignature() accepts the hash value that has to be signed and returns the digitally signed hash as a return value
  4. Inside this function we create an instance of a class called RSACryptoServiceProvider
  5. We also create an instance of a class called RSAPKCS1SignatureFormatter and pass the instance of RSACryptoServiceProvider in its constructor.
  6. The RSAPKCS1SignatureFormatter class is used to create PKCS #1 (Public Key Cryptographic Signature) version 1.5 signature. Where as RSACryptoServiceProvider provides encryption services.
  7. Since we will be using MD5 as a hashing algorithm, we call SetHashAlgorithm()method of RSAPKCS1SignatureFormatter and pass “MD5” as a parameter. If your hashing algorithm is SHA1 you would have passed SHA1 instead.
  8. Then we call ExportParameters() method of RSACryptoServiceProvider to get public and private keys generated. We store these keys the class level variables m_public and m_private respectively.
    Finally we call CreateSignature() method of RSAPKCS1SignatureFormatterclass which returns the signature. The same is returned as the return value of the function.
  9. The VerifySignature() method accepts two parameters – original hash value and signed hash value. It compares the hashes and return true if they match.
  10. Inside this function we create an instance of RSACryptoServiceProvider class.
  11. We need to supply key information during signature verification and hence we create an instance of RSAParameters structure.
  12. The Modulus and Exponent properties of this structure are set to the equivalent properties of previously obtained public key (m_public).
  13. We then call ImportParameters() method of RSACryptoServiceProvider to import the key information into the instance.
  14. Then we create an instance of RSAPKCS1SignatureDeformatter class. This class is used to verify RSA PKCS #1 version 1.5 signatures.
  15. Again, we set the hashing algorithm to MD5 using SetHashAlgorithm() method of RSAPKCS1SignatureDeformatter class.
  16. Finally we call VerifySignature() method of RSAPKCS1SignatureDeformatterclass and pass original hash value and signed hash value to it. This method returns true if the signature is verified successfully else it returns false. The same return value is returned as to the caller.

Summary

In this article we learnt about digital signatures. Digital signatures allow you to verify that the data came from known sender. The classes RSACryptoServiceProvider, RSAPKCS1SignatureFormatter and RSAPKCS1SignatureDeformatter from System.Security.Cryptography allow you to work with digital signatures.

Check http://www.dotnetbips.com for original articles.

Hash Values

In this part we are going to learn how to ensure that data coming to you has not been tampered with during the transfer. The technique that we will be using is hash. Hash values allow us to verify the integrity of data. The hash value of received data can be compared to the hash value of data that was sent to check if the data is tampered.

.NET Framework classes for creating hashes

.NET Framework provides following main classes to work with hashes:

  • SHA1Managed
  • MD5CryptoServiceProvider
  • MACTripleDES

Since SHA1 is now a broken algorithm, we will use MD5CryptoServiceProvider to generate hash values.

Example
We are going to create a helper class that will help us create and verify hash values using MD5 algorithm. The class contains two methods – GetHash() and VerifyHash(). The former accepts string whose hash value is to be generated and returns the computed hash as a byte array. The later accepts the message as it was received and the hash generated previously and returns true if the message is not altered during transmit otherwise returns false.

MD5HashHelper.cs

Let’s dissect the code step by step:

  1. We first need to import System.Security.Cryptography namespace in your class
  2. The GetHash() accepts string whose hash value is to be generated and returns the computed hash as a byte array.
  3. Inside the function we used UTF8Encoding class and get a byte representation of the string to be transferred.
  4. We then create an instance of MD5CryptoServiceProvider class and call it’s ComputeHash by passing the byte created above to it.
  5. The ComputeHash() function generates the hash for the given data and returns another byte array that represents the hash value of the data.
  6. The VerifyHash() function accepts the message as it was received and the hash generated previously and returns true if the message is not altered during transmit otherwise returns false.
  7. Inside this function we again use UTF8Encoding class and generate byte representation of the received message.
  8. We then compute hash for this data using the same ComputeHash() method of MD5CryptoServiceProvider class.
  9. Finally, we run a for loop and check each and every byte of original hash value and the hash we generated above. If both the hash values are matching we can conclude that the data is not tampered.

Check http://www.dotnetbips.com for original articles.

Public Key Encryption

Introduction

Data encrypted by public key can be decrypted only by the corresponding private key and vice a versa. One of the most popular algorithm for encrypting and decrypting data using this technique is RSA. The acronym RSA stands for Rivest, Shamir, and Adelman who are the inventors of the technique. The .NET framework provides a class called RSACryptoServiceProvider that encapsulates this algorithm. In this article we are going to learn how to use this class to secure your data.

Developing a class for encryption and decryption

Many developers don’t want to go into the internals of Cryptography. They simply need a quick and easy way to secure their data. So we are going to develop such reusable class that will do the job of encrypting and decrypting for us.

We will create a class called PublicKeySecurityHelper which will have two methods – Encrypt and Decrypt. In addition we will also create a helper class called MyRSAInfo. This class will simply store certain pieces of data (such as public key and private key).

Here, is the complete code of the class.

PublicKeySecurityHelper.cs

RSAInfo.cs

Program.cs

Below the code step by step:

Encrypting data

  1. First we import the required namespaces. Especially System.Security.Cryptography is important one because it contains our core class RSACryptoServiceProvider.
  2. We create a method called Encrypt() that accepts the string to be encrypted and returns an instance of a class called RSAInfo.
  3. RSAInfo is our custom class defined at the bottom of the code. It consists of four public members – PublicKey, PrivateKey, Parameters and Data.
  4. The PublicKey and PrivateKey members store the generated public key and private key respectively.
  5. The Parameters variable is of type CspParameters. This is used to automatically generate public and private keys and reuse them later on.
  6. The Data is an array of bytes and stores the encrypted version of the data
  7. Inside the Encrypt() method we create an instance of CspParameters class and set its Flag property to CspProviderFlags.UseMachineKeyStore. This enumerated value specifies from where the key information should be picked up i.e. from default key container or from machine level key store.
  8. Then we create new instance of RSACryptoServiceProvider class passing the CspParameters instance.
  9. We then call Encrypt() method of RSACryptoServiceProvider class and pass data to be encrypted. Since this parameter is byte array we convert our string into byte array using GetBytes() method. The second parameter of the method indicates whether to use OAEP padding (true) or PKCS#1 v1.5 padding (false). The former can be used only on Windows XP machines and hence we pass False. The Encrypt() method of RSACryptoServiceProvider class returns a byte array that contains encrypted version of the data.
  10. Finally, we fill all the members of RSAInfo class and return to the caller. Note how we call ToXmlString() method first passing False and then passing True to get public and private keys respectively.

Decrypting data

  1. In order to decrypt the data we create a method called Decrypt() that accepts an instance of RSAInfo class. This instance must be the one returned by the Encrypt() method explained earlier.
  2. Inside Decrypt() method we create an instance of RSACryptoServiceProviderclass again passing the same CspParameters.
  3. We then call FromXmlString() method of the RSACryptoServiceProvider class and pass the private key generated before. More details here.
  4. Finally, we call Decrypt() method of RSACryptoServiceProvider class and pass the encrypted data. The second parameter of Decrypt method has the same significance as that of the corresponding parameter of Encrypt() method

Summary

Public key encryption is a secure way to transfer data over networks. The fact that the private key is not sent in unsafe manner makes it more secure and robust. This technique is used in Secure Socket Layer (SSL) or HTTPS based web sites. The .NET framework class RSACryptoServiceProvider allows you to generate public and private keys, encrypt and decrypt data.

Check http://www.dotnetbips.com for original articles.

Secret Key Encryption

Triple-DES

The System.Security.Cryptography namespace contains a class called TripleDESCryptoServiceProvider that provides Triple-DES encryption to your data. DES stands for Data Encryption Standard and the word triple is used because it encrypts the original data thrice.

The secret key encryption needs two things to encrypt the data:

  • A secret key
  • An initialization vector

The encryption algorithms employ use a chaining technique to encrypt the data. In this technique the entire data to be encrypted is divided in smaller blocks. The previously encrypted block of data is used to encrypt the current one and the process repeats.

The Initialization Vector (IV) serves as a seed that is used to encrypt and decrypt the first block of bytes. This ensures that no two blocks of data produce the same block of encrypted text.

For using TripleDESCryptoServiceProvider the encryption key must be of 24 bytes and the initialization vector must be of 8 bytes.

Example of using TripleDESCryptoServiceProvider class:

SecurityHelper.cs

Check http://www.dotnetbips.com for original articles.

Cryptography and .NET Framework Introduction

Security is key consideration for many applications. Providing authentication and authorization services to your application is just one part of the overall security. What about the data that is being used and transferred in the application? That is where cryptography comes into picture. Cryptography is a huge topic by itself.

Many times application provide security features such as login forms and role based security. However, what if someone intercepts the data that is being flown over the network? What if someone plays with the data that is being transmitted over the network? What if someone opens SQL Server database that is storing passwords? Cryptography provides solution to such questions. Using .NET Cryptographic classes you can encrypt the data that is being flown in your system or network and then decrypt when you want authenticated user to modify or read it. In short Cryptography provides following features:

  • Protect data being transferred from reading by third parties
  • Protect data being transferred from any modification
  • Make sure that data is arriving from the intended location

Types of Cryptographic classes

The overall Cryptographic classes available in .NET framework can be classified in four categories:

  • Classes that deal with secret key encryption (also called as Symmetric Cryptography)
  • Classes that deal with public key encryption (also called Asymmetric Cryptography)
  • Classes that deal with digital signatures (also called cryptographic signatures)
  • Classes that deal with cryptographic hashes

All the cryptography related classes can be found in System.Security.Cryptography namespace.

Secret Key Encryption

In Secret Key Cryptography the data being protected is encrypted using a single secret key. This key is known only to sender and receiver. The sender encrypts the data using the secret key. The receiver decrypts the data using the same secret key. It is very important to keep the key secret otherwise anybody having the key can decrypt the data.

.NET Framework provides following classes to work with Secret Key Cryptography:

  • DESCryptoServiceProvider
  • RC2CryptoServiceProvider
  • RijndaelManaged
  • TripleDESCryptoServiceProvider

Public Key Encryption

Unlike secret key encryption, public key encryption uses two keys. One is called public key and the other is called as private key. The public key is not kept secret at all where as private key is kept confidential by the owner of that key. The data encrypted by private key can be decrypted only using its corresponding public key and data encrypted using public key can be decrypted using its private key. Naturally, in order to encrypt the data being transmitted you need to use public key. This data can be decrypted only with the corresponding private key.

.NET Framework provides following classes to work with public key encryption:

  • DSACryptoServiceProvider
  • RSACryptoServiceProvider

Digital Signatures

Digital signatures are used to verify identity of the sender and ensure data integrity. They are often used along with public key encryption. Digital signature work as follows:

  1. Sender applies hash algorithm to the data being sent and creates a message digest. Message digest is compact representation of the data being sent.
  2. Sender then encrypts the message digest with the private key to get a digital signature
  3. Sender sends the data over a secure channel
  4. Receiver receives the data and decrypts the digital signature using public key and retrieves the message digest
  5. Receiver applies the same hash algorithm as the sender to the data and creates a new message digest
  6. If sender’s digest and receiver’s digest match then it means that the message really came from the said sender.

The classes DSACryptoServiceProvider and RSACryptoServiceProvider are used to create digital signatures.

Hashes

Hash algorithms create a fixed length output for a given variable length data. If somebody changes the original data even slightly then the hash generated will be different than original hash. They are often used with digital signatures.

Some of the classes in .NET that deal with hashes are:

  • SHA1Managed
  • MD5CryptoServiceProvider
  • MACTripleDES

Random Number Generators

While working with cryptography classes many times you need to generate cryptographic keys. Random number generators are used for this purpose. .NET provides a class called RNGCryptoServiceProvider to generate such random numbers.

Below you will find additional details and code samples for different cryptography techniques.

Check http://www.dotnetbips.com for original articles.