Windows窗体如何解密密码SQL实体框架

时间:2019-10-22 15:37:37

标签: c# sql entity-framework sha256

我有以下问题,我需要在Windows窗体中创建一个项目,以咨询由Entity Framework生成的SQL数据库的数据,因此,我试图比较由 WF输入的密码与数据库中的密码相同,问题是 EF 会对密码数据进行加密,因此,如果我必须进行比较,则需要对其进行解密。这是一个假设,没有其他方法可以比较此数据。这是我的代码

public partial class MainWindow : Window
{
    private Models.SecurityController _security;
    public MainWindow()
    {
        InitializeComponent();
        _security = new Models.SecurityController();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var email = EmailInput.Text;
        var pass = PassInput.Password;
        email = email.Replace(" ", "");
        if (email == "" )
        {
            EmailInput.Focus();
            Errorlbl.Content = "Por favor utiliza un mail valido";
        }
        else if (pass == "")
        {
            PassInput.Focus();
            Errorlbl.Content = "Por favor utiliza una contraseña";
        }
        else if (email != null && pass != null)
        {
            using (DBEnt db = new DBEnt())
            {
                var item = db.AspNetUsers.Where(u => u.Email.Equals(email)).FirstOrDefault();

                if (item == null)
                {
                    Errorlbl.Content = "Usuario mail invalido";
                }
                else {
                    Errorlbl.Content = "Usuario valido";
                }

                var query =
                db.AspNetUsers.Where(u => u.Email.Equals(email)).FirstOrDefault();
                var hashedpassword = query.PasswordHash;
                var unhashed = _security.Decrypt(pass, hashedpassword);
            }
        }
    }
}

到目前为止,哈希密码返回menull

所有这些都是 SecurityController

class SecurityController
{
    public string Encrypt(string key, string data)
    {
        string encData = null;
        byte[][] keys = GetHashKeys(key);

        try
        {
            encData = EncryptStringToBytes_Aes(data, keys[0], keys[1]);
        }
        catch (CryptographicException) { }
        catch (ArgumentNullException) { }

        return encData;
    }

    public string Decrypt(string key, string data)
    {
        string decData = null;
        byte[][] keys = GetHashKeys(key);

        try
        {
            decData = DecryptStringFromBytes_Aes(data, keys[0], keys[1]);
        }
        catch (CryptographicException) { }
        catch (ArgumentNullException) { }

        return decData;
    }

    private byte[][] GetHashKeys(string key)
    {
        byte[][] result = new byte[2][];
        Encoding enc = Encoding.UTF8;

        SHA256 sha2 = new SHA256CryptoServiceProvider();

        byte[] rawKey = enc.GetBytes(key);
        byte[] rawIV = enc.GetBytes(key);

        byte[] hashKey = sha2.ComputeHash(rawKey);
        byte[] hashIV = sha2.ComputeHash(rawIV);

        Array.Resize(ref hashIV, 16);

        result[0] = hashKey;
        result[1] = hashIV;

        return result;
    }

    //source: https://msdn.microsoft.com/de-de/library/system.security.cryptography.aes(v=vs.110).aspx
    private static string EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        byte[] encrypted;

        using (AesManaged aesAlg = new AesManaged())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt =
                        new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        return Convert.ToBase64String(encrypted);
    }

    //source: https://msdn.microsoft.com/de-de/library/system.security.cryptography.aes(v=vs.110).aspx
    private static string DecryptStringFromBytes_Aes(string cipherTextString, byte[] Key, byte[] IV)
    {
        byte[] cipherText = Convert.FromBase64String(cipherTextString);

        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        string plaintext = null;

        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt =
                        new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
        }
        return plaintext;
    }
}

也许我变得非常复杂,有人知道我如何做得更好或者我做得好吗?

0 个答案:

没有答案