📄 mrbrick.c
字号:
/*
* Module to implement Comb method for fast
* computation of g^x mod n, for fixed g and n, using precomputation.
* This idea can be used to substantially speed up certain phases
* of the Digital Signature Standard (DSS) for example.
*
* See "Handbook of Applied Cryptography", CRC Press, 2001
*
* Copyright (c) 1988-2006 Shamus Software Ltd.
*/
#include <stdlib.h>
#include "miracl.h"
#ifndef MR_STATIC
BOOL brick_init(_MIPD_ brick *b,big g,big n,int window,int nb)
{ /* Uses Montgomery arithmetic internally *
* g is the fixed base for exponentiation *
* n is the fixed modulus *
* nb is the maximum number of bits in the exponent */
int i,j,k,t,bp;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (nb<2 || window<1 || window>nb || mr_mip->ERNUM) return FALSE;
t=MR_ROUNDUP(nb,window);
if (t<2) return FALSE;
MR_IN(109)
#ifndef MR_ALWAYS_BINARY
if (mr_mip->base != mr_mip->base2)
{
mr_berror(_MIPP_ MR_ERR_NOT_SUPPORTED);
MR_OUT
return FALSE;
}
#endif
b->window=window;
b->max=nb;
b->table=mr_alloc(_MIPP_ (1<<window),sizeof(big));
if (b->table==NULL)
{
mr_berror(_MIPP_ MR_ERR_OUT_OF_MEMORY);
MR_OUT
return FALSE;
}
b->n=mirvar(_MIPP_ 0);
copy(n,b->n);
prepare_monty(_MIPP_ n);
nres(_MIPP_ g,mr_mip->w1);
convert(_MIPP_ 1,mr_mip->w2);
nres(_MIPP_ mr_mip->w2,mr_mip->w2);
b->table[0]=mirvar(_MIPP_ 0);
copy(mr_mip->w2,b->table[0]);
b->table[1]=mirvar(_MIPP_ 0);
copy(mr_mip->w1,b->table[1]);
for (j=0;j<t;j++)
nres_modmult(_MIPP_ mr_mip->w1,mr_mip->w1,mr_mip->w1);
convert(_MIPP_ 1,mr_mip->w2);
nres(_MIPP_ mr_mip->w2,mr_mip->w2);
k=1;
for (i=2;i<(1<<window);i++)
{
b->table[i]=mirvar(_MIPP_ 0);
if (i==(1<<k))
{
k++;
copy(mr_mip->w1,b->table[i]);
for (j=0;j<t;j++)
nres_modmult(_MIPP_ mr_mip->w1,mr_mip->w1,mr_mip->w1);
continue;
}
bp=1;
copy(mr_mip->w2,b->table[i]);
for (j=0;j<k;j++)
{
if (i&bp)
nres_modmult(_MIPP_ b->table[1<<j],b->table[i],b->table[i]);
bp<<=1;
}
}
MR_OUT
return TRUE;
}
void brick_end(brick *b)
{
int i;
for (i=0;i<(1<<b->window);i++)
mirkill(b->table[i]);
mirkill(b->n);
mr_free(b->table);
}
#endif
void pow_brick(_MIPD_ brick *b,big e,big w)
{
int i,j,t;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (size(e)<0) mr_berror(_MIPP_ MR_ERR_NEG_POWER);
t=MR_ROUNDUP(b->max,b->window);
MR_IN(110)
#ifndef MR_ALWAYS_BINARY
if (mr_mip->base != mr_mip->base2)
{
mr_berror(_MIPP_ MR_ERR_NOT_SUPPORTED);
MR_OUT
return;
}
#endif
if (logb2(_MIPP_ e) > b->max)
{
mr_berror(_MIPP_ MR_ERR_EXP_TOO_BIG);
MR_OUT
return;
}
prepare_monty(_MIPP_ b->n);
j=recode(_MIPP_ e,t,b->window,t-1);
copy(b->table[j],mr_mip->w1);
for (i=t-2;i>=0;i--)
{
j=recode(_MIPP_ e,t,b->window,i);
nres_modmult(_MIPP_ mr_mip->w1,mr_mip->w1,mr_mip->w1);
nres_modmult(_MIPP_ mr_mip->w1,b->table[j],mr_mip->w1);
}
redc(_MIPP_ mr_mip->w1,w);
MR_OUT
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -