使用现有密钥进行C#AES加密

问题描述

我正在尝试使用AES加密和已存在的密钥(存储在字符串中)对RSA公钥进行加密。

byte[] aesKey = Encoding.ASCII.GetBytes("QdQ/gNE+bRbxZe5S19KisveOGiDYCaynXN/olGVVQ3g="); 
        byte[] aesIV = Encoding.ASCII.GetBytes("vlymVsSBEgw1PDSeNhvZdw");
        Debug.WriteLine("We are in the get function. aesKey: " + Encoding.UTF8.GetString(aesKey,aesKey.Length) + " aesKey.ToString() = " + aesKey.ToString());
        //string strAESKey = Encoding.UTF8.GetString(aesKey,aesKey.Length);
        Aes myAes = Aes.Create();
        myAes.Key = aesKey; // it crashes here.
        myAes.IV = aesIV;

将aes密钥分配给myAes(myAes.Key = aesKey;)时会崩溃

我收到以下错误

System.Security.Cryptography.CryptographicException: 'The specified key is not a valid size for this algorithm.'

我该如何解决

解决方法

使用Convert.FromBase64String解码Base64字符串,因此您的第一行应该是

byte[] aesKey = Convert.FromBase64String("QdQ/gNE+bRbxZe5S19KisVEOGiDYCaynXN/olGVVQ3g="); 
        
byte[] aesIV = Convert.FromBase64String("vlymVsSBEgw1PDSeNhvZdw==");

请注意,您错过了IV字符串的填充。