0

我正在处理解密密码,我遇到了这个错误 Invalid length for a Base-64 char array。我尝试了太多东西,但由于这个错误,我的项目被卡住了。这是我的代码。

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;
        }

    }
4

1 回答 1

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);
    }
}
于 2013-05-25T08:31:39.283 回答