Howto write .Net Encrypt using X509 Certificate in C#

Hello there ,

In this post we will see how to Encrypt/Decrypt a string using X509 Certificate in C#.

I will include encryption/decryption functions below .

The code will assume that the public key is available for the program, and the private key for the certificate saved in Windows Certificate store

 // Encrypt 
        public string EncryptMessage(String message)
        {
            // Initialize the certificate
            X509Certificate2 cert = new X509Certificate2();
            //create string encoder
            UTF8Encoding encoder = new UTF8Encoding();
            // import certificate
            cert.Import(encoder.GetBytes(certificate));

            ContentInfo contentInfo = new ContentInfo(encoder.GetBytes(message));
            EnvelopedCms envelop = new EnvelopedCms(contentInfo);
            CmsRecipient recip = new CmsRecipient(cert);
            envelop.Encrypt(recip);
            byte[] encoded = envelop.Encode();
            return Convert.ToBase64String(envelop.Encode());
        }

        // Decrypt 
        public string DecryptMessage(string message)
        {
            UTF8Encoding encoder = new UTF8Encoding();

            EnvelopedCms envelop = new EnvelopedCms();
            envelop.Decode(Convert.FromBase64String(message));
            //envelop.Decrypt(envelop.RecipientInfos[0]);
            envelop.Decrypt();

            byte[] messageInBytes = envelop.ContentInfo.Content;

            return encoder.GetString(messageInBytes);
        }
Posted in Cryptography, Programming and tagged , , , , , , , , , , . Bookmark the permalink. RSS feed for this post. Leave a trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

Swedish Greys - a WordPress theme from Nordic Themepark.