static gcry_err_code_t elg_sign (int algo, gcry_mpi_t *resarr, gcry_mpi_t data, gcry_mpi_t *skey, int flags, int hashalgo) { gcry_err_code_t err = GPG_ERR_NO_ERROR; ELG_secret_key sk; (void)algo; (void)flags; (void)hashalgo; if (mpi_is_opaque (data)) return GPG_ERR_INV_DATA; if ((! data) || (! skey[0]) || (! skey[1]) || (! skey[2]) || (! skey[3])) err = GPG_ERR_BAD_MPI; else { sk.p = skey[0]; sk.g = skey[1]; sk.y = skey[2]; sk.x = skey[3]; resarr[0] = mpi_alloc (mpi_get_nlimbs (sk.p)); resarr[1] = mpi_alloc (mpi_get_nlimbs (sk.p)); sign (resarr[0], resarr[1], data, &sk); } return err; }
/**************** * Returns true if the signature composed of A and B is valid. */ static int verify(gcry_mpi_t a, gcry_mpi_t b, gcry_mpi_t input, ELG_public_key *pkey ) { int rc; gcry_mpi_t t1; gcry_mpi_t t2; gcry_mpi_t base[4]; gcry_mpi_t ex[4]; if( !(mpi_cmp_ui( a, 0 ) > 0 && mpi_cmp( a, pkey->p ) < 0) ) return 0; /* assertion 0 < a < p failed */ t1 = mpi_alloc( mpi_get_nlimbs(a) ); t2 = mpi_alloc( mpi_get_nlimbs(a) ); #if 0 /* t1 = (y^a mod p) * (a^b mod p) mod p */ gcry_mpi_powm( t1, pkey->y, a, pkey->p ); gcry_mpi_powm( t2, a, b, pkey->p ); mpi_mulm( t1, t1, t2, pkey->p ); /* t2 = g ^ input mod p */ gcry_mpi_powm( t2, pkey->g, input, pkey->p ); rc = !mpi_cmp( t1, t2 ); #elif 0 /* t1 = (y^a mod p) * (a^b mod p) mod p */ base[0] = pkey->y; ex[0] = a; base[1] = a; ex[1] = b; base[2] = NULL; ex[2] = NULL; mpi_mulpowm( t1, base, ex, pkey->p ); /* t2 = g ^ input mod p */ gcry_mpi_powm( t2, pkey->g, input, pkey->p ); rc = !mpi_cmp( t1, t2 ); #else /* t1 = g ^ - input * y ^ a * a ^ b mod p */ mpi_invm(t2, pkey->g, pkey->p ); base[0] = t2 ; ex[0] = input; base[1] = pkey->y; ex[1] = a; base[2] = a; ex[2] = b; base[3] = NULL; ex[3] = NULL; mpi_mulpowm( t1, base, ex, pkey->p ); rc = !mpi_cmp_ui( t1, 1 ); #endif mpi_free(t1); mpi_free(t2); return rc; }
/* This function returns a new context for Barrett based operations on the modulus M. This context needs to be released using _gcry_mpi_barrett_free. If COPY is true M will be transferred to the context and the user may change M. If COPY is false, M may not be changed until gcry_mpi_barrett_free has been called. */ mpi_barrett_t _gcry_mpi_barrett_init (gcry_mpi_t m, int copy) { mpi_barrett_t ctx; gcry_mpi_t tmp; mpi_normalize (m); ctx = xcalloc (1, sizeof *ctx); if (copy) { ctx->m = mpi_copy (m); ctx->m_copied = 1; } else ctx->m = m; ctx->k = mpi_get_nlimbs (m); tmp = mpi_alloc (ctx->k + 1); /* Barrett precalculation: y = floor(b^(2k) / m). */ mpi_set_ui (tmp, 1); mpi_lshift_limbs (tmp, 2 * ctx->k); mpi_fdiv_q (tmp, tmp, m); ctx->y = tmp; ctx->r1 = mpi_alloc ( 2 * ctx->k + 1 ); ctx->r2 = mpi_alloc ( 2 * ctx->k + 1 ); return ctx; }
void mpi_fdiv_q( MPI quot, MPI dividend, MPI divisor ) { MPI tmp = mpi_alloc( mpi_get_nlimbs(quot) ); mpi_fdiv_qr( quot, tmp, dividend, divisor); mpi_free_gpg(tmp); }
void _gcry_mpi_fdiv_q( gcry_mpi_t quot, gcry_mpi_t dividend, gcry_mpi_t divisor ) { gcry_mpi_t tmp = mpi_alloc( mpi_get_nlimbs(quot) ); _gcry_mpi_fdiv_qr( quot, tmp, dividend, divisor); mpi_free(tmp); }
void gcry_mpi_div (gcry_mpi_t quot, gcry_mpi_t rem, gcry_mpi_t dividend, gcry_mpi_t divisor, int round) { if (!round) { if (!rem) { gcry_mpi_t tmp = mpi_alloc (mpi_get_nlimbs(quot)); _gcry_mpi_tdiv_qr (quot, tmp, dividend, divisor); mpi_free (tmp); } else _gcry_mpi_tdiv_qr (quot, rem, dividend, divisor); } else if (round < 0) { if (!rem) _gcry_mpi_fdiv_q (quot, dividend, divisor); else if (!quot) _gcry_mpi_fdiv_r (rem, dividend, divisor); else _gcry_mpi_fdiv_qr (quot, rem, dividend, divisor); } else log_bug ("mpi rounding to ceiling not yet implemented\n"); }
/* R = X mod M Using Barrett reduction. Before using this function _gcry_mpi_barrett_init must have been called to do the precalculations. CTX is the context created by this precalculation and also conveys M. If the Barret reduction could no be done a straightforward reduction method is used. We assume that these conditions are met: Input: x =(x_2k-1 ...x_0)_b m =(m_k-1 ....m_0)_b with m_k-1 != 0 Output: r = x mod m */ void _gcry_mpi_mod_barrett (gcry_mpi_t r, gcry_mpi_t x, mpi_barrett_t ctx) { gcry_mpi_t m = ctx->m; int k = ctx->k; gcry_mpi_t y = ctx->y; gcry_mpi_t r1 = ctx->r1; gcry_mpi_t r2 = ctx->r2; int sign; mpi_normalize (x); if (mpi_get_nlimbs (x) > 2*k ) { mpi_mod (r, x, m); return; } sign = x->sign; x->sign = 0; /* 1. q1 = floor( x / b^k-1) * q2 = q1 * y * q3 = floor( q2 / b^k+1 ) * Actually, we don't need qx, we can work direct on r2 */ mpi_set ( r2, x ); mpi_rshift_limbs ( r2, k-1 ); mpi_mul ( r2, r2, y ); mpi_rshift_limbs ( r2, k+1 ); /* 2. r1 = x mod b^k+1 * r2 = q3 * m mod b^k+1 * r = r1 - r2 * 3. if r < 0 then r = r + b^k+1 */ mpi_set ( r1, x ); if ( r1->nlimbs > k+1 ) /* Quick modulo operation. */ r1->nlimbs = k+1; mpi_mul ( r2, r2, m ); if ( r2->nlimbs > k+1 ) /* Quick modulo operation. */ r2->nlimbs = k+1; mpi_sub ( r, r1, r2 ); if ( mpi_has_sign ( r ) ) { if (!ctx->r3) { ctx->r3 = mpi_alloc ( k + 2 ); mpi_set_ui (ctx->r3, 1); mpi_lshift_limbs (ctx->r3, k + 1 ); } mpi_add ( r, r, ctx->r3 ); } /* 4. while r >= m do r = r - m */ while ( mpi_cmp( r, m ) >= 0 ) mpi_sub ( r, r, m ); x->sign = sign; }
gcry_mpi_t gcry_mpi_set( gcry_mpi_t w, const gcry_mpi_t u ) { if( !w ) w = _gcry_mpi_alloc( mpi_get_nlimbs(u) ); _gcry_mpi_set( w, (gcry_mpi_t)u ); return w; }
static gcry_err_code_t ecc_sign (int algo, gcry_mpi_t *resarr, gcry_mpi_t data, gcry_mpi_t *skey) { gpg_err_code_t err; ECC_secret_key sk; (void)algo; if (!data || !skey[0] || !skey[1] || !skey[2] || !skey[3] || !skey[4] || !skey[5] || !skey[6] ) return GPG_ERR_BAD_MPI; sk.E.p = skey[0]; sk.E.a = skey[1]; sk.E.b = skey[2]; point_init (&sk.E.G); err = os2ec (&sk.E.G, skey[3]); if (err) { point_free (&sk.E.G); return err; } sk.E.n = skey[4]; point_init (&sk.Q); err = os2ec (&sk.Q, skey[5]); if (err) { point_free (&sk.E.G); point_free (&sk.Q); return err; } sk.d = skey[6]; resarr[0] = mpi_alloc (mpi_get_nlimbs (sk.E.p)); resarr[1] = mpi_alloc (mpi_get_nlimbs (sk.E.p)); err = sign (data, &sk, resarr[0], resarr[1]); if (err) { mpi_free (resarr[0]); mpi_free (resarr[1]); resarr[0] = NULL; /* Mark array as released. */ } point_free (&sk.E.G); point_free (&sk.Q); return err; }
int elg_encrypt( int algo, MPI *resarr, MPI data, MPI *pkey ) { ELG_public_key pk; if( !is_ELGAMAL(algo) ) return G10ERR_PUBKEY_ALGO; if( !data || !pkey[0] || !pkey[1] || !pkey[2] ) return G10ERR_BAD_MPI; pk.p = pkey[0]; pk.g = pkey[1]; pk.y = pkey[2]; resarr[0] = mpi_alloc( mpi_get_nlimbs( pk.p ) ); resarr[1] = mpi_alloc( mpi_get_nlimbs( pk.p ) ); do_encrypt( resarr[0], resarr[1], data, &pk ); return 0; }
int mpi_fdiv_q( MPI quot, MPI dividend, MPI divisor ) { MPI tmp = mpi_alloc( mpi_get_nlimbs(quot) ); if (!tmp) return -ENOMEM; mpi_fdiv_qr( quot, tmp, dividend, divisor); mpi_free(tmp); return 0; }
/**************** * Test whether the secret key is valid. * Returns: true if this is a valid key. */ static int check_secret_key( RSA_secret_key *sk ) { int rc; gcry_mpi_t temp = mpi_alloc( mpi_get_nlimbs(sk->p)*2 ); mpi_mul(temp, sk->p, sk->q ); rc = mpi_cmp( temp, sk->n ); mpi_free(temp); return !rc; }
/**************** * Test whether the secret key is valid. * Returns: if this is a valid key. */ static int check_secret_key( ELG_secret_key *sk ) { int rc; gcry_mpi_t y = mpi_alloc( mpi_get_nlimbs(sk->y) ); gcry_mpi_powm( y, sk->g, sk->x, sk->p ); rc = !mpi_cmp( y, sk->y ); mpi_free( y ); return rc; }
static void sign(gcry_mpi_t a, gcry_mpi_t b, gcry_mpi_t input, ELG_secret_key *skey ) { gcry_mpi_t k; gcry_mpi_t t = mpi_alloc( mpi_get_nlimbs(a) ); gcry_mpi_t inv = mpi_alloc( mpi_get_nlimbs(a) ); gcry_mpi_t p_1 = mpi_copy(skey->p); /* * b = (t * inv) mod (p-1) * b = (t * inv(k,(p-1),(p-1)) mod (p-1) * b = (((M-x*a) mod (p-1)) * inv(k,(p-1),(p-1))) mod (p-1) * */ mpi_sub_ui(p_1, p_1, 1); k = gen_k( skey->p, 0 /* no small K ! */ ); gcry_mpi_powm( a, skey->g, k, skey->p ); mpi_mul(t, skey->x, a ); mpi_subm(t, input, t, p_1 ); mpi_invm(inv, k, p_1 ); mpi_mulm(b, t, inv, p_1 ); #if 0 if( DBG_CIPHER ) { log_mpidump("elg sign p= ", skey->p); log_mpidump("elg sign g= ", skey->g); log_mpidump("elg sign y= ", skey->y); log_mpidump("elg sign x= ", skey->x); log_mpidump("elg sign k= ", k); log_mpidump("elg sign M= ", input); log_mpidump("elg sign a= ", a); log_mpidump("elg sign b= ", b); } #endif mpi_free(k); mpi_free(t); mpi_free(inv); mpi_free(p_1); }
gcry_err_code_t _gcry_elg_encrypt (int algo, gcry_mpi_t *resarr, gcry_mpi_t data, gcry_mpi_t *pkey, int flags) { gcry_err_code_t err = GPG_ERR_NO_ERROR; ELG_public_key pk; (void)algo; (void)flags; if ((! data) || (! pkey[0]) || (! pkey[1]) || (! pkey[2])) err = GPG_ERR_BAD_MPI; else { pk.p = pkey[0]; pk.g = pkey[1]; pk.y = pkey[2]; resarr[0] = mpi_alloc (mpi_get_nlimbs (pk.p)); resarr[1] = mpi_alloc (mpi_get_nlimbs (pk.p)); do_encrypt (resarr[0], resarr[1], data, &pk); } return err; }
/**************** * Barrett precalculation: y = floor(b^(2k) / m) */ static gcry_mpi_t init_barrett( gcry_mpi_t m, int *k, gcry_mpi_t *r1, gcry_mpi_t *r2 ) { gcry_mpi_t tmp; mpi_normalize( m ); *k = mpi_get_nlimbs( m ); tmp = mpi_alloc( *k + 1 ); mpi_set_ui( tmp, 1 ); mpi_lshift_limbs( tmp, 2 * *k ); mpi_fdiv_q( tmp, tmp, m ); *r1 = mpi_alloc( 2* *k + 1 ); *r2 = mpi_alloc( 2* *k + 1 ); return tmp; }
gcry_err_code_t _gcry_elg_sign (int algo, gcry_mpi_t *resarr, gcry_mpi_t data, gcry_mpi_t *skey) { gcry_err_code_t err = GPG_ERR_NO_ERROR; ELG_secret_key sk; (void)algo; if ((! data) || (! skey[0]) || (! skey[1]) || (! skey[2]) || (! skey[3])) err = GPG_ERR_BAD_MPI; else { sk.p = skey[0]; sk.g = skey[1]; sk.y = skey[2]; sk.x = skey[3]; resarr[0] = mpi_alloc (mpi_get_nlimbs (sk.p)); resarr[1] = mpi_alloc (mpi_get_nlimbs (sk.p)); sign (resarr[0], resarr[1], data, &sk); } return err; }
/**************** * Barrett reduction: We assume that these conditions are met: * Given x =(x_2k-1 ...x_0)_b * m =(m_k-1 ....m_0)_b with m_k-1 != 0 * Output r = x mod m * Before using this function init_barret must be used to calucalte y and k. * Returns: false = no error * true = can't perform barret reduction */ static int calc_barrett( gcry_mpi_t r, gcry_mpi_t x, gcry_mpi_t m, gcry_mpi_t y, int k, gcry_mpi_t r1, gcry_mpi_t r2 ) { int xx = k > 3 ? k-3:0; mpi_normalize( x ); if( mpi_get_nlimbs(x) > 2*k ) return 1; /* can't do it */ /* 1. q1 = floor( x / b^k-1) * q2 = q1 * y * q3 = floor( q2 / b^k+1 ) * Actually, we don't need qx, we can work direct on r2 */ mpi_set( r2, x ); mpi_rshift_limbs( r2, k-1 ); mpi_mul( r2, r2, y ); mpi_rshift_limbs( r2, k+1 ); /* 2. r1 = x mod b^k+1 * r2 = q3 * m mod b^k+1 * r = r1 - r2 * 3. if r < 0 then r = r + b^k+1 */ mpi_set( r1, x ); if( r1->nlimbs > k+1 ) /* quick modulo operation */ r1->nlimbs = k+1; mpi_mul( r2, r2, m ); if( r2->nlimbs > k+1 ) /* quick modulo operation */ r2->nlimbs = k+1; mpi_sub( r, r1, r2 ); if( mpi_has_sign (r) ) { gcry_mpi_t tmp; tmp = mpi_alloc( k + 2 ); mpi_set_ui( tmp, 1 ); mpi_lshift_limbs( tmp, k+1 ); mpi_add( r, r, tmp ); mpi_free(tmp); } /* 4. while r >= m do r = r - m */ while( mpi_cmp( r, m ) >= 0 ) mpi_sub( r, r, m ); return 0; }
gcry_mpi_t gcry_mpi_set( gcry_mpi_t w, gcry_mpi_t u) { mpi_ptr_t wp, up; mpi_size_t usize = u->nlimbs; int usign = u->sign; if (!w) w = _gcry_mpi_alloc( mpi_get_nlimbs(u) ); RESIZE_IF_NEEDED(w, usize); wp = w->d; up = u->d; MPN_COPY( wp, up, usize ); w->nlimbs = usize; w->flags = u->flags; w->sign = usign; return w; }
int elg_decrypt( int algo, MPI *result, MPI *data, MPI *skey ) { ELG_secret_key sk; if( !is_ELGAMAL(algo) ) return G10ERR_PUBKEY_ALGO; if( !data[0] || !data[1] || !skey[0] || !skey[1] || !skey[2] || !skey[3] ) return G10ERR_BAD_MPI; sk.p = skey[0]; sk.g = skey[1]; sk.y = skey[2]; sk.x = skey[3]; *result = mpi_alloc_secure( mpi_get_nlimbs( sk.p ) ); decrypt( *result, data[0], data[1], &sk ); return 0; }
static void decrypt(gcry_mpi_t output, gcry_mpi_t a, gcry_mpi_t b, ELG_secret_key *skey ) { gcry_mpi_t t1 = mpi_alloc_secure( mpi_get_nlimbs( skey->p ) ); /* output = b/(a^x) mod p */ gcry_mpi_powm( t1, a, skey->x, skey->p ); mpi_invm( t1, t1, skey->p ); mpi_mulm( output, b, t1, skey->p ); #if 0 if( DBG_CIPHER ) { log_mpidump("elg decrypted x= ", skey->x); log_mpidump("elg decrypted p= ", skey->p); log_mpidump("elg decrypted a= ", a); log_mpidump("elg decrypted b= ", b); log_mpidump("elg decrypted M= ", output); } #endif mpi_free(t1); }
gcry_err_code_t _gcry_elg_decrypt (int algo, gcry_mpi_t *result, gcry_mpi_t *data, gcry_mpi_t *skey, int flags) { gcry_err_code_t err = GPG_ERR_NO_ERROR; ELG_secret_key sk; (void)algo; (void)flags; if ((! data[0]) || (! data[1]) || (! skey[0]) || (! skey[1]) || (! skey[2]) || (! skey[3])) err = GPG_ERR_BAD_MPI; else { sk.p = skey[0]; sk.g = skey[1]; sk.y = skey[2]; sk.x = skey[3]; *result = mpi_alloc_secure (mpi_get_nlimbs (sk.p)); decrypt (*result, data[0], data[1], &sk); } return err; }
gcry_mpi_t _gcry_mpi_set (gcry_mpi_t w, gcry_mpi_t u) { mpi_ptr_t wp, up; mpi_size_t usize = u->nlimbs; int usign = u->sign; if (!w) w = _gcry_mpi_alloc( mpi_get_nlimbs(u) ); if (mpi_is_immutable (w)) { mpi_immutable_failed (); return w; } RESIZE_IF_NEEDED(w, usize); wp = w->d; up = u->d; MPN_COPY( wp, up, usize ); w->nlimbs = usize; w->flags = u->flags; w->flags &= ~(16|32); /* Reset the immutable and constant flags. */ w->sign = usign; return w; }
/* * Generate a random secret exponent K less than Q. * Note that ECDSA uses this code also to generate D. */ gcry_mpi_t _gcry_dsa_gen_k (gcry_mpi_t q, int security_level) { gcry_mpi_t k = mpi_alloc_secure (mpi_get_nlimbs (q)); unsigned int nbits = mpi_get_nbits (q); unsigned int nbytes = (nbits+7)/8; char *rndbuf = NULL; /* To learn why we don't use mpi_mod to get the requested bit size, read the paper: "The Insecurity of the Digital Signature Algorithm with Partially Known Nonces" by Nguyen and Shparlinski. Journal of Cryptology, New York. Vol 15, nr 3 (2003) */ if (DBG_CIPHER) log_debug ("choosing a random k of %u bits at seclevel %d\n", nbits, security_level); for (;;) { if ( !rndbuf || nbits < 32 ) { xfree (rndbuf); rndbuf = _gcry_random_bytes_secure (nbytes, security_level); } else { /* Change only some of the higher bits. We could improve this by directly requesting more memory at the first call to get_random_bytes() and use these extra bytes here. However the required management code is more complex and thus we better use this simple method. */ char *pp = _gcry_random_bytes_secure (4, security_level); memcpy (rndbuf, pp, 4); xfree (pp); } _gcry_mpi_set_buffer (k, rndbuf, nbytes, 0); /* Make sure we have the requested number of bits. This code looks a bit funny but it is easy to understand if you consider that mpi_set_highbit clears all higher bits. We don't have a clear_highbit, thus we first set the high bit and then clear it again. */ if (mpi_test_bit (k, nbits-1)) mpi_set_highbit (k, nbits-1); else { mpi_set_highbit (k, nbits-1); mpi_clear_bit (k, nbits-1); } if (!(mpi_cmp (k, q) < 0)) /* check: k < q */ { if (DBG_CIPHER) log_debug ("\tk too large - again\n"); continue; /* no */ } if (!(mpi_cmp_ui (k, 0) > 0)) /* check: k > 0 */ { if (DBG_CIPHER) log_debug ("\tk is zero - again\n"); continue; /* no */ } break; /* okay */ } xfree (rndbuf); return k; }
/**************** * Public key operation. Encrypt INPUT with PKEY and put result into OUTPUT. * * c = m^e mod n * * Where c is OUTPUT, m is INPUT and e,n are elements of PKEY. */ static void public(gcry_mpi_t output, gcry_mpi_t input, RSA_public_key *pkey ) { if( output == input ) /* powm doesn't like output and input the same */ { gcry_mpi_t x = mpi_alloc( mpi_get_nlimbs(input)*2 ); mpi_powm( x, input, pkey->e, pkey->n ); mpi_set(output, x); mpi_free(x); } else mpi_powm( output, input, pkey->e, pkey->n ); } #if 0 static void stronger_key_check ( RSA_secret_key *skey ) { gcry_mpi_t t = mpi_alloc_secure ( 0 ); gcry_mpi_t t1 = mpi_alloc_secure ( 0 ); gcry_mpi_t t2 = mpi_alloc_secure ( 0 );
/**************** * Calculate the multiplicative inverse X of A mod N * That is: Find the solution x for * 1 = (a*x) mod n */ int mpi_invm(MPI x, const MPI a, const MPI n) { /* Extended Euclid's algorithm (See TAOPC Vol II, 4.5.2, Alg X) * modified according to Michael Penk's solution for Exercice 35 * with further enhancement */ MPI u = NULL, v = NULL; MPI u1 = NULL, u2 = NULL, u3 = NULL; MPI v1 = NULL, v2 = NULL, v3 = NULL; MPI t1 = NULL, t2 = NULL, t3 = NULL; unsigned k; int sign; int odd = 0; int rc = -ENOMEM; if (mpi_copy(&u, a) < 0) goto cleanup; if (mpi_copy(&v, n) < 0) goto cleanup; for (k = 0; !mpi_test_bit(u, 0) && !mpi_test_bit(v, 0); k++) { if (mpi_rshift(u, u, 1) < 0) goto cleanup; if (mpi_rshift(v, v, 1) < 0) goto cleanup; } odd = mpi_test_bit(v, 0); u1 = mpi_alloc_set_ui(1); if (!u1) goto cleanup; if (!odd) { u2 = mpi_alloc_set_ui(0); if (!u2) goto cleanup; } if (mpi_copy(&u3, u) < 0) goto cleanup; if (mpi_copy(&v1, v) < 0) goto cleanup; if (!odd) { v2 = mpi_alloc(mpi_get_nlimbs(u)); if (!v2) goto cleanup; if (mpi_sub(v2, u1, u) < 0) goto cleanup; /* U is used as const 1 */ } if (mpi_copy(&v3, v) < 0) goto cleanup; if (mpi_test_bit(u, 0)) { /* u is odd */ t1 = mpi_alloc_set_ui(0); if (!t1) goto cleanup; if (!odd) { t2 = mpi_alloc_set_ui(1); if (!t2) goto cleanup; t2->sign = 1; } if (mpi_copy(&t3, v) < 0) goto cleanup; t3->sign = !t3->sign; goto Y4; } else { t1 = mpi_alloc_set_ui(1); if (!t1) goto cleanup; if (!odd) { t2 = mpi_alloc_set_ui(0); if (!t2) goto cleanup; } if (mpi_copy(&t3, u) < 0) goto cleanup; } do { do { if (!odd) { if (mpi_test_bit(t1, 0) || mpi_test_bit(t2, 0)) { /* one is odd */ if (mpi_add(t1, t1, v) < 0) goto cleanup; if (mpi_sub(t2, t2, u) < 0) goto cleanup; } if (mpi_rshift(t1, t1, 1) < 0) goto cleanup; if (mpi_rshift(t2, t2, 1) < 0) goto cleanup; if (mpi_rshift(t3, t3, 1) < 0) goto cleanup; } else { if (mpi_test_bit(t1, 0)) if (mpi_add(t1, t1, v) < 0) goto cleanup; if (mpi_rshift(t1, t1, 1) < 0) goto cleanup; if (mpi_rshift(t3, t3, 1) < 0) goto cleanup; } Y4: ; } while (!mpi_test_bit(t3, 0)); /* while t3 is even */ if (!t3->sign) { if (mpi_set(u1, t1) < 0) goto cleanup; if (!odd) if (mpi_set(u2, t2) < 0) goto cleanup; if (mpi_set(u3, t3) < 0) goto cleanup; } else { if (mpi_sub(v1, v, t1) < 0) goto cleanup; sign = u->sign; u->sign = !u->sign; if (!odd) if (mpi_sub(v2, u, t2) < 0) goto cleanup; u->sign = sign; sign = t3->sign; t3->sign = !t3->sign; if (mpi_set(v3, t3) < 0) goto cleanup; t3->sign = sign; } if (mpi_sub(t1, u1, v1) < 0) goto cleanup; if (!odd) if (mpi_sub(t2, u2, v2) < 0) goto cleanup; if (mpi_sub(t3, u3, v3) < 0) goto cleanup; if (t1->sign) { if (mpi_add(t1, t1, v) < 0) goto cleanup; if (!odd) if (mpi_sub(t2, t2, u) < 0) goto cleanup; } } while (mpi_cmp_ui(t3, 0)); /* while t3 != 0 */ /* mpi_lshift( u3, k ); */ rc = mpi_set(x, u1); cleanup: mpi_free(u1); mpi_free(v1); mpi_free(t1); if (!odd) { mpi_free(u2); mpi_free(v2); mpi_free(t2); } mpi_free(u3); mpi_free(v3); mpi_free(t3); mpi_free(u); mpi_free(v); return rc; }
/**************** * We do not need to use the strongest RNG because we gain no extra * security from it - The prime number is public and we could also * offer the factors for those who are willing to check that it is * indeed a strong prime. With ALL_FACTORS set to true all afcors of * prime-1 are returned in FACTORS. * * mode 0: Standard * 1: Make sure that at least one factor is of size qbits. */ static gcry_err_code_t prime_generate_internal (int mode, gcry_mpi_t *prime_generated, unsigned int pbits, unsigned int qbits, gcry_mpi_t g, gcry_mpi_t **ret_factors, gcry_random_level_t randomlevel, unsigned int flags, int all_factors, gcry_prime_check_func_t cb_func, void *cb_arg) { gcry_err_code_t err = 0; gcry_mpi_t *factors_new = NULL; /* Factors to return to the caller. */ gcry_mpi_t *factors = NULL; /* Current factors. */ gcry_mpi_t *pool = NULL; /* Pool of primes. */ unsigned char *perms = NULL; /* Permutations of POOL. */ gcry_mpi_t q_factor = NULL; /* Used if QBITS is non-zero. */ unsigned int fbits = 0; /* Length of prime factors. */ unsigned int n = 0; /* Number of factors. */ unsigned int m = 0; /* Number of primes in pool. */ gcry_mpi_t q = NULL; /* First prime factor. */ gcry_mpi_t prime = NULL; /* Prime candidate. */ unsigned int nprime = 0; /* Bits of PRIME. */ unsigned int req_qbits; /* The original QBITS value. */ gcry_mpi_t val_2; /* For check_prime(). */ unsigned int is_secret = (flags & GCRY_PRIME_FLAG_SECRET); unsigned int count1 = 0, count2 = 0; unsigned int i = 0, j = 0; if (pbits < 48) return GPG_ERR_INV_ARG; /* If QBITS is not given, assume a reasonable value. */ if (!qbits) qbits = pbits / 3; req_qbits = qbits; /* Find number of needed prime factors. */ for (n = 1; (pbits - qbits - 1) / n >= qbits; n++) ; n--; val_2 = mpi_alloc_set_ui (2); if ((! n) || ((mode == 1) && (n < 2))) { err = GPG_ERR_INV_ARG; goto leave; } if (mode == 1) { n--; fbits = (pbits - 2 * req_qbits -1) / n; qbits = pbits - req_qbits - n * fbits; } else { fbits = (pbits - req_qbits -1) / n; qbits = pbits - n * fbits; } if (DBG_CIPHER) log_debug ("gen prime: pbits=%u qbits=%u fbits=%u/%u n=%d\n", pbits, req_qbits, qbits, fbits, n); prime = gcry_mpi_new (pbits); /* Generate first prime factor. */ q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL); if (mode == 1) q_factor = gen_prime (req_qbits, is_secret, randomlevel, NULL, NULL); /* Allocate an array to hold the factors + 2 for later usage. */ factors = gcry_calloc (n + 2, sizeof (*factors)); if (!factors) { err = gpg_err_code_from_errno (errno); goto leave; } /* Make a pool of 3n+5 primes (this is an arbitrary value). */ m = n * 3 + 5; if (mode == 1) /* Need some more (for e.g. DSA). */ m += 5; if (m < 25) m = 25; pool = gcry_calloc (m , sizeof (*pool)); if (! pool) { err = gpg_err_code_from_errno (errno); goto leave; } /* Permutate over the pool of primes. */ do { next_try: if (! perms) { /* Allocate new primes. */ for(i = 0; i < m; i++) { mpi_free (pool[i]); pool[i] = NULL; } /* Init m_out_of_n(). */ perms = gcry_calloc (1, m); if (! perms) { err = gpg_err_code_from_errno (errno); goto leave; } for(i = 0; i < n; i++) { perms[i] = 1; pool[i] = gen_prime (fbits, is_secret, randomlevel, NULL, NULL); factors[i] = pool[i]; } } else { m_out_of_n ((char*)perms, n, m); for (i = j = 0; (i < m) && (j < n); i++) if (perms[i]) { if(! pool[i]) pool[i] = gen_prime (fbits, 0, 1, NULL, NULL); factors[j++] = pool[i]; } if (i == n) { gcry_free (perms); perms = NULL; progress ('!'); goto next_try; /* Allocate new primes. */ } } /* Generate next prime candidate: p = 2 * q [ * q_factor] * factor_0 * factor_1 * ... * factor_n + 1. */ mpi_set (prime, q); mpi_mul_ui (prime, prime, 2); if (mode == 1) mpi_mul (prime, prime, q_factor); for(i = 0; i < n; i++) mpi_mul (prime, prime, factors[i]); mpi_add_ui (prime, prime, 1); nprime = mpi_get_nbits (prime); if (nprime < pbits) { if (++count1 > 20) { count1 = 0; qbits++; progress('>'); mpi_free (q); q = gen_prime (qbits, 0, 0, NULL, NULL); goto next_try; } } else count1 = 0; if (nprime > pbits) { if (++count2 > 20) { count2 = 0; qbits--; progress('<'); mpi_free (q); q = gen_prime (qbits, 0, 0, NULL, NULL); goto next_try; } } else count2 = 0; } while (! ((nprime == pbits) && check_prime (prime, val_2, cb_func, cb_arg))); if (DBG_CIPHER) { progress ('\n'); log_mpidump ("prime : ", prime); log_mpidump ("factor q: ", q); if (mode == 1) log_mpidump ("factor q0: ", q_factor); for (i = 0; i < n; i++) log_mpidump ("factor pi: ", factors[i]); log_debug ("bit sizes: prime=%u, q=%u", mpi_get_nbits (prime), mpi_get_nbits (q)); if (mode == 1) log_debug (", q0=%u", mpi_get_nbits (q_factor)); for (i = 0; i < n; i++) log_debug (", p%d=%u", i, mpi_get_nbits (factors[i])); progress('\n'); } if (ret_factors) { /* Caller wants the factors. */ factors_new = gcry_calloc (n + 4, sizeof (*factors_new)); if (! factors_new) { err = gpg_err_code_from_errno (errno); goto leave; } if (all_factors) { i = 0; factors_new[i++] = gcry_mpi_set_ui (NULL, 2); factors_new[i++] = mpi_copy (q); if (mode == 1) factors_new[i++] = mpi_copy (q_factor); for(j=0; j < n; j++) factors_new[i++] = mpi_copy (factors[j]); } else { i = 0; if (mode == 1) { factors_new[i++] = mpi_copy (q_factor); for (; i <= n; i++) factors_new[i] = mpi_copy (factors[i]); } else for (; i < n; i++ ) factors_new[i] = mpi_copy (factors[i]); } } if (g) { /* Create a generator (start with 3). */ gcry_mpi_t tmp = mpi_alloc (mpi_get_nlimbs (prime)); gcry_mpi_t b = mpi_alloc (mpi_get_nlimbs (prime)); gcry_mpi_t pmin1 = mpi_alloc (mpi_get_nlimbs (prime)); if (mode == 1) err = GPG_ERR_NOT_IMPLEMENTED; else { factors[n] = q; factors[n + 1] = mpi_alloc_set_ui (2); mpi_sub_ui (pmin1, prime, 1); mpi_set_ui (g, 2); do { mpi_add_ui (g, g, 1); if (DBG_CIPHER) { log_debug ("checking g:"); gcry_mpi_dump (g); log_printf ("\n"); } else progress('^'); for (i = 0; i < n + 2; i++) { mpi_fdiv_q (tmp, pmin1, factors[i]); /* No mpi_pow(), but it is okay to use this with mod prime. */ gcry_mpi_powm (b, g, tmp, prime); if (! mpi_cmp_ui (b, 1)) break; } if (DBG_CIPHER) progress('\n'); } while (i < n + 2); mpi_free (factors[n+1]); mpi_free (tmp); mpi_free (b); mpi_free (pmin1); } } if (! DBG_CIPHER) progress ('\n'); leave: if (pool) { for(i = 0; i < m; i++) mpi_free (pool[i]); gcry_free (pool); } if (factors) gcry_free (factors); /* Factors are shallow copies. */ if (perms) gcry_free (perms); mpi_free (val_2); mpi_free (q); mpi_free (q_factor); if (! err) { *prime_generated = prime; if (ret_factors) *ret_factors = factors_new; } else { if (factors_new) { for (i = 0; factors_new[i]; i++) mpi_free (factors_new[i]); gcry_free (factors_new); } mpi_free (prime); } return err; }
/* * Return true if n is probably a prime */ static int is_prime (gcry_mpi_t n, int steps, unsigned int *count) { gcry_mpi_t x = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t y = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t z = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t nminus1 = mpi_alloc( mpi_get_nlimbs( n ) ); gcry_mpi_t a2 = mpi_alloc_set_ui( 2 ); gcry_mpi_t q; unsigned i, j, k; int rc = 0; unsigned nbits = mpi_get_nbits( n ); mpi_sub_ui( nminus1, n, 1 ); /* Find q and k, so that n = 1 + 2^k * q . */ q = mpi_copy ( nminus1 ); k = mpi_trailing_zeros ( q ); mpi_tdiv_q_2exp (q, q, k); for (i=0 ; i < steps; i++ ) { ++*count; if( !i ) { mpi_set_ui( x, 2 ); } else { gcry_mpi_randomize( x, nbits, GCRY_WEAK_RANDOM ); /* Make sure that the number is smaller than the prime and keep the randomness of the high bit. */ if ( mpi_test_bit ( x, nbits-2) ) { mpi_set_highbit ( x, nbits-2); /* Clear all higher bits. */ } else { mpi_set_highbit( x, nbits-2 ); mpi_clear_bit( x, nbits-2 ); } assert ( mpi_cmp( x, nminus1 ) < 0 && mpi_cmp_ui( x, 1 ) > 0 ); } gcry_mpi_powm ( y, x, q, n); if ( mpi_cmp_ui(y, 1) && mpi_cmp( y, nminus1 ) ) { for ( j=1; j < k && mpi_cmp( y, nminus1 ); j++ ) { gcry_mpi_powm(y, y, a2, n); if( !mpi_cmp_ui( y, 1 ) ) goto leave; /* Not a prime. */ } if (mpi_cmp( y, nminus1 ) ) goto leave; /* Not a prime. */ } progress('+'); } rc = 1; /* May be a prime. */ leave: mpi_free( x ); mpi_free( y ); mpi_free( z ); mpi_free( nminus1 ); mpi_free( q ); mpi_free( a2 ); return rc; }
/**************** * Generate a random secret exponent k from prime p, so that k is * relatively prime to p-1. With SMALL_K set, k will be selected for * better encryption performance - this must never be used signing! */ static gcry_mpi_t gen_k( gcry_mpi_t p, int small_k ) { gcry_mpi_t k = mpi_alloc_secure( 0 ); gcry_mpi_t temp = mpi_alloc( mpi_get_nlimbs(p) ); gcry_mpi_t p_1 = mpi_copy(p); unsigned int orig_nbits = mpi_get_nbits(p); unsigned int nbits, nbytes; char *rndbuf = NULL; if (small_k) { /* Using a k much lesser than p is sufficient for encryption and * it greatly improves the encryption performance. We use * Wiener's table and add a large safety margin. */ nbits = wiener_map( orig_nbits ) * 3 / 2; if( nbits >= orig_nbits ) BUG(); } else nbits = orig_nbits; nbytes = (nbits+7)/8; if( DBG_CIPHER ) log_debug("choosing a random k "); mpi_sub_ui( p_1, p, 1); for(;;) { if( !rndbuf || nbits < 32 ) { gcry_free(rndbuf); rndbuf = gcry_random_bytes_secure( nbytes, GCRY_STRONG_RANDOM ); } else { /* Change only some of the higher bits. We could improve this by directly requesting more memory at the first call to get_random_bytes() and use this the here maybe it is easier to do this directly in random.c Anyway, it is highly inlikely that we will ever reach this code. */ char *pp = gcry_random_bytes_secure( 4, GCRY_STRONG_RANDOM ); memcpy( rndbuf, pp, 4 ); gcry_free(pp); } _gcry_mpi_set_buffer( k, rndbuf, nbytes, 0 ); for(;;) { if( !(mpi_cmp( k, p_1 ) < 0) ) /* check: k < (p-1) */ { if( DBG_CIPHER ) progress('+'); break; /* no */ } if( !(mpi_cmp_ui( k, 0 ) > 0) ) /* check: k > 0 */ { if( DBG_CIPHER ) progress('-'); break; /* no */ } if (gcry_mpi_gcd( temp, k, p_1 )) goto found; /* okay, k is relative prime to (p-1) */ mpi_add_ui( k, k, 1 ); if( DBG_CIPHER ) progress('.'); } } found: gcry_free(rndbuf); if( DBG_CIPHER ) progress('\n'); mpi_free(p_1); mpi_free(temp); return k; }
/**************** * RES = (BASE[0] ^ EXP[0]) * (BASE[1] ^ EXP[1]) * ... * mod M */ int mpi_mulpowm( MPI res, MPI *basearray, MPI *exparray, MPI m) { int rc = -ENOMEM; int k; /* number of elements */ int t; /* bit size of largest exponent */ int i, j, idx; MPI *G = NULL; /* table with precomputed values of size 2^k */ MPI tmp = NULL; for(k=0; basearray[k]; k++ ) ; if (!k) { printk("mpi_mulpowm: assert(k) failed\n"); BUG(); } for(t=0, i=0; (tmp=exparray[i]); i++ ) { j = mpi_get_nbits(tmp); if( j > t ) t = j; } if (i!=k) { printk("mpi_mulpowm: assert(i==k) failed\n"); BUG(); } if (!t) { printk("mpi_mulpowm: assert(t) failed\n"); BUG(); } if (k>=10) { printk("mpi_mulpowm: assert(k<10) failed\n"); BUG(); } //daveti: hack //G = kzalloc( (1<<k) * sizeof *G, GFP_KERNEL ); G = kzalloc( (1<<k) * sizeof *G, GFP_ATOMIC ); if (!G) goto nomem; /* and calculate */ tmp = mpi_alloc( mpi_get_nlimbs(m)+1 ); if (!tmp) goto nomem; if (mpi_set_ui( res, 1 ) < 0) goto nomem; for(i = 1; i <= t; i++ ) { if (mpi_mulm(tmp, res, res, m ) < 0) goto nomem; idx = build_index( exparray, k, i, t ); if (!(idx >= 0 && idx < (1<<k))) { printk("mpi_mulpowm: assert(idx >= 0 && idx < (1<<k)) failed\n"); BUG(); } if( !G[idx] ) { if( !idx ) { G[0] = mpi_alloc_set_ui( 1 ); if (!G[0]) goto nomem; } else { for(j=0; j < k; j++ ) { if( (idx & (1<<j) ) ) { if( !G[idx] ) { if (mpi_copy( &G[idx], basearray[j] ) < 0) goto nomem; } else { if (mpi_mulm(G[idx],G[idx],basearray[j],m) < 0) goto nomem; } } } if( !G[idx] ) { G[idx] = mpi_alloc(0); if (!G[idx]) goto nomem; } } } if (mpi_mulm(res, tmp, G[idx], m ) < 0) goto nomem; } rc = 0; nomem: /* cleanup */ mpi_free(tmp); for(i=0; i < (1<<k); i++ ) mpi_free(G[i]); kfree(G); return rc; }