11590Srgrimes/*
21590Srgrimes * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
31590Srgrimes *
41590Srgrimes * Licensed under the Apache License 2.0 (the "License").  You may not use
51590Srgrimes * this file except in compliance with the License.  You can obtain a copy
61590Srgrimes * in the file LICENSE in the source distribution or at
71590Srgrimes * https://www.openssl.org/source/license.html
81590Srgrimes */
91590Srgrimes
101590Srgrimes#include <stdio.h>
111590Srgrimes#include "internal/cryptlib.h"
121590Srgrimes#include "bn_local.h"
131590Srgrimes
141590Srgrimesint BN_bn2mpi(const BIGNUM *a, unsigned char *d)
151590Srgrimes{
161590Srgrimes    int bits;
171590Srgrimes    int num = 0;
181590Srgrimes    int ext = 0;
191590Srgrimes    long l;
201590Srgrimes
211590Srgrimes    bits = BN_num_bits(a);
221590Srgrimes    num = (bits + 7) / 8;
231590Srgrimes    if (bits > 0) {
241590Srgrimes        ext = ((bits & 0x07) == 0);
251590Srgrimes    }
261590Srgrimes    if (d == NULL)
271590Srgrimes        return (num + 4 + ext);
281590Srgrimes
291590Srgrimes    l = num + ext;
301590Srgrimes    d[0] = (unsigned char)(l >> 24) & 0xff;
311590Srgrimes    d[1] = (unsigned char)(l >> 16) & 0xff;
321590Srgrimes    d[2] = (unsigned char)(l >> 8) & 0xff;
331590Srgrimes    d[3] = (unsigned char)(l) & 0xff;
3455716Sobrien    if (ext)
351590Srgrimes        d[4] = 0;
361590Srgrimes    num = BN_bn2bin(a, &(d[4 + ext]));
371590Srgrimes    if (a->neg)
381590Srgrimes        d[4] |= 0x80;
3955716Sobrien    return (num + 4 + ext);
4055716Sobrien}
41
42BIGNUM *BN_mpi2bn(const unsigned char *d, int n, BIGNUM *ain)
43{
44    long len;
45    int neg = 0;
46    BIGNUM *a = NULL;
47
48    if (n < 4 || (d[0] & 0x80) != 0) {
49        ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH);
50        return NULL;
51    }
52    len = ((long)d[0] << 24) | ((long)d[1] << 16) | ((int)d[2] << 8) | (int)
53        d[3];
54    if ((len + 4) != n) {
55        ERR_raise(ERR_LIB_BN, BN_R_ENCODING_ERROR);
56        return NULL;
57    }
58
59    if (ain == NULL)
60        a = BN_new();
61    else
62        a = ain;
63
64    if (a == NULL)
65        return NULL;
66
67    if (len == 0) {
68        a->neg = 0;
69        a->top = 0;
70        return a;
71    }
72    d += 4;
73    if ((*d) & 0x80)
74        neg = 1;
75    if (BN_bin2bn(d, (int)len, a) == NULL) {
76        if (ain == NULL)
77            BN_free(a);
78        return NULL;
79    }
80    a->neg = neg;
81    if (neg) {
82        BN_clear_bit(a, BN_num_bits(a) - 1);
83    }
84    bn_check_top(a);
85    return a;
86}
87