Question Link
Question: Give You N, E, C, and know me ≡ C (mod n), and n = p * q, PQ are prime numbers.
Idea: This question is indeed consistent with the question name. It is an RSA algorithm. Currently, the most important encryption algorithm on the earth. The principle of the RSA algorithm.
After seeing this algorithm, we will know that this question is to find CD ≡ M (mod n). If M is required, we need to first find D, and D is the modulo antielement of E.
If the two positive integers A and n are mutually correlated, we can find the integer B so that AB-1 is divisible by N, or the remainder of AB by N is 1. In this case, B is called the modulo antielement of.
It can be seen from the modulo antielement that Ed kernel 1 (mod Phi [N]) (PHI [N] represents the Euler's function of N ).
According to the nature of Euler's function, Phi [N] = (p-1) * (q-1 ).
To evaluate the inverse element D of E, we need to use Extended Euclidean. ed + K * Phi [N] = 1. Pay attention to the negative number of D.
In the end, we need to use the Fast Power modulo to find the CD, and then mod n is the M.
#include <stdio.h>#include <string.h>#include <iostream>typedef long long LL ;using namespace std ;bool isprime(int n){ for(int i = 2 ; i * i <= n ; i++) { if(n % i == 0) return false ; } return true ;}int multimod(int a,int n,int m){ int tmp = a , res = 1 ; while(n) { //printf("11\n") ; if(n & 1) { res *= tmp ; res %= m ; } tmp *= tmp ; tmp %= m ; n >>= 1 ; //printf("%d\n",n) ; } return res ;}void exde(int a,int b,int &x,int& y){ int t ; if(b == 0) { x = 1 ; y = 0 ; return ; //return a; } exde(b,a%b,x,y) ; t = x ; x = y ; y = t-(a/b)*y; //return d ;}int main(){ int T ,e,c,n; scanf("%d",&T) ; while(T--) { scanf("%d %d %d",&e,&n,&c) ; int p,q ,x,y; //printf("1\n"); for(int i = 2 ; i * i <= n ; i++) { if((n % i == 0) && isprime(i) && isprime(n / i)) { p = i ; q = n / i ; break ; } } //printf("p = %d q = %d\n",p,q) ; exde(e,(p-1)*(q-1),x,y); //printf("%d %d\n",p,q) ; int d = x ; //printf("%d\n",d+(p-1)*(q-1)) ; if(d < 0) d = (d+(p-1)*(q-1)) %((p-1)*(q-1)) ; //printf("%d\n",d) ; int ans = multimod(c,d,n) ; printf("%d\n",ans) ; } return 0 ;}
View code
Ural 1141. RSA attack (Euler's theorem + Extended Euclidean + fast idempotent)