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);
52 ctx->k = mpi_get_nlimbs(m);
53 tmp = mpi_alloc(ctx->k + 1);
55 /* Barrett precalculation: y = floor(b^(2k) / m). */
57 mpi_lshift_limbs(tmp, 2 * ctx->k);
58 mpi_fdiv_q(tmp, tmp, m);
61 ctx->r1 = mpi_alloc(2 * ctx->k + 1);
62 ctx->r2 = mpi_alloc(2 * ctx->k + 1);
67 void mpi_barrett_free(mpi_barrett_t ctx)
84 * Using Barrett reduction. Before using this function
85 * _gcry_mpi_barrett_init must have been called to do the
86 * precalculations. CTX is the context created by this precalculation
87 * and also conveys M. If the Barret reduction could no be done a
88 * straightforward reduction method is used.
90 * We assume that these conditions are met:
91 * Input: x =(x_2k-1 ...x_0)_b
92 * m =(m_k-1 ....m_0)_b with m_k-1 != 0
95 void mpi_mod_barrett(MPI r, MPI x, mpi_barrett_t ctx)
105 if (mpi_get_nlimbs(x) > 2*k) {
113 /* 1. q1 = floor( x / b^k-1)
115 * q3 = floor( q2 / b^k+1 )
116 * Actually, we don't need qx, we can work direct on r2
119 mpi_rshift_limbs(r2, k-1);
121 mpi_rshift_limbs(r2, k+1);
123 /* 2. r1 = x mod b^k+1
124 * r2 = q3 * m mod b^k+1
126 * 3. if r < 0 then r = r + b^k+1
129 if (r1->nlimbs > k+1) /* Quick modulo operation. */
132 if (r2->nlimbs > k+1) /* Quick modulo operation. */
136 if (mpi_has_sign(r)) {
138 ctx->r3 = mpi_alloc(k + 2);
139 mpi_set_ui(ctx->r3, 1);
140 mpi_lshift_limbs(ctx->r3, k + 1);
142 mpi_add(r, r, ctx->r3);
145 /* 4. while r >= m do r = r - m */
146 while (mpi_cmp(r, m) >= 0)
153 void mpi_mul_barrett(MPI w, MPI u, MPI v, mpi_barrett_t ctx)
156 mpi_mod_barrett(w, w, ctx);