Ruby-sha和hash到c#

Ruby-sha和hash到c#,c#,ruby,md5,sha1,C#,Ruby,Md5,Sha1,我想把这个翻译成c# 我的代码 private static string GetSHA1HashData(string data) { //create new instance of md5 SHA1 sha1 = SHA1.Create(); //convert the input text to array of bytes byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(data

我想把这个翻译成c#

我的代码

private static string GetSHA1HashData(string data)
{
    //create new instance of md5
    SHA1 sha1 = SHA1.Create();

    //convert the input text to array of bytes
    byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(data));

    //create new instance of StringBuilder to save hashed data
    StringBuilder returnValue = new StringBuilder();
    //loop for each byte and add it to StringBuilder
    for (int i = 0; i < hashData.Length; i++)
    {
        returnValue.Append(hashData[i].ToString());
    }

    // return hexadecimal string
    return returnValue.ToString();
}
public static string CreateMD5Hash(string input)
{
    // Use input string to calculate MD5 hash
    MD5 md5 = System.Security.Cryptography.MD5.Create();
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hashBytes = md5.ComputeHash(inputBytes);

    // Convert the byte array to hexadecimal string
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < hashBytes.Length; i++)
    {
        sb.Append(hashBytes[i].ToString("X2"));
        // To force the hex string to lower-case letters instead of
        // upper-case, use he following line instead:
        // sb.Append(hashBytes[i].ToString("x2")); 
    }
    return sb.ToString();
}

但是我不能正确理解,任何想法都是错误的。问题是.NET默认使用UTF-16,而Ruby将使用其他东西(通常是UTF-8,但它也可能尊重数据库或web源设置的编码)

我想你只需要修改一行:

//convert the input text to array of bytes
byte[] hashData = sha1.ComputeHash(Encoding.ASCII.GetBytes(data));

根据Ruby版本接受的密码范围,您可能需要UTF-8甚至其他编码。但是,ASCII编码至少应该从您的示例数据中证明这个答案的正确性。

问题是.NET默认使用UTF-16,而Ruby将使用其他东西(通常是UTF-8,但也可能尊重数据库或web源设置的编码)

我想你只需要修改一行:

//convert the input text to array of bytes
byte[] hashData = sha1.ComputeHash(Encoding.ASCII.GetBytes(data));

根据Ruby版本接受的密码范围,您可能需要UTF-8甚至其他编码。但是,ASCII编码至少应该从您的示例数据中证明此答案的正确性。

SHA1/MD5密码?不,不,不。。。很抱歉不,问题是我有从RB代码生成的哈希。我有密码和nonce,但在使用c#时无法获得相同的哈希值。请在此处输入您的一个“不正确”尝试(编辑到问题中)。这可能很接近,并且会减少帮助您所需的工作量。我同意,尽管这里明显的手卷“安全”是残暴的。您可能可以撤销密码,只需稍加努力就可以重新存储它们。问题是我忘记了SHA1-tostring()方法中的“x2”。SHA1/MD5密码?不,不,不。。。很抱歉不,问题是我有从RB代码生成的哈希。我有密码和nonce,但在使用c#时无法获得相同的哈希值。请在此处输入您的一个“不正确”尝试(编辑到问题中)。这可能很接近,并且会减少帮助您所需的工作量。我同意,尽管这里明显的手卷“安全”是残暴的。您可能可以撤销密码,只需稍加努力即可重新存储它们。问题是我忘记了SHA1 tostring()方法中的“x2”。如上所述,sha中的tostring()方法中需要x2。Thanks@hippie:这是对这个答案的补充还是替代?(如果是另外的,我没有发现它,但可以作为注释添加到这个答案中,以帮助下一个人。)如上所述,在sha中的tostring()方法中需要x2。Thanks@hippie:这是对这个答案的补充还是替代?(如果是另外一个问题,我没有发现它,但可以作为注释添加到这个答案中,以帮助下一个人。)
//convert the input text to array of bytes
byte[] hashData = sha1.ComputeHash(Encoding.ASCII.GetBytes(data));