2 * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include "internal/cryptlib.h"
13 /* signed add of b to a. */
14 int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
16 int ret, r_neg, cmp_res;
21 if (a->neg == b->neg) {
23 ret = BN_uadd(r, a, b);
25 cmp_res = BN_ucmp(a, b);
28 ret = BN_usub(r, a, b);
29 } else if (cmp_res < 0) {
31 ret = BN_usub(r, b, a);
44 /* signed sub of b from a. */
45 int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
47 int ret, r_neg, cmp_res;
52 if (a->neg != b->neg) {
54 ret = BN_uadd(r, a, b);
56 cmp_res = BN_ucmp(a, b);
59 ret = BN_usub(r, a, b);
60 } else if (cmp_res < 0) {
62 ret = BN_usub(r, b, a);
75 /* unsigned add of b to a, r can be equal to a or b. */
76 int BN_uadd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
79 const BN_ULONG *ap, *bp;
80 BN_ULONG *rp, carry, t1, t2;
85 if (a->top < b->top) {
96 if (bn_wexpand(r, max + 1) == NULL)
105 carry = bn_add_words(rp, ap, bp, min);
112 t2 = (t1 + carry) & BN_MASK2;
124 /* unsigned subtraction of b from a, a must be larger than b. */
125 int BN_usub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
128 BN_ULONG t1, t2, borrow, *rp;
129 const BN_ULONG *ap, *bp;
138 if (dif < 0) { /* hmm... should not be happening */
139 BNerr(BN_F_BN_USUB, BN_R_ARG2_LT_ARG3);
143 if (bn_wexpand(r, max) == NULL)
150 borrow = bn_sub_words(rp, ap, bp, min);
157 t2 = (t1 - borrow) & BN_MASK2;
162 while (max && *--rp == 0)