Untitled

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

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

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

    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();

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

    BN_mod_exp(ya, g, xa, p, ctx);
    BN_mod_exp(yb, g, xb, p, ctx);
    BN_mod_exp(Kab_a, yb, xa, p, ctx);
    BN_mod_exp(Kab_b, ya, xb, p, ctx);

    printBN_hex("Alice's Public Key (ya) in Hex: ", ya);
    printBN_hex("Bob's Public Key (yb) in Hex: ", yb);
    printBN_hex("Shared Secret (Kab) as calculated by Alice in Hex: ", Kab_a);
    printBN_hex("Shared Secret (Kab) as calculated by Bob in Hex: ", Kab_b);

    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 with Hex Output:\n");
    diffie_hellman_hex(773, 2, 333, 603);
    
    printf("\nTask 2 with Hex Output:\n");
    diffie_hellman_hex(1553, 307, 1333, 807);

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