2

Im getting the error 'Invalid length for a Base-64 char array or string.' on this line

rm.IV = Convert.FromBase64String(ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(text)).Split(',')[0]);

Here is the code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        textBox2.Enabled = false;
    }

    private void label2_Click(object sender, EventArgs e) { }

    private void button1_Click(object sender, EventArgs e)
    {
        String s = generateKey(256);
        textBox2.Text = s;
    }

    private String generateKey(int keySize)
    {
        RijndaelManaged rm = new RijndaelManaged();
        rm.KeySize = keySize;
        rm.BlockSize = 128;
        rm.Mode = CipherMode.CBC;
        rm.Padding = PaddingMode.PKCS7;
        rm.GenerateIV();
        String iv = Convert.ToBase64String(rm.IV);
        rm.GenerateKey();
        String key = Convert.ToBase64String(rm.Key);
        string completeKey = iv + "," + key;

        return Convert.ToBase64String(ASCIIEncoding.UTF8.GetBytes(completeKey));
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (textBox2.Text == "" || textBox2.Text == null)
        {
            MessageBox.Show("Please generate a key!");
        }
        else
        {
            String key = textBox2.Text;
            String strToBeEncoded = textBox1.Text;
            String s = encryptAES(strToBeEncoded, key, 256);
            outputBox.Text = s;
        }
    }

    private String encryptAES(String text, String key, int keySize)
    {
        RijndaelManaged rm = new RijndaelManaged();
        rm.KeySize = keySize;
        rm.BlockSize = 128;
        rm.Mode = CipherMode.CBC;
        rm.Padding = PaddingMode.PKCS7;
        rm.IV = Convert.FromBase64String(ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(text)).Split(',')[0]);
        rm.Key = Convert.FromBase64String(ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(key)).Split(',')[1]);
        byte[] plainText = ASCIIEncoding.UTF8.GetBytes(text);
        ICryptoTransform crypto = rm.CreateEncryptor();
        byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);
        return Convert.ToBase64String(cipherText);
    }
}
4

1 回答 1

2

您正试图将 IV 从要加密的字符串中提取出来。

尝试改变:

rm.IV = Convert.FromBase64String(ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(text)).Split(',')[0]);

至:

rm.IV = Convert.FromBase64String(ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(key)).Split(',')[0]);
于 2013-07-30T16:11:42.223 回答