C#SQLite加密哈希SHA1

时间:2015-03-22 14:19:29

标签: c# sqlite encryption hash sha1

我在C#中有一个应用程序,在SQLite中有一个数据库。在数据库中,我有一个包含几列的表。在其中一列中,我有一个使用SHA1从查询加密的值。但我需要在我的C#应用​​程序中使用它,如下所示:

cmd.CommandText = "Select * from accounts where (username=@username and password=sha1(@password));";

我需要选择字符串值,以便登录到app。我收到错误:no such function sha1

来自其他帖子,例如:This one,我知道我必须使用sha1创建另一个哈希函数?但我真的不明白如何做到这一点。任何人都可以帮助我吗?对不起,如果它重复但我没有找到指定的答案。

1 个答案:

答案 0 :(得分:1)

由于SQLite默认情况下未实现任何sha1功能,您必须将密码哈希从 SQL 查询移至您的代码。

您的查询应该是:

cmd.CommandText = "Select * from accounts where (username=@username and password=@password);";

你应该传递这样的密码:

cmd.Parameters.AddWithValue("@password", sha1(password));

您应该实现自己的sha1功能

using System.Security.Cryptography;

...

string sha1(string input) {
    byte[] byteArray = Encoding.UTF8.GetBytes(input);
    string result="";
    using (HashAlgorithm hash = SHA1.Create()) {
        result=Convert.ToBase64String(hash.ComputeHash(byteArray));
    }
    return result;
}

重要

使用散列函数被认为非常不安全用于存储密码,您应该考虑学习Key Derivation function,阅读维基百科页面将引导您进行此类函数的C#实现。