Digital Certificates in C#

For any communication on network authentications is compulsory before exchanging data. Authentication means validating the identity of the user. Authentication can happen in the form digital certificates. Receiver should have the certificate which shared by sender. With the help of digital certificates, we can get proper secure communication. In this article, we discuss how to create digital certificates and how can we use them for secure communication.

Cryptographic system creates the digital certificates and digital certificate uses hashing & asymmetric encryption techniques. Any Digital certificate contains public/private key pair where public key known by all and private key known by only the owner and it saved in secure place.

Create Certificate: Open Microsoft Visual Studio Command prompt and execute command makecert -n "cn=CSharpCertificate" -sr currentuser -ss techinfocornerCertStore as shown below.

As shown above certificate created. We can find and export certificate by using mmc command. Open Run command and enter mmc, it displays console window. From File menu, open Add or Remove Snap-ins and Add Certificates as below and click Ok. Select My user account in Certificates snap-in.

If you expand Certificates node, we can find techinfocornerCertStore as shown below.

We can export the certificate by right click on the CSharpCertificate => All Tasks => select Export option as shown below.

Save the certificate in secure place. We have to provide this certificate to receiver for verification of the message.

Open Microsoft Visual Studio 2015 => Create Console Application and name it as CSharpDigitalCert. Add new class with name as DigitalCertificates. Add below code for DigitalCertificates to has data and to create signature.

using System.Security.Cryptography;

using System.Security.Cryptography.X509Certificates;

using System.Text; 

namespace CSharpDigitalCert

{

    public static class DigitalCertificates

    {

         public static bool VerifyMessage(byte[] signature, string messageFromAhemd)

        {

            var messageHash = GetMessageHash(messageFromAhemd);

            X509Certificate2 certificate = GetCertFromSystemStore();

            RSACryptoServiceProvider cryptoServiceProvider = (RSACryptoServiceProvider)certificate.PublicKey.Key;

            return cryptoServiceProvider.VerifyHash(messageHash, CryptoConfig.MapNameToOID("SHA1"), signature);

        } 

        public static byte[] GetDigitalSignatureForMsg(byte[] hashBytes)

        {

            X509Certificate2 certificate = GetCertFromSystemStore(); 

            RSACryptoServiceProvider rsaCryptoService = (RSACryptoServiceProvider)certificate.PrivateKey;

            return rsaCryptoService.SignHash(hashBytes, CryptoConfig.MapNameToOID("SHA1"));

        } 

        public static byte[] GetMessageHash(string sampleData)

        {

            SHA1Managed managedHash = new SHA1Managed();

            return managedHash.ComputeHash(Encoding.Unicode.GetBytes(sampleData));

        } 

        public static X509Certificate2 GetCertFromSystemStore()

        {

            X509Store x509Store = new X509Store("techinfocornerCertStore", StoreLocation.CurrentUser);

            x509Store.Open(OpenFlags.ReadOnly);

            return x509Store.Certificates[0];

        }

    }

} 

Now call these methods for given message as shown below.

using System; 

namespace CSharpDigitalCert

{

    class Program

    {

        static void Main(string[] args)

        {

            string msg = "This is the example for Digital Certificates in C#";           

            byte[] hashBytes = DigitalCertificates.GetMessageHash(msg);

            byte[] signature = DigitalCertificates.GetDigitalSignatureForMsg(hashBytes);

            bool isValidMsg = DigitalCertificates.VerifyMessage(signature, msg); 

            Console.WriteLine("Is it Correct message: {0}", isValidMsg);

            Console.ReadLine();

        }

    }

}

                                                                                    CSharpDigitalCert.zip