1 /* mpi-mod.c - Modular reduction
2 * Copyright (C) 1998, 1999, 2001, 2002, 2003,
3 * 2007 Free Software Foundation, Inc.
5 * This file is part of Libgcrypt.
9 #include "mpi-internal.h"
12 /* Context used with Barrett reduction. */
13 struct barrett_ctx_s {
14 MPI m; /* The modulus - may not be modified. */
15 int m_copied; /* If true, M needs to be released. */
18 MPI r1; /* Helper MPI. */
19 MPI r2; /* Helper MPI. */
20 MPI r3; /* Helper MPI allocated on demand. */
25 void mpi_mod(MPI rem, MPI dividend, MPI divisor)
27 mpi_fdiv_r(rem, dividend, divisor);
30 /* This function returns a new context for Barrett based operations on
31 * the modulus M. This context needs to be released using
32 * _gcry_mpi_barrett_free. If COPY is true M will be transferred to
33 * the context and the user may change M. If COPY is false, M may not
34 * be changed until gcry_mpi_barrett_free has been called.
36 mpi_barrett_t mpi_barrett_init(MPI m, int copy)
42 ctx = kcalloc(1, sizeof(*ctx), GFP_KERNEL);
50 ctx->k = mpi_get_nlimbs(m);
51 tmp = mpi_alloc(ctx->k + 1);
53 /* Barrett precalculation: y = floor(b^(2k) / m). */
55 mpi_lshift_limbs(tmp, 2 * ctx->k);
56 mpi_fdiv_q(tmp, tmp, m);
59 ctx->r1 = mpi_alloc(2 * ctx->k + 1);
60 ctx->r2 = mpi_alloc(2 * ctx->k + 1);
65 void mpi_barrett_free(mpi_barrett_t ctx)
82 * Using Barrett reduction. Before using this function
83 * _gcry_mpi_barrett_init must have been called to do the
84 * precalculations. CTX is the context created by this precalculation
85 * and also conveys M. If the Barret reduction could no be done a
86 * straightforward reduction method is used.
88 * We assume that these conditions are met:
89 * Input: x =(x_2k-1 ...x_0)_b
90 * m =(m_k-1 ....m_0)_b with m_k-1 != 0
93 void mpi_mod_barrett(MPI r, MPI x, mpi_barrett_t ctx)
103 if (mpi_get_nlimbs(x) > 2*k) {
111 /* 1. q1 = floor( x / b^k-1)
113 * q3 = floor( q2 / b^k+1 )
114 * Actually, we don't need qx, we can work direct on r2
117 mpi_rshift_limbs(r2, k-1);
119 mpi_rshift_limbs(r2, k+1);
121 /* 2. r1 = x mod b^k+1
122 * r2 = q3 * m mod b^k+1
124 * 3. if r < 0 then r = r + b^k+1
127 if (r1->nlimbs > k+1) /* Quick modulo operation. */
130 if (r2->nlimbs > k+1) /* Quick modulo operation. */
134 if (mpi_has_sign(r)) {
136 ctx->r3 = mpi_alloc(k + 2);
137 mpi_set_ui(ctx->r3, 1);
138 mpi_lshift_limbs(ctx->r3, k + 1);
140 mpi_add(r, r, ctx->r3);
143 /* 4. while r >= m do r = r - m */
144 while (mpi_cmp(r, m) >= 0)
151 void mpi_mul_barrett(MPI w, MPI u, MPI v, mpi_barrett_t ctx)
154 mpi_mod_barrett(w, w, ctx);