Binary manipulation

Viewed 31

I am trying to code up the SHA-256 algorithm as shown by https://blog.boot.dev/cryptography/how-sha-2-works-step-by-step-sha-256/. From what I can tell, my code is perfect up until this algorithm:

for (int i = 16; i < 64; i++)
{
    s0 = s1 = "";

    right7 = rotate(w[i - 15], 7);
    right18 = rotate(w[i - 15], 18);
    right3 = "000" + w[i - 15].Remove(29);
    s0 = xor(xor(right7, right18), right3);

    right17 = rotate(w[i - 2], 17);
    right19 = rotate(w[i - 2], 19);
    right10 = "0000000000" + w[i - 2].Remove(22);

    s1 = xor(xor(right17, right19), right10);
    w[i] = add(add(add(s0, s1), w[i - 16]), w[i-7]);
}

Here are the sub-routines for add, rotate and xor:

static string rotate(string input, int amount)
{
    return input.Substring(32-amount) + input.Remove(32-amount);
}

static string add(string input1, string input2)
{
    string output = "";
    Int64 one = Convert.ToInt64(input1, 2);
    Int64 two = Convert.ToInt64(input2, 2);
    Int64 total = one + two;
    if (total > (Math.Pow(2, 32)))
    {
        total -= Convert.ToInt64(Math.Pow(2, 32));
    } 
    output = Convert.ToString(total, 2);
    if (output.Length < 32)
    {
        output = new string('0', 32 - output.Length) + output;
    }
    return output;
}

static string xor(string input1, string input2)
{
    int total;
    string output = "";
    for (int i = 0; i < 32; i++)
    {
        total = Convert.ToInt32(Convert.ToString(input1[i])) + Convert.ToInt32(Convert.ToString(input2[i]));
        
        if (total == 1)
        {
            output += '1';
        }
        else
        {
            output += '0';
        }
    }
    return output;
}

The first iteration of I works, but then the second one doesn't by a couple of binary digits, and past the number 22, it's completely wrong. Any ideas or guidance would be greatly appreciated

0 Answers
Related