Untitled
unknown
plain_text
2 years ago
2.0 kB
17
Indexable
#include <openssl/bn.h>
#include <openssl/rand.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);
}
// Function to generate a random k
void generate_random_k(BIGNUM *k, BIGNUM *p, BN_CTX *ctx) {
// Generate a random number k where 1 < k < p-1
do {
if (!BN_rand_range(k, p)) {
// Handle error
printf("Error generating random k.\n");
exit(1);
}
} while (BN_is_zero(k) || BN_is_one(k)); // Ensure k is not 0 or 1
}
void elgamal_encrypt(long pval, long gval, long xval, long Mval) {
BN_CTX *ctx = BN_CTX_new();
// Initialize variables
BIGNUM *p = BN_new();
BIGNUM *g = BN_new();
BIGNUM *x = BN_new();
BIGNUM *M = BN_new();
BIGNUM *k = BN_new();
BIGNUM *C1 = BN_new();
BIGNUM *C2 = BN_new();
BIGNUM *y = BN_new(); // Public key
// Assign values
BN_set_word(p, pval);
BN_set_word(g, gval);
BN_set_word(x, xval);
BN_set_word(M, Mval);
// Generate a random k
generate_random_k(k, p, ctx);
// Calculate y = g^x mod p (Public key)
BN_mod_exp(y, g, x, p, ctx);
// Calculate C1 = g^k mod p
BN_mod_exp(C1, g, k, p, ctx);
// Calculate C2 = M * y^k mod p
BN_mod_exp(y, y, k, p, ctx); // y^k mod p
BN_mod_mul(C2, M, y, p, ctx); // M * y^k mod p
// Output
printBN("Random k: ", k);
printBN("C1: ", C1);
printBN("C2: ", C2);
// Cleanup
BN_free(p);
BN_free(g);
BN_free(x);
BN_free(M);
BN_free(k);
BN_free(C1);
BN_free(C2);
BN_free(y);
BN_CTX_free(ctx);
}
int main() {
printf("El-Gamal Encryption with Random k:\n");
elgamal_encrypt(773, 2, 333, 321); // Task 1
printf("\n");
elgamal_encrypt(6469, 5055, 2256, 4312); // Task 2
return 0;
}Editor is loading...
Leave a Comment