0

If I know parameter a, k and p then how do I calculate this in C#?

s=a*k^-1 mod p

Its for cryptographic purpose and I'm new. Please don't feel offended if the question is not appropriate.

Please note that k^-1 is the modular inverse of k (mod p) and not power operator.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Milon Sarker
  • 478
  • 8
  • 25

2 Answers2

2

Since the question is about modular inverse, I suppose it will benefit the seeker to look at another SO question.

Crux of the answer is -

Net 4.0+ implements BigInteger with a special modular arithmetics function ModPow (which produces “X power Y modulo Z”), you don't need a third-party library to emulate ModInverse. If m is a prime, all you need to do is to compute:

In C# as per MSDN documentation this is defined as

public static BigInteger ModPow(
    BigInteger value,
    BigInteger exponent,
    BigInteger modulus
)

Using this we can do something like to calculate inverse of the k modulo p like

BigInteger bi= ModPow(k, -1, p );
int b= (int) bi;
s= (a* bi )%p;
Community
  • 1
  • 1
DhruvJoshi
  • 17,041
  • 6
  • 41
  • 60
  • 1
    using `ModPow(k, -1, p )` will cause an `ArgumentOutOfRangeException` to be thrown indicating that `exponent is negative`. [BigInteger.ModPow Method Exceptions](https://msdn.microsoft.com/en-us/library/system.numerics.biginteger.modpow(v=vs.110).aspx#Anchor_1) – Etor Madiv Apr 23 '17 at 16:30
-4

public static double DoMath(double a, double k, double p)

    {
        return (a * Math.Pow(k, -1)) % p;
    }
Bogdan Banciu
  • 169
  • 1
  • 6