Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SHA256 fixes #1

Merged
merged 2 commits into from
Oct 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 12 additions & 18 deletions src/lib/sha256.c
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
#define ROTL(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
#define ROTR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))

#define IS_ALIGNED(p, a) (!((uintptr_t)(p) & (uintptr_t)((a) - 1)))

#define Ch(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
#define Maj(x, y, z) (((x) & ((y) | (z))) | ((y) & (z)))
#define SIGMA0(x) (ROTR((x), 2) ^ ROTR((x), 13) ^ ROTR((x), 22))
Expand Down Expand Up @@ -176,16 +178,6 @@ void ecdsa_sha256_init(ecdsa_sha256_context_t *sc)
sc->bufferLength = 0L;
}

static void burnStack(int size)
{
char buf[128];

memset(buf, 0, sizeof(buf));
size -= sizeof(buf);
if (size > 0)
burnStack(size);
}

static void SHA256Guts(ecdsa_sha256_context_t *sc, const uint32_t *cbuf)
{
uint32_t buf[64];
Expand Down Expand Up @@ -388,11 +380,12 @@ static void SHA256Guts(ecdsa_sha256_context_t *sc, const uint32_t *cbuf)
sc->hash[7] += h;
}



void ecdsa_sha256_update(ecdsa_sha256_context_t *sc, const void *data, size_t len)
{
uint32_t bufferBytesLeft;
uint32_t bytesToCopy;
int needBurn = 0;

if (sc->bufferLength) {
bufferBytesLeft = 64L - sc->bufferLength;
Expand All @@ -411,16 +404,21 @@ void ecdsa_sha256_update(ecdsa_sha256_context_t *sc, const void *data, size_t le

if (sc->bufferLength == 64L) {
SHA256Guts(sc, sc->buffer.words);
needBurn = 1;
sc->bufferLength = 0L;
}
}

while (len > 63L) {
uint32_t words[64 / sizeof(uint32_t)];

sc->totalLength += 512L;

SHA256Guts(sc, data);
needBurn = 1;
if (IS_ALIGNED(data, sizeof(uint32_t))) {
SHA256Guts(sc, data);
} else {
memcpy(words, data, sizeof(words));
SHA256Guts(sc, words);
}
neocturne marked this conversation as resolved.
Show resolved Hide resolved

data = ((uint8_t *) data) + 64L;
len -= 64L;
Expand All @@ -433,10 +431,6 @@ void ecdsa_sha256_update(ecdsa_sha256_context_t *sc, const void *data, size_t le

sc->bufferLength += len;
}

if (needBurn)
burnStack(sizeof(uint32_t[74]) + sizeof(uint32_t *[6]) +
sizeof(int));
}

void ecdsa_sha256_final(ecdsa_sha256_context_t *sc, uint8_t hash[ECDSA_SHA256_HASH_SIZE])
Expand Down