#include <openssl/bn.h>
#include <assert.h>
#include <limits.h>
#include "internal.h"
BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret) {
size_t num_words;
unsigned m;
BN_ULONG word = 0;
BIGNUM *bn = NULL;
if (ret == NULL) {
ret = bn = BN_new();
}
if (ret == NULL) {
return NULL;
}
if (len == 0) {
ret->width = 0;
return ret;
}
num_words = ((len - 1) / BN_BYTES) + 1;
m = (len - 1) % BN_BYTES;
if (!bn_wexpand(ret, num_words)) {
if (bn) {
BN_free(bn);
}
return NULL;
}
assert(num_words <= INT_MAX);
ret->width = (int)num_words;
ret->neg = 0;
while (len--) {
word = (word << 8) | *(in++);
if (m-- == 0) {
ret->d[--num_words] = word;
word = 0;
m = BN_BYTES - 1;
}
}
return ret;
}
BIGNUM *BN_le2bn(const uint8_t *in, size_t len, BIGNUM *ret) {
BIGNUM *bn = NULL;
if (ret == NULL) {
bn = BN_new();
ret = bn;
}
if (ret == NULL) {
return NULL;
}
if (len == 0) {
ret->width = 0;
ret->neg = 0;
return ret;
}
size_t num_words = ((len - 1) / BN_BYTES) + 1;
if (!bn_wexpand(ret, num_words)) {
BN_free(bn);
return NULL;
}
ret->width = (int)num_words;
ret->d[num_words - 1] = 0;
OPENSSL_memcpy(ret->d, in, len);
return ret;
}
size_t BN_bn2bin(const BIGNUM *in, uint8_t *out) {
size_t n, i;
BN_ULONG l;
n = i = BN_num_bytes(in);
while (i--) {
l = in->d[i / BN_BYTES];
*(out++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff;
}
return n;
}
static int fits_in_bytes(const uint8_t *bytes, size_t num_bytes, size_t len) {
uint8_t mask = 0;
for (size_t i = len; i < num_bytes; i++) {
mask |= bytes[i];
}
return mask == 0;
}
int BN_bn2le_padded(uint8_t *out, size_t len, const BIGNUM *in) {
const uint8_t *bytes = (const uint8_t *)in->d;
size_t num_bytes = in->width * BN_BYTES;
if (len < num_bytes) {
if (!fits_in_bytes(bytes, num_bytes, len)) {
return 0;
}
num_bytes = len;
}
OPENSSL_memcpy(out, bytes, num_bytes);
OPENSSL_memset(out + num_bytes, 0, len - num_bytes);
return 1;
}
int BN_bn2bin_padded(uint8_t *out, size_t len, const BIGNUM *in) {
const uint8_t *bytes = (const uint8_t *)in->d;
size_t num_bytes = in->width * BN_BYTES;
if (len < num_bytes) {
if (!fits_in_bytes(bytes, num_bytes, len)) {
return 0;
}
num_bytes = len;
}
for (size_t i = 0; i < num_bytes; i++) {
out[len - i - 1] = bytes[i];
}
OPENSSL_memset(out, 0, len - num_bytes);
return 1;
}
BN_ULONG BN_get_word(const BIGNUM *bn) {
switch (bn_minimal_width(bn)) {
case 0:
return 0;
case 1:
return bn->d[0];
default:
return BN_MASK2;
}
}
int BN_get_u64(const BIGNUM *bn, uint64_t *out) {
switch (bn_minimal_width(bn)) {
case 0:
*out = 0;
return 1;
case 1:
*out = bn->d[0];
return 1;
#if defined(OPENSSL_32_BIT)
case 2:
*out = (uint64_t) bn->d[0] | (((uint64_t) bn->d[1]) << 32);
return 1;
#endif
default:
return 0;
}
}