Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

you are using double which is a floating point number for something that is mathematicaly not defined for floating point numbers ... the modulo operator ...

i suggest using arbitrary precision integers like BigInteger

I appreciate that You are going to implement the Diffie-Hellman algorithm idea, but for everyone who are looking for a solution I can tell that there is no need to discover the circle again.

The Diffie-Hellman secret key exchange protocol is already implemented here:

System.Security.Cryptography.ECDiffieHellmanCng 

and there is a link to great example of usage: http://msdn.microsoft.com/en-us/library/system.security.cryptography.ecdiffiehellmancng(v=vs.110).aspx

Pay attention to measure the performance of the solution in Your environment before deploy. Process of generation PublicKey takes up to 40ms on my Intel Core I5. :-(

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top