Barrett Reduction算法求模

Barrett Reduction is a method of reducing a number modulo another number. Barrett reduction, when used to reduce a single number, is slower than a normal divide algorithm. However, by precomputing some values, one can easily far exceed the speed of normal modular reductions.

Because Barrett reduction's benefits are most visible when it is used to reduce various numbers modulo a single number many times, for example, when doing modular exponentiation. Barrett reduction is not particularly useful when used with small numbers (32 or 64 bits); it's benefits occur when using numbers that are implemented by multiple precision arithmetic libraries, such as when implementing the RSA cryptosystem, which uses modular exponentiation with large (> 512 bit) numbers, to encrypt and decrypt.

So, how do you do it? First, keep in mind the following restriction: Barrett Reduction can only reduce numbers that are, at most, twice as long (in words) as the modulus. Thats computer words; usually these are 32 bits long (for example on x86 and PowerPC machines), and sometimes 64 bits (like on the Alpha, UltraSPARC, and MIPS R10000).

So you have some modulus, called m, which is k words long (numbered k-1...0, with 0 being the least significant word). First, precalculate the value:

mu = floor(b^k / m)

where b is the "base" of the integers used. For example, if you represented the numbers as a sequence of 32-bit values, b is 2^32, or 0x100000000. You will keep this value mu across function calls (probably stored in a structure somewhere), so you can reuse it.

Now, given a number x, which is an arbitrary integer of size (at most) 2k words (2k-1...0), this procedure (in pseudocode) will return the value of x mod m:

q1 = floor(x / b^(k-1))
q2 = q1 * mu
q3 = floor(q2 / b^(k+1))
r1 = x mod b^(k+1)
r2 = (q3 * m) mod b^(k+1)
r  = r1 - r2

  
  
   
    
  
  
if(r < 0)
  r = r + b^(k+1)
while(r >= m)
  r = r - m
return r

Note that the divisions and modular reductions in this procedure can be replaced by right shifts and AND operations (respectively) if (and only if) b is a power of 2 (which, by far, will be the most common choice). This results in the remaining operations being addition and multiplication, both of which are much cheaper than division for multiple precision integers.

This algorithm is also specified in the Handbook of Applied Cryptography (good book!), and is implemented by some crypto libraries. Another method of doing fast modular reductions is Montgomery Reduction.

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值