Minifycode 2023-02-14 Viewed 1.1K times C#

AES/CBC/PKCS5Padding Encryption/Decryption in C#


In this article you will learn, If you want to encrypt data in AES with mode CBC ( Cipher Block Chaining ) and in Padding > PKCS5, I use below code just for PKCS7, it is working as you need. 

You need to encrypt a string using DESede pkcs5 padding. However C# only provides PKCS7 padding. So how can I achieve this?

 

protected RijndaelManaged myRijndael;
        public string EncryptText(string plainText, string encryptionKey) 
        {
            string iv= GenerateKeyAndIV();
            using (myRijndael = new RijndaelManaged()) 
            {
                myRijndael.Key = HexStringToByte(encryptionKey); 
                myRijndael.IV = HexStringToByte(iv); 
                myRijndael.Mode = CipherMode.CBC; 
                myRijndael.Padding = PaddingMode.PKCS7; 
                byte[] encrypted = EncryptStringToBytes(plainText, myRijndael.Key, myRijndael.IV);
                byte[] data = myRijndael.IV.Concat(encrypted).ToArray();
                string encString = Convert.ToBase64String(data);
                return encString; 
            } 
        }
        protected byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV) 
        {     
            // Check arguments.
 
            if (plainText == null || plainText.Length <= 0)
         
                throw new ArgumentNullException("plainText");
     
            if (Key == null || Key.Length <= 0)
         
                throw new ArgumentNullException("Key");
     
            if (IV == null || IV.Length <= 0)
         
                throw new ArgumentNullException("Key");
     
            byte[] encrypted;     
            // Create an RijndaelManaged object 
            // with the specified key and IV. 
            using (RijndaelManaged rijAlg = new RijndaelManaged())         
            {         
                rijAlg.Key = Key;         
                rijAlg.IV = IV; 
                // Create a decrytor to perform the stream transform. 
                ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
                // Create the streams used for encryption. 
                using (MemoryStream msEncrypt = new MemoryStream())             
                {             
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))                 
                    {                 
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))                     
                        {
                            //Write all data to the stream. 
                            swEncrypt.Write(plainText);                     
                        }                 
                        encrypted = msEncrypt.ToArray();                 
                    }             
                }         
            }
            // Return the encrypted bytes from the memory stream.
            return encrypted;
        }

        public string DecryptText(string encryptedString,string encryptionKey)
        {
            
            using (myRijndael = new RijndaelManaged())

            {
                myRijndael.Key = HexStringToByte(encryptionKey);
                myRijndael.Mode = CipherMode.CBC;
                myRijndael.Padding = PaddingMode.PKCS7;
                Byte[] ourEnc = Convert.FromBase64String(encryptedString);
                byte[] enc = Convert.FromBase64String(encryptedString);
                myRijndael.IV = enc.Take(16).ToArray();
                enc = enc.Skip(16).ToArray();
                string ourDec = DecryptStringFromBytes(enc, myRijndael.Key, myRijndael.IV);
                return ourDec;
            }
        }
        protected string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            if (cipherText == null || cipherText.Length <= 0)

                throw new ArgumentNullException("cipherText");

            if (Key == null || Key.Length <= 0)

                throw new ArgumentNullException("Key");

            if (IV == null || IV.Length <= 0)

                throw new ArgumentNullException("Key");
            string plaintext = null;
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;

                rijAlg.IV = IV;
                // Create a decrytor to perform the stream transform.

                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
                // Create the streams used for decryption.

                using (MemoryStream msDecrypt = new MemoryStream(cipherText))

                {

                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))

                    {

                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                        {
                            plaintext = srDecrypt.ReadToEnd();

                        }

                    }

                }
            }
            return plaintext;
        }
        public  string GenerateKeyAndIV()
        {    
            // This code is only here for an example
            RijndaelManaged myRijndaelManaged = new RijndaelManaged();    
            myRijndaelManaged.Mode = CipherMode.CBC;    
            myRijndaelManaged.Padding = PaddingMode.PKCS7;
            myRijndaelManaged.GenerateIV();    
            myRijndaelManaged.GenerateKey();
            string newinitVector = ByteArrayToHexString(myRijndaelManaged.IV);
            return newinitVector;
        }
        protected static byte[] HexStringToByte(string hexString) 
        {
            try 
            {         
                int bytesCount = (hexString.Length) / 2;         
                byte[] bytes = new byte[bytesCount];         
                for (int x = 0; x < bytesCount; ++x)             
                {             
                    bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);             
                }         
                return bytes;         
            }     
            catch 
            {         
                throw;         
            }     
        }
        public static string ByteArrayToHexString(byte[] ba) 
        {         
            StringBuilder hex = new StringBuilder(ba.Length * 2);         
            foreach (byte b in ba)             
                hex.AppendFormat("{0:x2}", b);         
            return hex.ToString();         
        }

 

AES/CBC/PKCS5Padding Encryption/Decryption in C#
C# is a programming language developed by Microsoft that runs on the .NET Framework. C# is used to develop web, desktop, mobile, games and much more application. C# is a object-oriented programming language developed by Microsoft within its .NET Framework. Led by Anders Hejlsberg, your basic C# programming and will also take you through various advanced concepts related to C# programming language. C# such as control statements, objects and classes, inheritance, constructor, destructor, this, static, sealed, polymorphism, abstraction, abstract class, interface, File IO, Collections, namespace, encapsulation, properties, indexer, arrays, strings, regex, exception handling, multithreading etc. For example... using System; namespace MinifyCode { class Program { static void Main(string[] args) { Console.WriteLine("Hello Minify Code"); } } } Output: Hello Minify Code In this article you will learn, what is server side controls. We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request object, and the Response object. Session Application Cache Request Response Server User Trace Server Object The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform many type of jobs. Methods and Properties of the Server object The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; using System.Data.Entity; namespace minifycode { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Initialize the product database. Database.SetInitializer(new ProductDatabaseInitializer()); // Create custom role and user. RoleActions roleActions = new RoleActions(); roleActions.AddUserAndRole(); // Add Routes. RegisterCustomRoutes(RouteTable.Routes); } void RegisterCustomRoutes(RouteCollection routes) { routes.MapPageRoute( "ProductsCategoryRoute", "Category/{categoryName}", "~/ProductList.aspx" ); routes.MapPageRoute( "ProductNameRoute", "Product/{productName}", "~/ProductDetails.aspx" ); } } }