c,python: Use little-endina byte order for bigint arithmetics

This better matches what one would expect from the hex or base64
(upcoming) formats.
This commit is contained in:
2021-11-15 01:13:17 +01:00
parent cc473f4c24
commit bcae51ead9
7 changed files with 51 additions and 56 deletions

View File

@ -18,6 +18,8 @@
#include <openssl/sha.h>
#include "bhash.h"
/* List of vowels */
#define PHOGEN_VOWELS "aeiou"
@ -78,11 +80,11 @@ struct
char *output;
} phogen_test_table[] =
{
{ "passgeny", "herang xiasem zitend qibele" },
{ "phonetic", "lineum foneum zybale mangur" },
{ "generator", "latole elitab ackina exprou" },
{ "password", "nulize nomere fonici crednt" },
{ "duck", "catabb rompor cricin prunsi" },
{ "passgeny", "vatome iddeda pashis artarc" },
{ "phonetic", "joredl qibini kninet ouslis" },
{ "generator", "vormul zilyth disedl chryso" },
{ "password", "wompot ficara uplort lancon" },
{ "duck", "inerea iricin ovusia irrisi" },
};
const char phogen_python_header[] =
@ -452,38 +454,11 @@ void phogen_rstrip(char *str, char *what)
}
}
/*
* Take the buffer in `bigin` and treat is as a big-endian big number.
* Perform a division using the 32-bit divisor in `base` and return the
* 32-bit modulo.
*/
uint32_t bigint_mod32(void *bigint, size_t bigintsz, uint32_t base)
{
uint32_t *pi;
uint64_t n;
uint32_t mod = 0;
for (pi = (uint32_t *)bigint;
pi < (uint32_t *)(bigint + bigintsz);
pi++)
{
n = mod;
n <<= sizeof(uint32_t) * 8;
n |= htonl(*pi);
*pi = ntohl(n / base);
mod = n % base;
}
return mod;
}
/*
* Take input buffer `in` and generate its phonetic representation
* and store it to out.
*/
void phogen(char *out, size_t outsz, void *in, size_t insz)
void phogen(char *out, size_t outsz, bhash_t *bh)
{
int ii;
@ -502,7 +477,7 @@ void phogen(char *out, size_t outsz, void *in, size_t insz)
{
if (phogen_freq_list[ni][nsize].fe_letter == '\0') break;
}
nsel = bigint_mod32(in, insz, nsize);
nsel = bhash_mod32(bh, nsize);
out[ii] = phogen_freq_list[ni][nsel].fe_letter;
@ -523,6 +498,7 @@ bool phogen_test(void)
SHA256_CTX sha256_ctx;
int ii;
int ij;
bhash_t bh;
bool retval = true;
@ -532,17 +508,21 @@ bool phogen_test(void)
SHA256_Update(&sha256_ctx, phogen_test_table[ii].input, strlen(phogen_test_table[ii].input));
SHA256_Final(sha256, &sha256_ctx);
bhash_init(&bh, sha256, sizeof(sha256));
/* 4 words, each 6 characters long and 1 more character for spaces */
char buf[(6 + 1) * 4];
char *pbuf = buf;
for (ij = 0; ij < 4; ij++)
{
phogen(pbuf, 7, sha256, sizeof(sha256));
phogen(pbuf, 7, &bh);
pbuf += strlen(pbuf);
*pbuf++ = ' ';
}
*(--pbuf) = '\0';
bhash_fini(&bh);
if (strcmp(buf, phogen_test_table[ii].output) != 0)
{
fprintf(stderr, "Error, test failed: %s != %s\n", buf, phogen_test_table[ii].output);