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
11 #include "internal/cryptlib.h"
14 int BN_lshift1(BIGNUM *r, const BIGNUM *a)
16 register BN_ULONG *ap, *rp, t, c;
24 if (bn_wexpand(r, a->top + 1) == NULL)
28 if (bn_wexpand(r, a->top + 1) == NULL)
34 for (i = 0; i < a->top; i++) {
36 *(rp++) = ((t << 1) | c) & BN_MASK2;
37 c = t >> (BN_BITS2 - 1);
45 int BN_rshift1(BIGNUM *r, const BIGNUM *a)
47 BN_ULONG *ap, *rp, t, c;
60 if (bn_wexpand(r, i) == NULL)
68 c = t << (BN_BITS2 - 1);
72 rp[i] = ((t >> 1) & BN_MASK2) | c;
73 c = t << (BN_BITS2 - 1);
76 r->neg = 0; /* don't allow negative zero */
81 int BN_lshift(BIGNUM *r, const BIGNUM *a, int n)
86 BNerr(BN_F_BN_LSHIFT, BN_R_INVALID_SHIFT);
90 ret = bn_lshift_fixed_top(r, a, n);
99 * In respect to shift factor the execution time is invariant of
100 * |n % BN_BITS2|, but not |n / BN_BITS2|. Or in other words pre-condition
101 * for constant-time-ness is |n < BN_BITS2| or |n / BN_BITS2| being
104 int bn_lshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n)
109 BN_ULONG l, m, rmask = 0;
117 if (bn_wexpand(r, a->top + nw + 1) == NULL)
121 lb = (unsigned int)n % BN_BITS2;
123 rb %= BN_BITS2; /* say no to undefined behaviour */
124 rmask = (BN_ULONG)0 - rb; /* rmask = 0 - (rb != 0) */
129 t[a->top] = (l >> rb) & rmask;
130 for (i = a->top - 1; i > 0; i--) {
133 t[i] = (m | ((l >> rb) & rmask)) & BN_MASK2;
135 t[0] = (l << lb) & BN_MASK2;
137 /* shouldn't happen, but formally required */
141 memset(r->d, 0, sizeof(*t) * nw);
144 r->top = a->top + nw + 1;
145 r->flags |= BN_FLG_FIXED_TOP;
150 int BN_rshift(BIGNUM *r, const BIGNUM *a, int n)
155 BNerr(BN_F_BN_RSHIFT, BN_R_INVALID_SHIFT);
159 ret = bn_rshift_fixed_top(r, a, n);
168 * In respect to shift factor the execution time is invariant of
169 * |n % BN_BITS2|, but not |n / BN_BITS2|. Or in other words pre-condition
170 * for constant-time-ness for sufficiently[!] zero-padded inputs is
171 * |n < BN_BITS2| or |n / BN_BITS2| being non-secret.
173 int bn_rshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n)
187 /* shouldn't happen, but formally required */
192 rb = (unsigned int)n % BN_BITS2;
194 lb %= BN_BITS2; /* say no to undefined behaviour */
195 mask = (BN_ULONG)0 - lb; /* mask = 0 - (lb != 0) */
198 if (r != a && bn_wexpand(r, top) == NULL)
204 for (i = 0; i < top - 1; i++) {
206 t[i] = (l >> rb) | ((m << lb) & mask);
213 r->flags |= BN_FLG_FIXED_TOP;