无法将varchar类型转换为byte []

时间:2014-02-17 07:53:23

标签: c# type-conversion

我想将明文密码与crypted_pa​​ssword和保存在数据库中的salt进行比较,因为我有一个名为passwordisvalid()的函数,它有3个参数(string,byte [],byte []) plaintextpassword的字符串,byte []表示保存的cryptedpassword和保存的salt和 crypted_pa​​ssword和salt属性是varchar类型在数据库中 所以我的问题是我如何将varchar数据类型转换为byte [],以便我可以将它传递给passwordisvalid()?

public static bool IsPasswordValid(string passwordPlainText, byte[] savedSaltBytes, byte[] savedHashBytes)
{
    byte[] array1 =GenerateSaltedHash(passwordPlainText,savedSaltBytes);
    byte[] array2 = savedHashBytes;

    if (array1.Length != array2.Length)
        return false;

    for (int i = 0; i < array1.Length; i++)
    {
        if (array1[i] != array2[i])
            return false;
    }

    return true;
} 

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

数据库中的varchar元素应映射回字符串。所以问题就变成了,我怎样才能得到一个字符串转换为字节数组。

看一下这篇文章:How do I get a consistent byte representation of strings in C# without manually specifying an encoding?它解释了如何在不使用utf编码的情况下转换为byte []。