示例#1
0
/*
 * Create own private value X and export G^X
 */
int dhm_make_public (dhm_context * ctx, int x_size, unsigned char* output, int olen, int (*f_rng) (void* ), void* p_rng)
{
    int ret, i, n;
    unsigned char* p;

    if (ctx == NULL || olen < 1 || olen > ctx->len)
        return (POLARSSL_ERR_DHM_BAD_INPUT_DATA);

    /*
     * generate X and calculate GX = G^X mod P
     */
    n = x_size / sizeof (t_int);
    MPI_CHK (mpi_grow (&ctx->X, n));
    MPI_CHK (mpi_lset (&ctx->X, 0));

    n = x_size - 1;
    p = (unsigned char *) ctx->X.p;
    for (i = 0; i < n; i++)
        *p++ = (unsigned char) f_rng (p_rng);

    while (mpi_cmp_mpi (&ctx->X, &ctx->P) >= 0)
        mpi_shift_r (&ctx->X, 1);

    MPI_CHK (mpi_exp_mod (&ctx->GX, &ctx->G, &ctx->X, &ctx->P, &ctx->RP));

    MPI_CHK (mpi_write_binary (&ctx->GX, output, olen));

  cleanup:

    if (ret != 0)
        return (POLARSSL_ERR_DHM_MAKE_PUBLIC_FAILED | ret);

    return (0);
}
示例#2
0
文件: dhm.c 项目: 54madao/Mobile-C
/*
 * Setup and write the ServerKeyExchange parameters
 */
int dhm_make_params( dhm_context *ctx, int x_size,
                     unsigned char *output, int *olen,
                     int (*f_rng)(void *), void *p_rng )
{
    int i, ret, n, n1, n2, n3;
    unsigned char *p;

    /*
     * generate X and calculate GX = G^X mod P
     */
    n = x_size / sizeof( t_int );
    MPI_CHK( mpi_grow( &ctx->X, n ) );
    MPI_CHK( mpi_lset( &ctx->X, 0 ) );

    n = x_size >> 3;
    p = (unsigned char *) ctx->X.p;
    for( i = 0; i < n; i++ )
        *p++ = (unsigned char) f_rng( p_rng );

    while( mpi_cmp_mpi( &ctx->X, &ctx->P ) >= 0 )
           mpi_shift_r( &ctx->X, 1 );

    MPI_CHK( mpi_exp_mod( &ctx->GX, &ctx->G, &ctx->X,
                          &ctx->P , &ctx->RP ) );

    /*
     * export P, G, GX
     */
#define DHM_MPI_EXPORT(X,n)                     \
    MPI_CHK( mpi_write_binary( X, p + 2, n ) ); \
    *p++ = (unsigned char)( n >> 8 );           \
    *p++ = (unsigned char)( n      ); p += n;

    n1 = mpi_size( &ctx->P  );
    n2 = mpi_size( &ctx->G  );
    n3 = mpi_size( &ctx->GX );

    p = output;
    DHM_MPI_EXPORT( &ctx->P , n1 );
    DHM_MPI_EXPORT( &ctx->G , n2 );
    DHM_MPI_EXPORT( &ctx->GX, n3 );

    *olen  = p - output;

    ctx->len = n1;

cleanup:

    if( ret != 0 )
        return( ret | XYSSL_ERR_DHM_MAKE_PARAMS_FAILED );

    return( 0 );
}