Untitled
unknown
plain_text
10 months ago
1.8 kB
4
Indexable
#include <stdio.h>
// Function to calculate gcd
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
// Function to calculate (base^exp) % mod
int modular_exponentiation(int base, int exp, int mod) {
int result = 1;
base = base % mod;
while (exp > 0) {
if (exp % 2 == 1) { // If exp is odd
result = (result * base) % mod;
}
exp = exp / 2; // Divide exp by 2
base = (base * base) % mod;
}
return result;
}
int main() {
// Step 1: Choose two prime numbers p and q
int p = 11, q = 13; // Prime numbers
int n = p * q; // Compute n
int phi = (p - 1) * (q - 1); // Compute Euler's totient function
printf("Phi(n) = %d \n", phi);
// Step 2: Choose public key exponent e such that gcd(e, phi) = 1
int e = 7; // A simple choice for e
while (gcd(e, phi) != 1) {
e++; // Increment e until gcd(e, phi) = 1
}
// Step 3: Find private key d such that (e * d) % phi = 1
int d = 1;
while ((e * d) % phi != 1) {
d++; // Increment d until the condition is met
}
// Display keys
printf("Public Key: (e = %d, n = %d)\n", e, n);
printf("Private Key: (d = %d, n = %d)\n", d, n);
// Step 4: Encrypt a message (plaintext)
int plaintext = 9; // Changed plaintext value
if (plaintext < 0 || plaintext >= n) {
printf("Error: Plaintext must be in the range 0 <= plaintext < n.\n");
return 1;
}
int ciphertext = modular_exponentiation(plaintext, e, n);
printf("Plaintext: %d\n", plaintext);
printf("Encrypted Ciphertext: %d\n", ciphertext);
// Step 5: Decrypt the message
int decrypted = modular_exponentiation(ciphertext, d, n);
printf("Decrypted Plaintext: %d\n", decrypted);
return 0;
}Editor is loading...
Leave a Comment