]>
git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/bn/bn_add.c
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
)
17 int a_neg
= a
->neg
, ret
;
29 /* only one is negative */
36 /* we are now a - b */
38 if (BN_ucmp(a
, b
) < 0) {
39 if (!BN_usub(r
, b
, a
))
43 if (!BN_usub(r
, a
, b
))
50 ret
= BN_uadd(r
, a
, b
);
56 /* unsigned add of b to a */
57 int BN_uadd(BIGNUM
*r
, const BIGNUM
*a
, const BIGNUM
*b
)
60 const BN_ULONG
*ap
, *bp
;
61 BN_ULONG
*rp
, carry
, t1
, t2
;
67 if (a
->top
< b
->top
) {
76 if (bn_wexpand(r
, max
+ 1) == NULL
)
85 carry
= bn_add_words(rp
, ap
, bp
, min
);
94 t2
= (t1
+ 1) & BN_MASK2
;
102 /* carry != 0 => dif == 0 */
109 /* copy remaining words if ap != rp */
116 /* unsigned subtraction of b from a, a must be larger than b. */
117 int BN_usub(BIGNUM
*r
, const BIGNUM
*a
, const BIGNUM
*b
)
120 register BN_ULONG t1
, t2
, *rp
;
121 register const BN_ULONG
*ap
, *bp
;
131 if (dif
< 0) { /* hmm... should not be happening */
132 BNerr(BN_F_BN_USUB
, BN_R_ARG2_LT_ARG3
);
136 if (bn_wexpand(r
, max
) == NULL
)
145 for (i
= min
; i
!= 0; i
--) {
150 t1
= (t1
- t2
- 1) & BN_MASK2
;
153 t1
= (t1
- t2
) & BN_MASK2
;
155 *(rp
++) = t1
& BN_MASK2
;
158 carry
= bn_sub_words(rp
, ap
, bp
, min
);
163 if (carry
) { /* subtracted */
170 t2
= (t1
- 1) & BN_MASK2
;
177 memcpy(rp
, ap
, sizeof(*rp
) * dif
);
185 int BN_sub(BIGNUM
*r
, const BIGNUM
*a
, const BIGNUM
*b
)
188 int add
= 0, neg
= 0;
217 if (!BN_uadd(r
, a
, b
))
223 /* We are actually doing a - b :-) */
225 max
= (a
->top
> b
->top
) ? a
->top
: b
->top
;
226 if (bn_wexpand(r
, max
) == NULL
)
228 if (BN_ucmp(a
, b
) < 0) {
229 if (!BN_usub(r
, b
, a
))
233 if (!BN_usub(r
, a
, b
))