none
cryptograpy with rijndaelSymmetry key RRS feed

  • Question

  • Hi,
    I'm using the RijndaelSymmetry key for encrypting and decrypting strings in two web service methods.
    During my tests I found that the word "finally" has the encrypted value of "RXh+WV+v0ZBp1foSCeJ1Nw=="
    and "Finally" has the encrypted value of "ZInthcow0Hhm9z0cu6gT4Q=="

    When I try to Decrypt "ZInthcow0Hhm9z0cu6gT4Q==", it succeeds.
    However, when I try to Decrypt "RXh+WV+v0ZBp1foSCeJ1Nw==", I receive a "wrong format "error message.
    Would you be able to help me resolve this error?
    Thank you.
    Chieko Jurkus


    Chieko

    Hi Timon,  Sorry for the delay in responding with my code for encrypting and decrypting strings.  Here it is:  I have three classes, Class for RijndaelSymmetricKey, CryptoHelper that calls methods in the RijndaelSymmetricKey class, and  the EncryptionController  with web method to call the CryptoHelper methods, and finally, the javascript methods that call the encryption controller encryptdata and decryptdata web methods.

    Class for RijndaelSymmetricKey:
    namespace SymmetricKeyGenTool
    {
        /// <summary>
        /// This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and
        /// decrypt data. As long as encryption and decryption routines use the same
        /// parameters to generate the keys, the keys are guaranteed to be the same.
        /// </summary>
        public class RijndaelSymmetricKey
        {
            /// <summary>
            /// Encrypts specified plaintext using Rijndael symmetric key algorithm
            /// and returns a base64-encoded result.
            /// </summary>
            /// <param name="plainText">
            /// Plaintext value to be encrypted.
            /// </param>
            /// <param name="passPhrase">
            /// Passphrase from which a pseudo-random password will be derived. The
            /// derived password will be used to generate the encryption key.
            /// Passphrase can be any string.
            /// </param>
            /// <param name="saltValue">
            /// Salt value used along with passphrase to generate password. Salt can
            /// be any string.
            /// </param>
            /// <param name="hashAlgorithm">
            /// Hash algorithm used to generate password. Allowed values are: "MD5" and
            /// "SHA1". SHA1 hashes are a bit slower.
            /// </param>
            /// <param name="passwordIterations">
            /// Number of iterations used to generate password. One or two iterations
            /// should be enough.
            /// </param>
            /// <param name="initVector">
            /// Initialization vector (or IV). This value is required to encrypt the
            /// first block of plaintext data. For RijndaelManaged class IV must be
            /// exactly 16 ASCII characters long.
            /// </param>
            /// <param name="keySize">
            /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
            /// Longer keys are more secure than shorter keys.
            /// </param>
            /// <returns>
            /// Encrypted value formatted as a base64-encoded string.
            /// </returns>
            public static string Encrypt
            (
                string plainText,
                string passPhrase,
                string saltValue,
                string hashAlgorithm,
                int passwordIterations,
                string initVector,
                int keySize
            )
            {
                byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
                byte[] saltValueBytes = Encoding.UTF8.GetBytes(saltValue);

                // Convert our plaintext into a byte array.
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

                // First, we must create a password, from which the key will be derived.
                // This password will be generated from the specified passphrase and
                // salt value. The password will be created using the specified hash
                // algorithm. Password creation can be done in several iterations.
                PasswordDeriveBytes password = new PasswordDeriveBytes
                (
                    passPhrase,
                    saltValueBytes,
                    hashAlgorithm,
                    passwordIterations
                );

                // Use the password to generate pseudo-random bytes for the encryption
                // key. Specify the size of the key in bytes (instead of bits).
                byte[] keyBytes = password.GetBytes(keySize / 8);

                // Create uninitialized Rijndael encryption object.
                RijndaelManaged symmetricKey = new RijndaelManaged();

                // It is reasonable to set encryption mode to Cipher Block Chaining
                // (CBC). Use default options for other symmetric key parameters.
                symmetricKey.Mode = CipherMode.CBC;

                // Generate encryptor from the existing key bytes and initialization
                // vector. Key size will be defined based on the number of the key
                // bytes.
                ICryptoTransform encryptor = symmetricKey.CreateEncryptor
                (
                    keyBytes,
                    initVectorBytes
                );

                // Define memory stream which will be used to hold encrypted data.
                MemoryStream memoryStream = new MemoryStream();

                // Define cryptographic stream (always use Write mode for encryption).
                CryptoStream cryptoStream = new CryptoStream
                (
                    memoryStream,
                    encryptor,
                    CryptoStreamMode.Write
                );

                // Start encrypting.
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

                // Finish encrypting.
                cryptoStream.FlushFinalBlock();

                // Convert our encrypted data from a memory stream into a byte array.
                byte[] cipherTextBytes = memoryStream.ToArray();

                // Close both streams.
                memoryStream.Close();
                cryptoStream.Close();

                // Convert encrypted data into a base64-encoded string.
                string cipherText = Convert.ToBase64String(cipherTextBytes);

                // Return encrypted string.
                return cipherText;
            }

            /// <summary>
            /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
            /// </summary>
            /// <param name="cipherText">
            /// Base64-formatted ciphertext value.
            /// </param>
            /// <param name="passPhrase">
            /// Passphrase from which a pseudo-random password will be derived. The
            /// derived password will be used to generate the encryption key.
            /// Passphrase can be any string.
            /// </param>
            /// <param name="saltValue">
            /// Salt value used along with passphrase to generate password. Salt can
            /// be any string.
            /// </param>
            /// <param name="hashAlgorithm">
            /// Hash algorithm used to generate password. Allowed values are: "MD5" and
            /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
            /// </param>
            /// <param name="passwordIterations">
            /// Number of iterations used to generate password. One or two iterations
            /// should be enough.
            /// </param>
            /// <param name="initVector">
            /// Initialization vector (or IV). This value is required to encrypt the
            /// first block of plaintext data. For RijndaelManaged class IV must be
            /// exactly 16 ASCII characters long.
            /// </param>
            /// <param name="keySize">
            /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
            /// Longer keys are more secure than shorter keys.
            /// </param>
            /// <returns>
            /// Decrypted string value.
            /// </returns>
            /// <remarks>
            /// Most of the logic in this function is similar to the Encrypt
            /// logic.
            /// </remarks>
            public static string Decrypt
            (
                string cipherText,
                string passPhrase,
                string saltValue,
                string hashAlgorithm,
                int passwordIterations,
                string initVector,
                int keySize
            )
            {
                // Convert strings defining encryption key characteristics into byte
                // arrays.

                byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
                byte[] saltValueBytes = Encoding.UTF8.GetBytes(saltValue);

                // Convert our ciphertext into a byte array.
                byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

                // First, we must create a password, from which the key will be
                // derived. This password will be generated from the specified
                // passphrase and salt value. The password will be created using
                // the specified hash algorithm. Password creation can be done in
                // several iterations.
                PasswordDeriveBytes password = new PasswordDeriveBytes
                (
                    passPhrase,
                    saltValueBytes,
                    hashAlgorithm,
                    passwordIterations
                );

                // Use the password to generate pseudo-random bytes for the encryption
                // key. Specify the size of the key in bytes (instead of bits).
                byte[] keyBytes = password.GetBytes(keySize / 8);

                // Create uninitialized Rijndael encryption object.
                RijndaelManaged symmetricKey = new RijndaelManaged();

                // It is reasonable to set encryption mode to Cipher Block Chaining
                // (CBC). Use default options for other symmetric key parameters.
                symmetricKey.Mode = CipherMode.CBC;

                // Generate decryptor from the existing key bytes and initialization
                // vector. Key size will be defined based on the number of the key
                // bytes.
                ICryptoTransform decryptor = symmetricKey.CreateDecryptor
                (
                    keyBytes,
                    initVectorBytes
                );

                // Define memory stream which will be used to hold encrypted data.
                MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

                // Define cryptographic stream (always use Read mode for encryption).
                CryptoStream cryptoStream = new CryptoStream
                (
                    memoryStream,
                    decryptor,
                    CryptoStreamMode.Read
                );

                // Since at this point we don't know what the size of decrypted data
                // will be, allocate the buffer long enough to hold ciphertext;
                // plaintext is never longer than ciphertext.
                byte[] plainTextBytes = new byte[cipherTextBytes.Length];

                // Start decrypting.
                int decryptedByteCount = cryptoStream.Read
                (
                    plainTextBytes,
                    0,
                    plainTextBytes.Length
                );

                // Close both streams.
                memoryStream.Close();
                cryptoStream.Close();

                // Convert decrypted data into a string.
                // Let us assume that the original plaintext string was UTF8-encoded.
                string plainText = Encoding.UTF8.GetString
                (
                    plainTextBytes,
                    0,
                    decryptedByteCount
                );

                // Return decrypted string.  
                return plainText;
            }
        }
    }

    Class for cryptoHelper:

    namespace SymmetricKeyGenTool
    {
       public static  class CryptoHelper
        {
            private static string passPhrase = "Pas5pr@se"; // can be any string
            private static string saltValue = "{3Di-Inc-USA}";        // can be any string
            private static string hashAlgorithm = "SHA1";             // can be "MD5"
            private static int passwordIterations = 2;                // can be any number
            private static string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
            private static int keySize = 256;                // can be 192 or 128

            public static string Encrypt(string plainText)
            {
                string cipherText = RijndaelSymmetricKey.Encrypt
               (
                   plainText,
                   passPhrase,
                   saltValue,
                   hashAlgorithm,
                   passwordIterations,
                   initVector,
                   keySize
               );
                return cipherText;
            }
            public static string Decrypt(string cipherText)
            {
                string plainText = RijndaelSymmetricKey.Decrypt
                (
                    cipherText,
                    passPhrase,
                    saltValue,
                    hashAlgorithm,
                    passwordIterations,
                    initVector,
                    keySize
                );
                return plainText;
            }
        }
    }

    web method to encrypt / decrypt:
    namespace Services.Encryption.Controllers
    {
        /// <summary>
        ///           Provides methods to encrypt a string value and Decrypt a string value.
        /// </summary>
        public class EncryptionController : ApiController
        {
            /// <summary>
            ///             Decrypts a string value.
            /// </summary>
            /// <param name="StringToDecrypt">value of the string to decrypt</param>
            /// <returns>value of the decrypted string.</returns>
            [HttpGet]
            public   IHttpActionResult DecryptData(string StringToDecrypt)
            {
                string stacktrace = string.Empty;
                string errortype = string.Empty;
                string DecryptedData = string.Empty;
                try
                {
                    string s = HttpUtility.UrlDecode(StringToDecrypt);
                   DecryptedData = SymmetricKeyGenTool.CryptoHelper.Decrypt(HttpUtility.UrlDecode(StringToDecrypt));
                 
                }// catch error when the stringToDecrypt is not the right format.
                catch (System.FormatException formatEx)
                {              
                    errortype = formatEx.GetType().ToString();
                    DecryptedData = "Oops something went wrong..." + errortype + ". Please ensure the value for StringToDecrypt is correct";
                }//  catch all of the rest of the errors.
                catch(System.Security.Cryptography.CryptographicException c)
                {
                    string mssg = c.Message;
                }
                catch (Exception ex) {
                    stacktrace = ex.StackTrace;
                    errortype = ex.GetType().ToString();
                    DecryptedData = "Oops something went wrong..." + stacktrace;
                }
                // string DecryptedData = SymmetricKeyGenTool.CryptoHelper.Decrypt(StringToDecrypt);
                return Ok(DecryptedData);

                /* how to call the method*/
                //http://localhost:50824/api/Encryption/DecryptData?StringTodecrypt=22fPUWLGTgc6/+PzSdAwtawA==
                // where localhost : 50824 is the value of the domain.
                // http://localhost/Encryption_API/api/Encryption/DecryptData?StringToDecrypt=DIe9cbfNkCBsINxSkQt0Ww== // from iis localhost
            }

            /// <summary>
            ///           Encrypts a string value
            /// </summary>
            /// <param name="StringToEncrypt">value to encrypt</param>
            /// <returns>value of the encrypted string.</returns>
           [HttpGet]
           public IHttpActionResult EncryptData(string StringToEncrypt)
            {
               return  Ok(SymmetricKeyGenTool.CryptoHelper.Encrypt(StringToEncrypt));

                /* how to call the method*/
                // http://localhost:50824/api/Encryption/EncryptData?StringToEncrypt=me
                // where localhost : 50824 is the value of the domain.
                //http://localhost/Encryption_API/api/Encryption/EncryptData?StringToEncrypt=me // from IIS localhost
            }


        }
    }

    Javascript methods to call web service encrypt and decrypt:
    <script language="javascript">
         // declare the uri for the web service.
         var uri = 'api/Encryption';

             $( document ).ready(function() {
             //alert( "Ready!" );
             });

         function EncryptString() {
            // alert("string encrypted");
             var StringToEncrypt = $('#StringToEncrypt').val();
             $.getJSON(uri + '/EncryptData?StringToEncrypt=' + encodeURIComponent(StringToEncrypt))
                 .done(function (data) {
                     $('#EncryptedStringValue').text(data);
                 })
                 .fail(function (jqXHR, textStatus, err) {
                     $('#EncryptedStringValue').text('Error: ' + err);
                 });
         }
         function DecryptString() {
            // alert("string decrypted");
             var StringToDecrypt = $('#StringToDecrypt').val();
             $.getJSON(uri + '/DecryptData?StringToDecrypt=' + encodeURIComponent(StringToDecrypt))
                 .done(function (data) {
                     $('#DecryptedStringValue').text(data);
                 })
                 .fail(function (jqXHR, textStatus, err) {
                     $('#DecryptedStringValue').text('Error: ' + err);
                 });

         }
            </script>

    Thank you very much.

    Chieko

    • Edited by Chieko Thursday, June 25, 2020 6:56 PM Additional code files used to encrypt and decrypt strings
    Tuesday, June 23, 2020 11:44 PM

Answers

  • The encryption is fine. You can confirm this using a simple test app.

    static void Main(string[] args)
    {
        var tests = new[]
        {
            "finally",
            "Finally"
        };
    
        Console.WriteLine("Input\t\tEncrypted\t\t\tDecrypted");
        Console.WriteLine(new string('-', 70));
        foreach (var test in tests)
        {
            var encrypted = CryptoHelper.Encrypt(test);
            var decrypted = CryptoHelper.Decrypt(encrypted);
    
            Console.WriteLine($"{test.PadRight(20)}{encrypted.PadRight(30)}{decrypted.PadRight(30)}");
        }
    }

    The issue is with this line.

    string s = HttpUtility.UrlDecode(StringToDecrypt);

    It is a common believe that bas64 values are valid in URLs. Notice the encrypted value `RXH+WV". Spaces aren't allowed in URLs so we use either %20 or +. When the server gets that value back it doesn't do anything by default. However you call UrlDecode which proceeds to go through and replace all %## values with their decoded equivalent. This includes the +. So the resultant string is no longer the correct encrypted value. Base64 strings are valid in URLs but they may contain characters (the plus specifically) that are not valid in decoded values. Hence you cannot decode a URL that contains a base64 string unless you first guarantee that it has been encoded. Failure to do this corrupts the value. 

    Since you don't URL encode the value when you pass it back from your original encryption you shouldn't try to decode it when you get it either. URL encoding must always be paired. Remove the URL decoding line and your problem will go away.

    I should mention that if you want this more bulletproof then consider hex encoding after base64 encoding. Hex encoding converts all the base64 characters to their hex equivalent. This allows you to then URL encode (or decode) and it won't change the original value. I would only do this if you really don't know whether the passed value is encoded or not though.


    Michael Taylor http://www.michaeltaylorp3.net


    Monday, June 29, 2020 4:34 PM
    Moderator

All replies

  • Hi Cgieko,

    Thank you for posting here.

    It is difficult for us to analyze the cause of the error based on the existing information, please provide some code for us to test.

    Do you mind encrypting the string into a byte array?

    This is an example.

            public static void Main()
            {
                try
                {
                    string original = "Finally";
                    using (RijndaelManaged myRijndael = new RijndaelManaged())
                    {
    
                        myRijndael.GenerateKey();
                        myRijndael.GenerateIV();
                        byte[] encrypted = EncryptStringToBytes(original,
                                           myRijndael.Key, myRijndael.IV);
    
                        string aftdecryp = DecryptStringFromBytes(encrypted,
                                           myRijndael.Key, myRijndael.IV);
                        Console.WriteLine("Original: {0}", original);
                        Console.WriteLine("After Decryption: {0}", aftdecryp);
                    }
    
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
    
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                }
            }
            static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
            {
                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;
                using (RijndaelManaged rijAlg = new RijndaelManaged())
                {
                    rijAlg.Key = Key;
                    rijAlg.IV = IV;
                    ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key,
                                                 rijAlg.IV);
                    using (MemoryStream msEncrypt = new MemoryStream())
                    {
                        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt,
                                encryptor, CryptoStreamMode.Write))
                        {
                            using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                            {
                                swEncrypt.Write(plainText);
                            }
                            encrypted = msEncrypt.ToArray();
                        }
                    }
                }
                return encrypted;
            }
            static 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;
                    ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key,
                                                 rijAlg.IV);
                    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;
            }

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, June 24, 2020 2:07 AM
  • Hi Chieko,

    Rather than edit your original reply to provide the code that Timon asked for, you should have provided that code in a Reply to Timon. Otherwise, he's not notified that you have responded.

    You don't have to create a new reply now, since by me replying, Timon will be notified that there are replies to this thread.


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Monday, June 29, 2020 3:42 PM
    Moderator
  • The encryption is fine. You can confirm this using a simple test app.

    static void Main(string[] args)
    {
        var tests = new[]
        {
            "finally",
            "Finally"
        };
    
        Console.WriteLine("Input\t\tEncrypted\t\t\tDecrypted");
        Console.WriteLine(new string('-', 70));
        foreach (var test in tests)
        {
            var encrypted = CryptoHelper.Encrypt(test);
            var decrypted = CryptoHelper.Decrypt(encrypted);
    
            Console.WriteLine($"{test.PadRight(20)}{encrypted.PadRight(30)}{decrypted.PadRight(30)}");
        }
    }

    The issue is with this line.

    string s = HttpUtility.UrlDecode(StringToDecrypt);

    It is a common believe that bas64 values are valid in URLs. Notice the encrypted value `RXH+WV". Spaces aren't allowed in URLs so we use either %20 or +. When the server gets that value back it doesn't do anything by default. However you call UrlDecode which proceeds to go through and replace all %## values with their decoded equivalent. This includes the +. So the resultant string is no longer the correct encrypted value. Base64 strings are valid in URLs but they may contain characters (the plus specifically) that are not valid in decoded values. Hence you cannot decode a URL that contains a base64 string unless you first guarantee that it has been encoded. Failure to do this corrupts the value. 

    Since you don't URL encode the value when you pass it back from your original encryption you shouldn't try to decode it when you get it either. URL encoding must always be paired. Remove the URL decoding line and your problem will go away.

    I should mention that if you want this more bulletproof then consider hex encoding after base64 encoding. Hex encoding converts all the base64 characters to their hex equivalent. This allows you to then URL encode (or decode) and it won't change the original value. I would only do this if you really don't know whether the passed value is encoded or not though.


    Michael Taylor http://www.michaeltaylorp3.net


    Monday, June 29, 2020 4:34 PM
    Moderator
  • In addition to what CoolDadTx told you, there are some semi-standard ways of transforming base 64 so that it becomes "Url-safe".

    One of the most common replaces "+" and "/" with "-" and "_", and suppresses the "=" padding. Of course, these changes have to be reversed before decoding from base 64 at the receiving end. This results in a shorter text than you would get by using hex encoding.

    See https://en.wikipedia.org/wiki/Base64#URL_applications

    Monday, June 29, 2020 8:11 PM
    Moderator
  • Thank you so much for your help. Indeed, when I took out the line for decoding the url, the error went away.

    Chieko


    Chieko

    Saturday, July 11, 2020 7:17 PM
  • Thank you for your comments. I will try the hex encoding after base 64 encoding.

    Chieko


    Chieko

    Saturday, July 11, 2020 7:20 PM