#include <stdio.h>
#include <stdlib.h>
#include <math.h>

// Função para calcular o MDC (Máximo Divisor Comum)
int mdc(int a, int b) {
    if (b == 0)
        return a;
    return mdc(b, a % b);
}

// Função para calcular o módulo inverso usando o algoritmo de Euclides estendido
int mod_inverse(int e, int phi) {
    int x0 = 0, x1 = 1, temp, quotient;
    int a = phi, b = e;
    
    while (b > 0) {
        quotient = a / b;
        temp = x1;
        x1 = x0 - quotient * x1;
        x0 = temp;
        
        temp = a;
        a = b;
        b = temp % b;
    }
    
    if (a == 1) {
        if (x0 < 0) {
            x0 += phi;
        }
        return x0;
    }
    
    return -1;  // Não encontrou o inverso
}

// Função para calcular o módulo φ(n)
int calculate_phi(int p, int q) {
    return (p - 1) * (q - 1);
}

// Função para gerar as chaves RSA (públicas e privadas)
void generate_keys(int p, int q, int e, int *n, int *d) {
    *n = p * q;
    int phi = calculate_phi(p, q);
    
    *d = mod_inverse(e, phi);
    
    if (*d == -1) {
        printf("Erro ao encontrar o inverso modular.\n");
        exit(1);
    }
}

// Função para criptografar um caractere usando RSA
int encrypt(int char_value, int e, int n) {
    long long int encrypted = 1;
    for (int i = 0; i < e; i++) {
        encrypted = (encrypted * char_value) % n;
    }
    return encrypted;
}

// Função para descriptografar um número usando RSA
int decrypt(int encrypted_value, int d, int n) {
    long long int decrypted = 1;
    for (int i = 0; i < d; i++) {
        decrypted = (decrypted * encrypted_value) % n;
    }
    return decrypted;
}

int main() {
    int p, q, e, n, d;
    printf("Digite os valores primos p e q:\n");
    scanf("%d %d", &p, &q);
    
    printf("Digite o valor de E (número público):\n");
    scanf("%d", &e);
    
    n = p * q;
    int phi = calculate_phi(p, q);
    
    // Verifica se E é coprimo com φ(n)
    if (mdc(e, phi) != 1) {
        printf("O número E não é coprimo com φ(n).\n");
        return 1;
    }
    
    generate_keys(p, q, e, &n, &d);
    
    printf("Chave pública (n, e): (%d, %d)\n", n, e);
    printf("Chave privada (n, d): (%d, %d)\n", n, d);
    
    char mensagem[100];
    printf("Digite a mensagem para criptografar:\n");
    scanf("%s", mensagem);
    
    printf("Mensagem criptografada:\n");
    for (int i = 0; mensagem[i] != '\0'; i++) {
        int char_value = mensagem[i] - 'A' + 11;  // Conversão de A=11
        int encrypted = encrypt(char_value, e, n);
        printf("%d ", encrypted);
    }
    
    printf("\n");

    // Descriptografar a mensagem
    printf("Mensagem descriptografada:\n");
    for (int i = 0; mensagem[i] != '\0'; i++) {
        int encrypted = (int) (mensagem[i] - 'A' + 11);  // Simulação dos valores criptografados
        int decrypted = decrypt(encrypted, d, n);
        char decrypted_char = (decrypted - 11) + 'A';  // Convertendo para o caractere original
        printf("%c", decrypted_char);
    }
    
    printf("\n");

    return 0;
}
 
by

C Language online compiler

Write, Run & Share C Language code online using OneCompiler's C online compiler for free. It's one of the robust, feature-rich online compilers for C language, running the latest C version which is C18. Getting started with the OneCompiler's C editor is really simple and pretty fast. The editor shows sample boilerplate code when you choose language as 'C' and start coding!

Read inputs from stdin

OneCompiler's C online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample C program which takes name as input and print your name with hello.

#include <stdio.h>
int main()
{
    char name[50];
    printf("Enter name:");
    scanf("%s", name);
    printf("Hello %s \n" , name );
    return 0;
    
}

About C

C language is one of the most popular general-purpose programming language developed by Dennis Ritchie at Bell laboratories for UNIX operating system. The initial release of C Language was in the year 1972. Most of the desktop operating systems are written in C Language.

Key features:

  • Structured Programming
  • Popular system programming language
  • UNIX, MySQL and Oracle are completely written in C.
  • Supports variety of platforms
  • Efficient and also handle low-level activities.
  • As fast as assembly language and hence used as system development language.

Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition if-else is used.

if(conditional-expression) {
   // code
} else {
   // code
}

You can also use if-else for nested Ifs and if-else-if ladder when multiple conditions are to be performed on a single variable.

2. Switch:

Switch is an alternative to if-else-if ladder.

switch(conditional-expression) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 // code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
  // code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(condition) {  
 // code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (condition); 

Arrays

Array is a collection of similar data which is stored in continuous memory addresses. Array values can be fetched using index. Index starts from 0 to size-1.

Syntax

One dimentional Array:

data-type array-name[size];

Two dimensional array:

data-type array-name[size][size];

Functions

Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity.

Two types of functions are present in C

  1. Library Functions:

Library functions are the in-built functions which are declared in header files like printf(),scanf(),puts(),gets() etc.,

  1. User defined functions:

User defined functions are the ones which are written by the programmer based on the requirement.

How to declare a Function

return_type function_name(parameters);

How to call a Function

function_name (parameters)

How to define a Function

return_type function_name(parameters) {  
  //code
}