我目前正在开发一个 Visual Studio C# Windows 窗体项目。但是,我对 SHA256 + salted 的工作方式感到困惑。我在网上找到了一些示例,但无法理解如何调用此函数。
我想在连接到数据库(Microsoft Access 2010)的登录表单中调用此函数。
- 如何通过单击按钮并从 中读取密码来调用此功能
Textbox
? - 如何在
Messagebox.Show
方法中显示哈希值?(出于我的测试目的) 是否可以比较两个文本(散列和加盐)并给出肯定的结果?
public static string sha256encrypt(string phrase, string UserName) { string salt = CreateSalt(UserName); string saltAndPwd = String.Concat(phrase, salt); UTF8Encoding encoder = new UTF8Encoding(); SHA256Managed sha256hasher = new SHA256Managed(); byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(saltAndPwd)); string hashedPwd = String.Concat(byteArrayToString(hashedDataBytes), salt); return hashedPwd; } public static string byteArrayToString(byte[] inputArray) { StringBuilder output = new StringBuilder(""); for (int i = 0; i < inputArray.Length; i++) { output.Append(inputArray[i].ToString("X2")); } return output.ToString(); } private static string CreateSalt(string UserName) { string username = UserName; byte[] userBytes; string salt; userBytes = ASCIIEncoding.ASCII.GetBytes(username); long XORED = 0x00; foreach (int x in userBytes) XORED = XORED ^ x; Random rand = new Random(Convert.ToInt32(XORED)); salt = rand.Next().ToString(); salt += rand.Next().ToString(); salt += rand.Next().ToString(); salt += rand.Next().ToString(); return salt; }
如何使用盐创建 SHA256 哈希?
shavalue = (sha256encrypt("password", "username");
saltedandhashtext = CreateSalt(shavalue);