c語言怎么實(shí)現(xiàn)rsa加密算法

小億
264
2024-02-20 09:48:34
欄目: 編程語言

下面是一個(gè)簡單的C語言實(shí)現(xiàn)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;
}

此代碼生成兩個(gè)隨機(jī)素?cái)?shù)p和q,計(jì)算n和phi的值,選擇一個(gè)公鑰e和私鑰d,然后使用公鑰對(duì)明文進(jìn)行加密,使用私鑰對(duì)密文進(jìn)行解密。請(qǐng)注意,此處的加密和解密僅用于示例目的,實(shí)際應(yīng)用中應(yīng)該使用更大的素?cái)?shù)和更復(fù)雜的操作。

0