Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.1 kB
1
Indexable
Never
#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);
}

int main() {
    BN_CTX *ctx = BN_CTX_new();
    BIGNUM *n = BN_new();
    BIGNUM *e = BN_new();
    BIGNUM *M = BN_new();
    BIGNUM *phi_n = BN_new();
    BIGNUM *d = BN_new();
    BIGNUM *C = BN_new();

    // Set given values
    BN_set_word(n, 6887);
    BN_set_word(e, 143);
    BN_set_word(M, 1234);

    // Calculate phi(n) = (p-1)(q-1)
    BN_set_word(phi_n, 6724); // From Step 2

    // Calculate d, the modular multiplicative inverse of e mod phi(n)
    BN_mod_inverse(d, e, phi_n, ctx); // d = e^-1 mod phi(n)

    // Encrypt M to get C: C = M^e mod n
    BN_mod_exp(C, M, e, n, ctx);

    // Output the results
    printBN("Decryption key d: ", d);
    printBN("Ciphertext C: ", C);

    // Free memory
    BN_free(n);
    BN_free(e);
    BN_free(M);
    BN_free(phi_n);
    BN_free(d);
    BN_free(C);
    BN_CTX_free(ctx);

    return 0;
}
Leave a Comment