无法获得RijndaelManaged AES 128 CBC来产生已知结果 [英] Can't get RijndaelManaged AES 128 CBC to produce a known result

查看:66
本文介绍了无法获得RijndaelManaged AES 128 CBC来产生已知结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在让RijndaelManaged与AES 128 CBC配合使用时遇到问题.我以前没有使用过RijndaelManaged,所以如果能帮助我,我将不胜感激.我正在尝试产生显示的结果 网页的"AES CBC 128位加密模式"部分.我已经在Java中完成了此操作,但我使用PKCS5作为填充模式,但在RijndaelManaged中不存在.


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;
        }

推荐答案



对于您的方法,我不太清楚.但是,除了加密的SALT和PASSWORD外,我还给了Microsoft示例代码.

当您像MessageBox.Show(RijndaelMemoryExample.Test("my test string"))那样调用时;加密然后解密后,它返回相同的输入字符串.

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.

<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;
        }
    }






这篇关于无法获得RijndaelManaged AES 128 CBC来产生已知结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆