So, after all, i want to explain the method:
The ideia is to two persons exchange one value through a public channel of comunication without really sending it.
This is how this works:
https://en.wikipedia.org/wiki/Diffie-Hellman
This is my C# code:
double primemodulus = 251;
double generator = 11;
public string TestarGamaValores()
{
Random R = new Random();
double Alice = R.Next(1, 100); //alice exp
double AliceCalculado = DefaultMod(Alice);
double Bob = R.Next(1, 100); //bob exp
double BobCalculado = DefaultMod(Bob);
//Trocar os calculados entre eles
double ChaveFinalAlice = CalcularAposTroca(Alice, BobCalculado);
double ChaveFinalBob = CalcularAposTroca(Bob, AliceCalculado);
return ("Chave Final Alice: " + ChaveFinalAlice + " Chave Final Bob: " + ChaveFinalBob);
}
//Calculate after exchange
public double CalcularAposTroca(double MyExp, double HisResultFromHisModulus)
{
double genrt = Math.Pow(HisResultFromHisModulus, MyExp);
double Chave = genrt % primemodulus;
return Chave;
}
public double DefaultMod(double MyExp)
{
double genrt = Math.Pow(generator, MyExp);
double Chave = genrt % primemodulus;
return Chave;
}
the only problem is, i cant get the values to be the same. ive reaserched if the formula is ok, and i think i didnt get it wrong, but the C# code seems not to be agreeing.
the results are indeed between 0 and 251 but are always different.
so what am i doing wrong?
is the C# code ok?
I think your problem is that you are using double instead of long (integer values), since doubles are stored only as approximations to the real number you might get rounding errors. See also this post Why is modulus operator not working for double in c#?
If you are dealing with larger values you will have to use a Structure with arbitrary size like BigInteger
.