[C language] Calculation when the exponent is negative in BIGNUM of OpenSSL

I was addicted to using the openssl library in C language, so make a note.

There is a function called BN_mod_exp in bn.h, but when I tried to do something like n ^ (-2) with this one, it didn't work.

//The variable name and the method are quite different, so please give it a try. ..
BN_set_word(shisu, 2); //2 is entered in shisu
BN_set_negative(shisu, 1);  //shisu-Become 2
BN_mod_exp(out, n, shisu, mod, ctx); //Calculation
//out becomes a strange value...

BN_mod_exp doesn't seem to be good at calculating negative exponentials, so I changed it as follows.

BN_set_word(shisu, 2); //2 is entered in shisu
BN_mod_exp(out, n, shisu, mod, ctx); // n^Calculation of 2
BN_mod_inverse(out, out, mod, ctx); // n^The inverse element of 2, that is, 1/n^Calculate 2
//out is the right value!

I calculated n ^ (-2) as 1 / n ^ 2 and it worked.

There are so many things I don't understand (especially mathematically), so it's dangerous information, but it worked, so I wrote it down. Is it Nanika because of the mod world? .. Is it just a BIGNUM specification? ..

Terminology: Negative index Negative index Negative value Negative value Exponentiation

Recommended Posts