1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[C言語]OpenSSLのBIGNUMで、指数がマイナスのときの計算

1
Posted at

opensslのライブラリをC言語で使っていたら、ハマったのでメモ。

bn.hBN_mod_exp という関数があるが、こいつで n^(-2) みたいな事をしようと思ったら、うまくいかなかった。

// 変数名とかやり方とかなかなかアレなんで、おおめにみてください。。
BN_set_word(shisu, 2); // shisu に 2 が入る
BN_set_negative(shisu, 1);  // shisu が -2 になる
BN_mod_exp(out, n, shisu, mod, ctx); // 計算
// out が変な値に...

BN_mod_exp はどうも負の指数の計算をうまいことしてくれないので、以下のように変更した。

BN_set_word(shisu, 2); // shisu に 2 が入る
BN_mod_exp(out, n, shisu, mod, ctx); // n^2 の計算
BN_mod_inverse(out, out, mod, ctx); // n^2 の逆元、つまり 1/n^2 を計算
// out が適切な値に!

n^(-2)1/n^2 として計算したらうまくいきました。

自分もわからないことだらけ(特に数学的に)なので、危うい情報ですがうまくいったのでメモしました。
mod の世界が故のナニカなのか。。
ただのBIGNUMの仕様なのか。。

用語ひっかけ:
負の指数
マイナスの指数
負の値
マイナスの値
べき乗

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?