RSA加密解密算法

这篇博客介绍了RSA加密算法的工作原理,包括选择两个大素数p和q,计算n和F(n),选择公钥e和私钥d的步骤。还给出了加密公式C = E(m) = me mod n以及解密公式M = D(c) = cd mod n。通过示例展示了如何使用给定的p、q、e和密文来解密数据,并提供了一个C++实现的代码片段用于将密文转换回明文。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description

RSA is one of the most powerful methods to encrypt data. The RSA algorithm is described as follow:

> choose two large prime integer p, q
> calculate n = p × q, calculate F(n) = (p - 1) × (q - 1)
> choose an integer e(1 < e < F(n)), making gcd(e, F(n)) = 1, e will be the public key
> calculate d, making d × e mod F(n) = 1 mod F(n), and d will be the private key

You can encrypt data with this method :

C = E(m) = me mod n

When you want to decrypt data, use this method :

M = D(c) = cd mod n

Here, c is an integer ASCII value of a letter of cryptograph and m is an integer ASCII value of a letter of plain text.

Now given p, q, e and some cryptograph, your task is to "translate" the cryptograph into plain text.

 

Input

Each case will begin with four integers p, q, e, l followed by a line of cryptograph. The integers p, q, e, l will be in the range of 32-bit integer. The cryptograph consists of l integers separated by blanks. 

 

Output

For each case, output the plain text in a single line. You may assume that the correct result of plain text are visual ASCII letters, you should output them as visualable letters with no blank between them.

 

Sample Input

101 103 7 11
7716 7746 7497 126 8486 4708 7746 623 7298 7357 3239

 

Sample Output

I-LOVE-ACM.

 

 

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
 int i,d,p,q,l,e;
 long n,f;
 long a,A;
 while(cin >> p >> q >> e >> l)
 {
  n=p*q;
  f=(p-1)*(q-1);
  d=1;
  while(d*e%f!=1)
  {
   d++;                    //找出d*e除以f余数为1时候的d的值
  }
  while(l>0)
  {
   cin >> a;
   A=1;
   for(i=1;i<=d;i++)   //即找出A== a^d mod n中的  A
   {
    A=(A*a)%n;
   }
   cout << char(A);//输出A的ACSLL形式的
   l--;
  }
  cout << endl;

 }
 return 0;
}

 

 

RSA算法 :它是第一个既能用于数据加密也能用于数字签名的算法。它易于理解和操作,也很流行。算法的名字以发明者的名字命名:Ron Rivest, Adi Shamir 和Leonard Adleman。但RSA的安全性一直未能得到理论上的证明。它经历了各种攻击,至今未被完全攻破。 
  
首先, 找出三个数, p, q, r, 其中 p, q 是两个相异的质数, e是与 (p-1)(q-1) 互质的数...... p, q, e 这三个数便是 private key  接著, 找出 d, 使得 d*e == 1 mod (p-1)(q-1)..... 注:意思是e*d除以(p-1)(q-1)的余数=1这个 d 一定存在, 因为 e与 (p-1)(q-1) 互质, 用辗转相除法就可以得到了..... 再来, 计算 n = pq....... d, n 这两个数便是 public key  编码过程是, 若资料为 a, 将其看成是一个大整数, 假设 a < n.... 如果 a >= n 的话, 就将 a 表成 s 进位 (s <= n, 通常取 s = 2^t), 则每一位数均小於 n, 然后分段编码...... 接下来, 计算 b == a^d mod n, (0 <= b < n), 注:^表示次方,不要理解为C#中的XORb 就是编码后的资料......  解码的过程是, 计算 c == b^e mod n (0 <= c < pq), 於是乎, 解码完毕......  c 和 a 其实是相等的  :)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值