## Blue Bridge Cup 2019 RSA encryption (fast power ride fast multiplicative inverse of Euler's theorem)

RSA is a classic encryption algorithms. Its basic encryption process is as follows.

First generating two prime numbers p, q n = p⋅q so disposed and d (p-1) * (q -1) prime can be found e d⋅e except that (p-1) ⋅ (q -1 ) a remainder of 1.
n-, D, E make up the private key, n, d composed of the public key.

When using a public key to encrypt a integer X (less than n), calculated C = X ^ d mod n, then C is encrypted ciphertext.

Upon receipt of the ciphertext C, you can use the private key to unlock, calculated as X = C ^ e mod n.
For example, when p = 5, q = 11, d = the time 3, n = 55, e = 27.

If the encryption numeral 24, to give 24 ^ 3mod55 = 19.

19 decrypts the digital to give 19 ^ 27 mod 55 = 24.

Now that you know the public key n = 1001733993063167141, d = 212353. At the same time you intercepted ciphertext C = 20,190,324 people sent to ask, how much is original?

E can be calculated as long as the original is obtained.

First calculate d, the good demand.

Let k = (p-1) * (q-1).

Release of the questions is then: d * e = 1 (mod k).

About inverse element d k is e, it is converted to the title find the inverse element d.

Known by the Euler's theorem, d is the inverse element d ^ (φ (k) -1).

Then according to the formula X = C ^ e (modn) is obtained.

``````#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

ll fast_mul(ll p,ll q,ll mod){      //计算p*q
ll ret=0;
p%=mod; q%=mod;
while(q>0){
if(q&1)
ret=(ret+p)%mod;

q>>=1;
p=(p+p)%mod;

}
return ret;
}

ll pow_mod(ll a,ll p,ll mod){      //计算a^p
ll ret=1;
a%=mod;
while(p>0){
if(p&1)
ret=fast_mul(ret,a,mod);

p>>=1;
a=fast_mul(a,a,mod);
}
return ret;
}

ll euler_phi(ll n){
ll m=sqrt(n+0.5);
ll ans=n;
for(int i=2;i<=m;i++)
if(n%i==0){
ans=ans/i*(i-1);
while(n%i==0) n/=i;
}
if(n>1) ans=ans/n*(n-1);
return ans;
}

ll get_zhishu(ll x){
for(int i=2;i<=x;i++){
if(x%i==0)
return i;
}
}

int main(){

ll n=1001733993063167141;
ll d=212353;
ll C=20190324;

ll p=get_zhishu(n);
printf("p的值为%lld\n",p);
ll q=n/p;
printf("q的值为%lld\n",q);

ll k=(p-1)*(q-1);
printf("k的值为%lld\n",k);

ll ans=euler_phi(k);
printf("phi(k)的值为%lld\n",ans);
ll e=pow_mod(d,ans-1,k);
printf("e的值为%lld\n",e);
printf("C^e的值为%lld",pow_mod(C,e,n));

}
``````

Published 57 original articles · won praise 58 · views 606

### Guess you like

Origin blog.csdn.net/weixin_43568895/article/details/103980462
Recommended
Ranking
Daily