Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.5 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h> // for srand, rand, and other standard library functions
#include <time.h>    // for time

// Function prototypes
void el_gamal_encrypt(int p, int g, int xa, int M, int *C1, int *C2);
int modular_exponentiation(int base, int exponent, int modulus);

// El-Gamal encryption function (defined after main)
void el_gamal_encrypt(int p, int g, int xa, int M, int *C1, int *C2) {
  // Seed the random number generator (improves randomness)
  srand(time(NULL));

  // Generate random value k
  int k = rand(); // Generate a random positive integer

  // Calculate C1 = g^k mod p
  *C1 = modular_exponentiation(g, k, p);

  // Calculate C2 = (M * ya^k) mod p
  *C2 = (M * modular_exponentiation(xa, k, p)) % p;
}

// Function to compute modular exponentiation (defined after main)
int modular_exponentiation(int base, int exponent, int modulus) {
  int result = 1;
  base = base % modulus;
  while (exponent > 0) {
    if (exponent % 2 == 1)
      result = (result * base) % modulus;
    exponent = exponent >> 1;
    base = (base * base) % modulus;
  }
  return result;
}

int main() {
  // Parameters
  int p = 773;  // Prime number
  int g = 2;    // Primitive root
  int xa = 333; // Alice's secret key
  int M = 321;  // Plaintext message

  // Variables to store ciphertext
  int C1, C2;

  // Perform El-Gamal encryption
  el_gamal_encrypt(p, g, xa, M, &C1, &C2);

  // Output ciphertext
  printf("Ciphertext (C1, C2): (%d, %d)\n", C1, C2);

  return 0;
}
Leave a Comment