How to do encrypt and decrypt data using Cryptography API Next Generation (CNG) in C#?

Prabs 1 Reputation point
2021-11-11T11:03:56.417+00:00

Hi Team,
How to implement encrypt and decrypt mechanism using CNG ( Cryptography API Next Generation) in C#.Net?

below link about CNG:
https://learn.microsoft.com/en-us/windows/win32/seccng/about-cng

Please help me on this.

Regards,
Prabhakaran

Developer technologies .NET .NET Runtime
Developer technologies C#
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. Zhiliang Xu 1 Reputation point Microsoft Employee
    2021-11-12T03:04:37+00:00

  2. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2021-11-12T08:44:17.587+00:00

    Hi @Prabs ,

    How to implement encrypt and decrypt mechanism using CNG ( Cryptography API Next Generation) in C#.Net?

    You can refer to the following two documents.
    https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aescng provides a CNG implementation of the Aes algorithm(SymmetricAlgorithm).
    https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rsacng provides a CNG implementation of the RSA algorithm(AsymmetricAlgorithm).
    Hope the documents could be helpful.
    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2021-11-19T06:21:24+00:00

    Hi @Prabs ,
    Here is a test example of AesCng https://github.com/er0dr1guez/corefx/blob/master/src/System.Security.Cryptography.Cng/tests/InvasiveCngTests.cs.
    And here is an implementation case of AesCng encryption and decryption which you can refer to.

            private String Encrypt_String_By_AesCng_Engine02(String PlainText,  
                                 String Password,  
                                  String Salt = "Kosher",  
                                 String HashAlgorithm = "SHA1",  
                                 int PasswordIterations = 2,  
                                 String InitialVector = "OFRna73m*aze01xY",  
                                 int KeySize = 256)  
            {  
            if (String.IsNullOrEmpty(PlainText)) return "";  
                byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);  
                byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);  
                byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);  
                PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);  
                SHA256Managed sHA256Managed = new SHA256Managed();  
                byte[] KeyBytes = sHA256Managed.ComputeHash(Encoding.Unicode.GetBytes(Password));  
      
            AesCng SymmetricKey = new AesCng();  
                SymmetricKey.Mode = CipherMode.CBC;  
                byte[] CipherTextBytes;  
                using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))  
                {  
                    using (MemoryStream MemStream = new MemoryStream())  
                    {  
                        using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))  
                        {  
                            CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);  
                            CryptoStream.FlushFinalBlock();  
                            CipherTextBytes = MemStream.ToArray();  
                            MemStream.Close();  
                            CryptoStream.Close();  
                        }  
                    }  
                }  
                SymmetricKey.Clear();  
            return Convert.ToBase64String(CipherTextBytes);  
            }  
      
            private String Decrypt_String_By_AesCng_Engine02(String CipherText,  
                         String Password,  
                          String Salt = "Kosher",  
                         String HashAlgorithm = "SHA1",  
                         int PasswordIterations = 2,  
                         String InitialVector = "OFRna73m*aze01xY",  
                         int KeySize = 256)  
            {  
                if (String.IsNullOrEmpty(CipherText))return "";  
                byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);  
                byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);  
                byte[] CipherTextBytes = Convert.FromBase64String(CipherText);  
                PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);  
                SHA256Managed sHA256Managed = new SHA256Managed();  
                byte[] KeyBytes = sHA256Managed.ComputeHash(Encoding.Unicode.GetBytes(Password));  
      
                AesCng SymmetricKey = new AesCng();  
                SymmetricKey.Mode = CipherMode.CBC;  
                byte[] PlainTextBytes = new byte[CipherTextBytes.Length - 1];  
                int ByteCount = 0;  
      
                using (ICryptoTransform Decryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))  
                {  
                    using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))  
                    {  
                        using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))  
                        {  
                            ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);  
                            MemStream.Close();  
                            CryptoStream.Close();  
                        }  
                    }  
                }  
                SymmetricKey.Clear();  
                return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);  
            }  
    

    Hope the code above colud be helpful.
    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  4. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2021-11-23T09:17:42.577+00:00

    Hi @Prabs ,
    I made some simplifications and modifications on the previous example, and it can now run correctly.
    You can refer to the following code.

            public string Encrypt(string PlainText, String Salt = "Kosher", String InitialVector = "OFRna73m*aze01xY")  
            {  
                if (string.IsNullOrEmpty(PlainText))  
                {  
                    return string.Empty;  
                }  
                SHA256Managed sHA256Managed = new SHA256Managed();  
                byte[] key = sHA256Managed.ComputeHash(Encoding.ASCII.GetBytes(Salt));  
                byte[] iv = Encoding.ASCII.GetBytes(InitialVector);  
      
                using (var SymmetricKey = new AesCng()  
                {  
                    Key = key,  
                    IV = iv,  
                    KeySize = 256,  
                    BlockSize = 128,  
                    Mode = CipherMode.CBC,  
                })  
                {  
                    using (var transform = SymmetricKey.CreateEncryptor(key, iv))  
                    {  
                        var inputBytes = Encoding.UTF8.GetBytes(PlainText);  
                        var encryptedBytes = transform.TransformFinalBlock(inputBytes, 0, inputBytes.Length);  
                        return Convert.ToBase64String(encryptedBytes);  
                    }  
                }  
            }  
      
            public string Decrypt(string CipherText, String Salt = "Kosher", String InitialVector = "OFRna73m*aze01xY")  
            {  
                if (string.IsNullOrEmpty(CipherText))  
                {  
                    return string.Empty;  
                }  
                SHA256Managed sHA256Managed = new SHA256Managed();  
                byte[] key = sHA256Managed.ComputeHash(Encoding.ASCII.GetBytes(Salt));  
                byte[] iv = Encoding.ASCII.GetBytes(InitialVector);  
      
                using (var SymmetricKey = new AesCng()  
                {  
                    Key = key,  
                    IV = iv,  
                    KeySize = 256,  
                    BlockSize = 128,  
                    Mode = CipherMode.CBC,  
                })  
                {  
                    using (var transform = SymmetricKey.CreateDecryptor(key, iv))  
                    {  
                        var inputBytes = Convert.FromBase64String(CipherText);  
                        var PlainTextBytes = transform.TransformFinalBlock(inputBytes, 0, inputBytes.Length);  
                        return Encoding.UTF8.GetString(PlainTextBytes);  
                    }  
                }  
            }  
    

    Hope the code above colud be helpful.
    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.