下面是一个简单的C语言实现RSA加密算法的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int is_prime(int n) {
if (n <= 1)
return 0;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0)
return 0;
}
return 1;
}
int generate_prime() {
int p;
do {
p = rand() % 100 + 1;
} while (!is_prime(p));
return p;
}
int mod_exp(int base, int exp, int mod) {
int result = 1;
while (exp > 0) {
if (exp % 2 == 1)
result = (result * base) % mod;
base = (base * base) % mod;
exp /= 2;
}
return result;
}
int main() {
int p = generate_prime();
int q = generate_prime();
int n = p * q;
int phi = (p - 1) * (q - 1);
int e = 2;
while (gcd(e, phi) != 1) {
e++;
}
int d = 1;
while ((d * e) % phi != 1) {
d++;
}
printf("Public key: (%d, %d)\n", e, n);
printf("Private key: (%d, %d)\n", d, n);
int plaintext = 123;
int ciphertext = mod_exp(plaintext, e, n);
printf("Encrypted message: %d\n", ciphertext);
int decrypted_text = mod_exp(ciphertext, d, n);
printf("Decrypted message: %d\n", decrypted_text);
return 0;
}
此代码生成两个随机素数p和q,计算n和phi的值,选择一个公钥e和私钥d,然后使用公钥对明文进行加密,使用私钥对密文进行解密。请注意,此处的加密和解密仅用于示例目的,实际应用中应该使用更大的素数和更复杂的操作。