Skip to content

Constant-time comparison: which approach is best? #20

@sdrapkin

Description

@sdrapkin

Which approach is best?

AndEq approach, used by internal and public Microsoft helpers:

static bool AndEq(byte[] a, byte[] b)
{
    bool f = a.Length == b.Length;
    for (int i = 0; i < a.Length && i < b.Length; ++i)
    {
        f &= a[i] == b[i];
    }
    return f;
}

OrXor approach (classic):

static bool OrXor(byte[] a, byte[] b)
{
    int x = a.Length ^ b.Length;
    for (int i = 0; i < a.Length && i < b.Length; ++i)
    {
        x |= a[i] ^ b[i];
    }
    return x == 0;
}

OrSub approach, recently advocated by Microsoft as the "better way" (no supporting evidence):

static bool OrSub(byte[] a, byte[] b)
{
    int x = a.Length ^ b.Length;
    for (int i = 0; i < a.Length && i < b.Length; ++i)
    {
        x |= a[i] - b[i];
    }
    return x == 0;
}

Some other approach?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions