cdiffie-hellman

I'm trying to recreate the Diffie-Hellman Key Exchange using addition but i get errors


#include<stdio.h>
#include<math.h>

long long int add(long long int a, long long int b,
        long long int G)
{
    if (b == 1)
        return a;

    else
        return (((long long int)(a + b)) % G);
}
int main()
{
    long long int G, x, a, y, b, ka, kb;



    G = 43; //the agreed number
    printf("The value of G : %lld\n\n", G);


    a = 23; //private key for a
    printf("The private key a for A : %lld\n", a);
    x = add(G, a); //gets the generated key


    b = 19; //private key for b
    printf("The private key b for B : %lld\n\n", b);
    y = add(G, b); // gets the generated key

    ka = add(y, a, G); // Secret key for a
    kb = add(x, b, G); // Secret key for b

    printf("Secret key for the A is : %lld\n", ka);
    printf("Secret Key for the B is : %lld\n", kb);

    return 0;
}

this is the flow of the code

THIS IS THE EXPECTED OUTPUT/FLOW OF THE PROGRAM but my code has problems i attached an image to show the problem.

A and B will agree upon a number

G = 43 is the agreed number

A will generate a private number a = 23

B will generate a private number b = 19

A will calculate G=43 + a=23 mod G=43 OR 43 + 23 mod 43 = 66 (let's call it x) x = 66

B will calculate G=43 + b=19 mod G=43 OR 43+19mod43 = 62 (let's call it y) y = 62

for A we get x = 66

for B we get y = 62

They will then exchange x and y

x = 66 will go to B

y = 62 will go to A

A will now calculate y + a mod G OR 62+23 mod 43 = 85 (secret number is ka) ka = 85

B will now calculate x + b mod G OR 66+19 mod 43 = 85 (secret number is kb) kb = 85

This is the error that I get


Solution

  • Your 'add' function is declared as taking 3 arguments

    long long int add(long long int a, long long int b, long long int G)
    

    but twice you try to call it only passing 2, here

    x = add(G, a); //gets the generated key
    

    and here

    y = add(G, b); // gets the generated key 
    

    reading the logic you posted those should be

    x = add(G, a, G); //gets the generated key
    

    and

    y = add(G, b, G); // gets the generated key