none
微软MSDN中AES类示例代码如何改变秘钥长度?

    问题

  • 各位专家:

        微软在AES类的解释中给出了示例代码(原文地址:https://msdn.microsoft.com/zh-cn/library/bb352381(v=vs.110).aspx),经过大神Shuanghua Li 和 cole wu的指点,结合我自己的摸索,实现了密码的录入(这个帖子地址:https://social.msdn.microsoft.com/Forums/zh-CN/ba97d0f8-425e-4967-8b9e-ba5cf9b6321c/msdnaes?forum=2212)。

        但目前也出现了下列问题:

        输入的密码长度只能是16个字符,既不能多,也不能少。否则就会出现“指定秘钥大小对此算法无效”的提示,情况如下图:

        我也浅显的了解到aes秘钥有128 192 256三种长度,但当我改变KeySide属性时(如人工制定myAes.KeySize = 256;时),也只能输入16位字符,否则依然出现上图提示。

        我不是专门的密码学专业毕业,对加密算法的理解目前只能停留在这样初级的阶段。

        我想达到的效果是:

        1、能够使用任意长度的字符进行加密。

        2、设定aes的秘钥长度。

        不知该如何修改代码?还请指点。谢谢大家!

        所有代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Security.Cryptography;
    using System.IO;
    
    namespace CSharp_7_AES
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    string original = "Here is some data to encrypt!";//待加密数据
    
                    // Create a new instance(实例) of the Aes class.  
                    // This generates a new key and initialization(初始化) vector(向量) (IV).
                    using (Aes myAes = Aes.Create())
                    {
                        myAes.KeySize = 256;//怎么没用呢?!
                        /*----补充内容------------------------------------------------------*/
                        Console.WriteLine("请输入密码");
                        string myKey = Console.ReadLine();//读取用户输入的密码   
                        myAes.Key = Encoding.ASCII.GetBytes(myKey);//这样写是行的
                        /*------------------------------------------------------------------*/
    
                        // Encrypt the string to an array of bytes.将数据加密为字节
                        byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);
    
                        // Decrypt the bytes to a string.从字节解密还原成数据
                        string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);
    
                        //Display the original data and the decrypted data.
                        Console.WriteLine("Original:   {0}", original);//原数据
                        Console.WriteLine("Round Trip: {0}", roundtrip);//解密后的数据
    
                        Console.ReadLine();//为了看结果用
                    }
    
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                    Console.ReadLine(); //为了看结果用
                }
    
            }
            /*----补充内容------------------------------------------------------*/
            //输入的密码转化为字节数组的方法
            static byte[] myGetBytes(string str)
            {
                byte[] bytes = new byte[str.Length * sizeof(char)];
                System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
                return bytes;
            }
            /*------------------------------------------------------------------*/
    
            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");
                byte[] encrypted;
                // Create an Aes object
                // with the specified key and IV.
                using (Aes aesAlg = Aes.Create())
                {
                    aesAlg.Key = Key;
                    aesAlg.IV = IV;
    
                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.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;
    
            }
    
            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 string used to hold
                // the decrypted text.
                string plaintext = null;
    
                // Create an Aes object
                // with the specified key and IV.
                using (Aes aesAlg = Aes.Create())
                {
                    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();
                            }
                        }
                    }
    
                }
    
                return plaintext;
    
            }
    
        }
    }


    • 已编辑 wxysy 2016年10月14日 1:38 补充链接
    2016年10月14日 1:35

全部回复

  • Hi wxysy,

    也行你需要对这个length进行转换.

    在加密的方法里面,应该这样转换一下:

    string encryptedString = Convert.ToBase64String(encryptedBytes);

    解密的方法里面,应该是:

    byte[] encryptedBytes = Convert.FromBase64String(encryptedString);

    你可以尝试一下.

    Best Regards,

    Hart


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. Click HERE to participate the survey.

    2016年10月18日 5:29
    版主
  • 感谢您的答复,但我试了数次,不成功,关键是找不到您说的加密解密中到底该怎么改,我找不到您说的两句代码的具体放置位置,还请赐教。
    2016年12月20日 0:44