Ниже приведен пример кода шифрования и дешифрования RSA (Ривест-Шамир-Адлеман) на языке C:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
long int gcd(long int a, long int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
long int encrypt(long int message, long int e, long int n) {
long int cipher = 1;
for (int i = 0; i < e; i++)
cipher = (cipher * message) % n;
return cipher;
}
long int decrypt(long int cipher, long int d, long int n) {
long int message = 1;
for (int i = 0; i < d; i++)
message = (message * cipher) % n;
return message;
}
int main() {
long int p, q, n, phi, e, d, message, cipher, decrypted_message;
printf("Enter two prime numbers (p and q): ");
scanf("%ld %ld", &p, &q);
n = p * q;
phi = (p - 1) * (q - 1);
for (e = 2; e < phi; e++) {
if (gcd(e, phi) == 1)
break;
}
for (d = 2; d < phi; d++) {
if ((d * e) % phi == 1)
break;
}
printf("Enter a message to encrypt: ");
scanf("%ld", &message);
cipher = encrypt(message, e, n);
printf("Encrypted message: %ld\n", cipher);
decrypted_message = decrypt(cipher, d, n);
printf("Decrypted message: %ld\n", decrypted_message);
return 0;
}
Этот код демонстрирует базовую реализацию шифрования и дешифрования RSA на языке C. Он генерирует пару простых чисел (p и q), вычисляет модуль (n) и функцию Эйлера (phi), выбирает показатель степени открытого ключа ( e) и экспоненту закрытого ключа (d) и выполняет операции шифрования и дешифрования с использованием алгоритма RSA.