+
+# calculate the multiplicative inverse of a mod b this is euclid's
+# extended algorithm. For more information see:
+# http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
+# arguments here should be Crypt::OpenSSL::Bignum objects. $a should
+# be the larger of the two values, and the two values should be
+# coprime.
+
+sub modular_multi_inverse {
+ my $a = shift;
+ my $b = shift;
+
+ my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
+ my $x = Crypt::OpenSSL::Bignum->zero();
+ my $y = Crypt::OpenSSL::Bignum->one();
+ my $lastx = Crypt::OpenSSL::Bignum->one();
+ my $lasty = Crypt::OpenSSL::Bignum->zero();
+
+ while (! $b->is_zero()) {
+ my ($quotient, $remainder) = $a->div($b, $ctx);
+
+ $a = $b;
+ $b = $remainder;
+
+ my $temp = $x;
+ $x = $lastx->sub($quotient->mul($x, $ctx));
+ $lastx = $temp;
+
+ $temp = $y;
+ $y = $lasty->sub($quotient->mul($y, $ctx));
+ $lasty = $temp;
+ }
+
+ if (!$a->is_one()) {
+ die "did this math wrong.\n";
+ }
+
+ return $lastx;
+}
+