【问题标题】:C# SQLite encryption hashing SHA1C# SQLite 加密散列 SHA1
【发布时间】:2015-05-25 13:43:17
【问题描述】:

我有一个 C# 应用程序和一个 SQLite 数据库。在数据库中,我有一个包含几列的表。在其中一列中,我有一个使用查询中的 SHA1 加密的值。但我需要像这样在我的 C# 应用程序中使用它:

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

我需要选择字符串值,以记录到应用程序。我收到错误:no such function sha1

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

【问题讨论】:

  • 使用Select * from accounts where (username=@username and password=@password);并绑定@password的哈希值
  • 在大多数情况下,使用像SHA1这样的哈希函数存储密码被认为是不安全的,请了解key derivation function,它被认为对密码存储更安全。
  • 你的意思是这样的:cmd.Parameters.AddWithValue("sha1(@password)", password);cmd.Parameters.AddWithValue(sha1("@password"), password); ??
  • 感谢 dvhh 的建议!
  • 在查询中使用Select * from accounts where (username=@username and password=@password); 作为查询,而在查询中没有sha1cmd.Parameters.AddWithValue(@password",sha1(password)");,这意味着您必须在c# 代码中应用sha1,而不是在SQL 中。

标签: c# sqlite encryption hash sha1


【解决方案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#实现这些函数。

【讨论】:

  • 一个问题,我只是出于好奇而尝试将 sha1 与 stirng sha1(string input) {} 一起使用,但我收到错误:sha1(string) is a method, which is not valid in the given context。为什么?
  • 对不起,名称冲突,我已经修改了我的答案
  • 是的,代码没问题,但它没有从表中识别出我的值。我认为这是问题所在:cmd.Parameters.AddWithValue("@password", sha1(password)); 我收到:Incorrect username or password
猜你喜欢
  • 2013-04-24
  • 2011-06-08
  • 1970-01-01
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 2011-02-18
  • 2011-03-03
  • 2014-03-26
相关资源
最近更新 更多