Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I'm having problems getting RijndaelManaged to work with AES 128 CBC. I havent used RijndaelManaged before so i would really appreciate if some could help. I'm trying to produce a result shown in this web page, section AES CBC 128-bit encryption mode. I have done it in Java but i used PKCS5 as padding mode but it does not exist in RijndaelManaged.


string hexKey = "2b7e151628aed2a6abf7158809cf4f3c";
string hexIv = "000102030405060708090A0B0C0D0E0F";
string hexText = "6bc1bee22e409f96e93d7e117393172a";


byte[] keyBytes = Encoding.ASCII.GetBytes(HexToAscii(hexKey));
byte[] ivBytes = Encoding.ASCII.GetBytes(HexToAscii(hexIv));
string asciiText = HexToAscii(hexText);

byte[] encryptedBytes = encryptStringToBytes_AES(asciiText, keyBytes, ivBytes);
string encryptedStr = Encoding.ASCII.GetString(encryptedBytes);
string encryptedHex = AsciiToHex(encryptedStr);
// Correct result of encryptedHex should be 7649abac8119b246cee98e9b12e9197d 
// but is 7183f203f3f5d3f5c3f3f4e3f33513f3f23673f3f3f3f3f553f3b4533f3f42	



//
// This is copy-pase code from http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx
public static byte[] encryptStringToBytes_AES(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("IV");

	// Declare the stream used to encrypt to an in memory
	// array of bytes.
	MemoryStream msEncrypt = null;

	// Declare the RijndaelManaged object
	// used to encrypt the data.
	RijndaelManaged aesAlg = null;

	try
	{
		// Create a RijndaelManaged object
		// with the specified key and IV.
		aesAlg = new RijndaelManaged();
		aesAlg.KeySize = 128;
		aesAlg.Mode = CipherMode.CBC;
		aesAlg.Padding = PaddingMode.PKCS7;
		aesAlg.Key = Key;
		aesAlg.IV = IV;


		// Create an encryptor to perform the stream transform.
		ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

		// Create the streams used for encryption.
		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);
			}
		}
	}
	finally
	{
		// Clear the RijndaelManaged object.
		if (aesAlg != null)
			aesAlg.Clear();
	}

	// Return the encrypted bytes from the memory stream.
	return msEncrypt.ToArray();
}



public static string AsciiToHex(string ascii)
        {
            string hex = "";

            for (int i = 0; i < ascii.Length; i++)
            {
                hex += Convert.ToInt32(ascii[i]).ToString("x");
            }

            return hex;
        }


public static string HexToAscii(string hex)
        {
            string ascii = "";

            for (int i = 0; i < hex.Length - 1; i = i + 2)
            {
                String oneHex = hex.Substring(i, 2);
                UInt32 asciiNum = Convert.ToUInt32(oneHex, 16);
                char asciiChar = Convert.ToChar(asciiNum);
                ascii += asciiChar.ToString();
            }

            return ascii;
        }
Posted

1 solution

Hi

I am not very clear about your approach. However I am give the microsoft example code in addition with a SALT and PASSWORD to encrypt.

When you call like MessageBox.Show(RijndaelMemoryExample.Test("my test string")); It returns the same input string after encryption and then decryption.

C#
<pre lang="msil">class RijndaelMemoryExample
    {
    public static string Test(string original)
        {
            try
            {
                //Use a salt and password to protect the string
                string saltText = "Test salt";
                string password = "Test password";
                // Create a new instance of the RijndaelManaged
                // class.  This generates a new key and initialization
                // vector (IV).
                System.Security.Cryptography.RijndaelManaged myRijndael = new System.Security.Cryptography.RijndaelManaged();
                byte[] salt = Encoding.ASCII.GetBytes(saltText);
                Rfc2898DeriveBytes rfcKey = new Rfc2898DeriveBytes(password, salt);
                myRijndael.Key = rfcKey.GetBytes(myRijndael.KeySize / 8);
                myRijndael.IV = rfcKey.GetBytes(myRijndael.BlockSize / 8);
                // Encrypt the string to an array of bytes.
                byte[] encrypted = encryptStringToBytes_AES(original, myRijndael.Key, myRijndael.IV);
                // Decrypt the bytes to a string.
                string roundtrip = decryptStringFromBytes_AES(encrypted, myRijndael.Key, myRijndael.IV);
                return roundtrip;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
                return "";
            }
        }
        static byte[] encryptStringToBytes_AES(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("IV");
            // Declare the stream used to encrypt to an in memory
            // array of bytes.
            MemoryStream msEncrypt = null;
            // Declare the RijndaelManaged object
            // used to encrypt the data.
            System.Security.Cryptography.RijndaelManaged aesAlg = null;
            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new System.Security.Cryptography.RijndaelManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;
                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for encryption.
                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);
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            // Return the encrypted bytes from the memory stream.
            return msEncrypt.ToArray();
        }
        static string decryptStringFromBytes_AES(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            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("IV");
            // Declare the RijndaelManaged object
            // used to decrypt the data.
            System.Security.Cryptography.RijndaelManaged aesAlg = null;
            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;
            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new System.Security.Cryptography.RijndaelManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.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))
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            return plaintext;
        }
    }


 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900