Base-64 char数组的长度无效

时间:2013-05-25 08:16:04

标签: c# login encryption

我正在处理Decrypt密码,我坚持这个错误Base-64 char数组的长度无效。我正在尝试太多的东西,但是由于这个错误,我的项目都被卡住了。这就是我的代码。< / p>

public string PasswordDecrypt(string sQueryString)
    {

        byte[] buffer;
        TripleDESCryptoServiceProvider loCryptoClass = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider loCryptoProvider = new MD5CryptoServiceProvider();


        try
        {
            string base64String;
            char[] base64CharArray;
            base64CharArray = new char[sQueryString.Length];
            base64String = new string(base64CharArray);
            Convert.FromBase64String(sQueryString);
            buffer = Convert.FromBase64String(sQueryString);
            loCryptoClass.Key = loCryptoProvider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(sQueryString.Replace("","+")));
            loCryptoClass.IV = lbtVector;
            return ASCIIEncoding.ASCII.GetString(loCryptoClass.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length));
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            loCryptoClass.Clear();
            loCryptoProvider.Clear();
            loCryptoClass = null;
            loCryptoProvider = null;
        }

    }

1 个答案:

答案 0 :(得分:1)

密码永远不应被解密(或加密,就此而言)。您应该在创建/更新凭证存储时创建密码的哈希值(最好是盐渍的),然后将该哈希值与从用户在尝试进行身份验证时输入的内容派生的哈希值进行比较。

这是我过去使用的一个实现(它有一些错误但适用于非关键应用程序):

public class HashProvider
{
    /// <summary>
    /// Computes the SHA1 hash from the given string.
    /// </summary>
    /// <param name="stringToHash">The string to hash.</param>
    /// <returns></returns>
    public static string GetSHA1Hash(string stringToHash)
    {
        var data = Encoding.UTF8.GetBytes(stringToHash);
        var hashData = new SHA1CryptoServiceProvider().ComputeHash(data);

        return String.Concat(hashData.Select(b => b.ToString("X2")));
    }


    /// <summary>
    /// Computes the SHA1 hash from the given string, and then encodes the hash as a Base64 string.
    /// </summary>
    /// <param name="stringToHash">The string to hash.</param>
    /// <returns></returns>
    public static string GetSHA1toBase64Hash(string stringToHash)
    {
        var data = Encoding.UTF8.GetBytes(stringToHash);
        var hashData = new SHA1CryptoServiceProvider().ComputeHash(data);

        return Convert.ToBase64String(hashData);
    }
}