Untitled

 avatar
unknown
plain_text
a year ago
1.7 kB
5
Indexable
#include <openssl/bn.h>
#include <stdio.h>

void printBN(const char *msg, BIGNUM *a) {
    char *number_str = BN_bn2dec(a);
    printf("%s%s\n", msg, number_str);
    OPENSSL_free(number_str);
}

void diffie_hellman(long pval, long gval, long xaval, long xbval) {
    BN_CTX *ctx = BN_CTX_new();

    // Initialize the BIGNUMs
    BIGNUM *p = BN_new();
    BIGNUM *g = BN_new();
    BIGNUM *xa = BN_new();
    BIGNUM *xb = BN_new();
    BIGNUM *ya = BN_new();
    BIGNUM *yb = BN_new();
    BIGNUM *Kab_a = BN_new();
    BIGNUM *Kab_b = BN_new();

    // Assign values
    BN_set_word(p, pval);
    BN_set_word(g, gval);
    BN_set_word(xa, xaval);
    BN_set_word(xb, xbval);

    // Calculate ya = g^xa mod p
    BN_mod_exp(ya, g, xa, p, ctx);
    
    // Calculate yb = g^xb mod p
    BN_mod_exp(yb, g, xb, p, ctx);

    // Calculate the shared secret Kab from Alice's perspective = yb^xa mod p
    BN_mod_exp(Kab_a, yb, xa, p, ctx);
    
    // Calculate the shared secret Kab from Bob's perspective = ya^xb mod p
    BN_mod_exp(Kab_b, ya, xb, p, ctx);

    // Print results
    printBN("Alice's Public Key (ya): ", ya);
    printBN("Bob's Public Key (yb): ", yb);
    printBN("Shared Secret (Kab) as calculated by Alice: ", Kab_a);
    printBN("Shared Secret (Kab) as calculated by Bob: ", Kab_b);

    // Free memory
    BN_free(p);
    BN_free(g);
    BN_free(xa);
    BN_free(xb);
    BN_free(ya);
    BN_free(yb);
    BN_free(Kab_a);
    BN_free(Kab_b);
    BN_CTX_free(ctx);
}

int main() {
    printf("Task 1:\n");
    diffie_hellman(773, 2, 333, 603);
    
    printf("\nTask 2:\n");
    diffie_hellman(1553, 307, 1333, 807);

    return 0;
}
Editor is loading...
Leave a Comment