#include <stdio.h>
#include <stdbool.h>
#define PRIME_TABLE_SIZE 1024
typedef unsigned long long bigNum;
bigNum primes[PRIME_TABLE_SIZE];
bigNum primes_size = 0;
bool is_prime(bigNum num) {
if (num < 2) return false;
for (bigNum i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}
void get_primes(bigNum start, bigNum count) {
while (count > 0) {
if (is_prime(start)) {
primes[primes_size++] = start;
count--;
}
start++;
}
}
bigNum gcd(bigNum a, bigNum b) {
bigNum m;
while ((m = a % b) != 0) {
a = b;
b = m;
}
return b;
}
bigNum get_e(bigNum phi) {
for (bigNum i = (rand() % (phi - 1)) + 1; i < phi; i++) {
if (gcd(phi, i) == 1) return i;
}
return 1; // Default fallback
}
bigNum get_d(bigNum phi, bigNum e) {
bigNum d = 1;
while ((d * e - 1) % phi != 0) {
d++;
}
return d;
}
bigNum mod_pow(bigNum base, bigNum exp, bigNum n) {
bigNum result = 1;
bigNum y = base % n;
while (exp > 0) {
if (exp & 1) {
result = (result * y) % n;
exp--;
}
y = (y * y) % n;
exp >>= 1;
}
return result;
}
void rsa_encrypt(const char* text, bigNum e, bigNum n, bigNum* cypher, bigNum* cypher_size) {
for (bigNum i = 0; text[i] != '\0'; i++) {
cypher[(*cypher_size)++] = mod_pow((bigNum)text[i], e, n);
}
}
void rsa_decrypt(const bigNum* cypher, bigNum d, bigNum n, char* decrypt, bigNum* decrypt_size) {
for (bigNum i = 0; i < *decrypt_size; i++) {
decrypt[i] = (char)mod_pow(cypher[i], d, n);
}
decrypt[*decrypt_size] = '\0'; // Null-terminate the string
}
int main() {
bigNum start = 2;
bigNum count = 1024;
get_primes(start, count);
for (bigNum i = 0; i < primes_size; i++) {
printf("%llu ", primes[i]);
}
printf("\n");
bigNum p = primes[primes_size / 3];
bigNum q = primes[primes_size - primes_size / 3];
bigNum n = p * q;
bigNum phi = (p - 1) * (q - 1);
bigNum e = get_e(phi);
bigNum d = get_d(phi, e);
printf("p: %llu q: %llu n: %llu phi: %llu e: %llu d: %llu\n", p, q, n, phi, e, d);
printf("pk=(e=%llu, n=%llu)\n", e, n);
printf("sk=(d=%llu, n=%llu)\n", d, n);
const char* plaintext = "chenjintao2107010309";
bigNum cypher[100];
bigNum cypher_size = 0;
rsa_encrypt(plaintext, e, n, cypher, &cypher_size);
printf("Cypher: ");
for (bigNum i = 0; i < cypher_size; i++) {
printf("%llu ", cypher[i]);
}
printf("\n");
char decrypt[100];
bigNum decrypt_size = cypher_size;
rsa_decrypt(cypher, d, n, decrypt, &decrypt_size);
printf("Decrypted: %s\n", decrypt);
return 0;
}
自用RSA算法
最新推荐文章于 2024-08-31 15:34:19 发布