intel / cryptography-primitives

Apache License 2.0
318 stars 86 forks source link

Modular exponentiation bug for 65 bits power input #39

Closed skmono closed 2 years ago

skmono commented 2 years ago

@bwang30 and I found a weird bug in the multi buffer modular exponentiation in mbx_exp4096_mb8 when the power input is exactly 65 bits.

The following is a sample input that fails to run:

  std::vector<Ipp32u> v_expo(3, 1); // 65 bits
  std::vector<Ipp32u> v_base(64, 1);
  std::vector<Ipp32u> v_mod(128, 2); // 4066 bits
  BigNumber bn_base[8];
  BigNumber bn_expo[8];
  BigNumber bn_mod[8];

  for (int i=0; i<8; ++i){
    bn_base[i] = BigNumber(&v_base[0], v_base.size());
    bn_mod[i] = BigNumber(&v_mod[0], v_mod.size());
    bn_expo[i] = BigNumber(&v_expo[0], v_expo.size());
  }

  std::cout<<"exp input bit size = "<<bn_expo[0].BitSize()<<std::endl; // 65

With the bn_expo value set above, exp_bits = 65 (bn_expo[i].BitSize()=65) and the result is completely off. However, any other value where BitSize != 65 works perfectly fine.

One temporary workaround for this issue was to intentionally align the exp_bits to 8, by adding:

#define BITSIZE_BYTE(n) ((((n) + 7) >> 3))
int maxExpBitLen = BITSIZE_BYTE(expBitLen) * 8;

where maxExpBitLen=72 when expBitLen=65.

I can provide a test code to replicate the issue if needed.

amatyuko-intc commented 2 years ago

@bwang30, @skmono, thanks for taking time to report this. The issue is fixed and the fix will be available in the next release.