要解密的数据长度无效

时间:2015-04-02 09:27:15

标签: c# encryption visual-studio-2013 cryptography .net-4.5

当crypto的异常表示要解密的数据长度无效时,我有解密密码的问题。我认为我需要将FromBase64更改为ToBase64。但它没有用。当代码在:

运行时发生了
 string plaintext = (new StreamReader(cs, Encoding.UTF8)).ReadToEnd();

这是我加密的完整代码:

public const string KEY = "123456sadasd"; // TODO: Change this key.

    public static string DecryptPassword(string encryptedText)
    {
        string base64req = encryptedText;
        string KEY = PasswordEncryption.KEY;
        int KEYBITCOUNT = 128;
        if (string.IsNullOrEmpty(base64req)) return base64req;
        RijndaelManaged crypt = new RijndaelManaged();
        crypt.KeySize = KEYBITCOUNT;
        crypt.Key = KeyFromString(KEY, KEYBITCOUNT);
        crypt.Padding = PaddingMode.None;
        MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64req));
        byte[] iv = new byte[crypt.IV.Length];
        ms.Read(iv, 0, iv.Length);
        crypt.IV = iv;
        CryptoStream cs = new CryptoStream(ms, crypt.CreateDecryptor(), CryptoStreamMode.Read);        
        //string plaintext = Convert.ToBase64String(iv).ToString();
        string plaintext = (new StreamReader(cs, Encoding.UTF8)).ReadToEnd();
        cs.FlushFinalBlock();
        //cs.Close();
        plaintext = plaintext.TrimEnd('\0');
        return plaintext; 
    }

    public static byte[] KeyFromString(string key, int keyBits)
    { // keyBits is 128, 192, or 256.
        byte[] keyBinary = Encoding.UTF8.GetBytes(key);
        byte[] b = new byte[keyBits / 8];
        for (int i = 0, j = 0; i < b.Length && j < keyBinary.Length; i++, j++)
        {
            b[i] = keyBinary[j];
        }
        return b;
    }
}

一点点帮助是值得欣赏的。感谢

0 个答案:

没有答案