2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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"
14 int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
16 int a_neg = a->neg, ret;
28 /* only one is negative */
37 /* we are now a - b */
39 if (BN_ucmp(a, b) < 0) {
40 if (!BN_usub(r, b, a))
44 if (!BN_usub(r, a, b))
51 ret = BN_uadd(r, a, b);
57 /* unsigned add of b to a */
58 int BN_uadd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
61 const BN_ULONG *ap, *bp;
62 BN_ULONG *rp, carry, t1, t2;
67 if (a->top < b->top) {
78 if (bn_wexpand(r, max + 1) == NULL)
87 carry = bn_add_words(rp, ap, bp, min);
94 t2 = (t1 + carry) & BN_MASK2;
106 /* unsigned subtraction of b from a, a must be larger than b. */
107 int BN_usub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
110 BN_ULONG t1, t2, borrow, *rp;
111 const BN_ULONG *ap, *bp;
120 if (dif < 0) { /* hmm... should not be happening */
121 BNerr(BN_F_BN_USUB, BN_R_ARG2_LT_ARG3);
125 if (bn_wexpand(r, max) == NULL)
132 borrow = bn_sub_words(rp, ap, bp, min);
139 t2 = (t1 - borrow) & BN_MASK2;
150 int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
153 int add = 0, neg = 0;
183 if (!BN_uadd(r, a, b))
189 /* We are actually doing a - b :-) */
191 max = (a->top > b->top) ? a->top : b->top;
192 if (bn_wexpand(r, max) == NULL)
194 if (BN_ucmp(a, b) < 0) {
195 if (!BN_usub(r, b, a))
199 if (!BN_usub(r, a, b))