夢的開始——RSA

qq_45717538發表於2020-10-19

題解

RSA的基本演算法,運用快速冪求出來每個數個d次方求餘於n,對應到字母表的每一個字元

程式碼

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<map>
using namespace std;
#define N 1000000
int pp[N],pri[N],tot,m;
char A[N] = {"abcdefghijklmnopqrstuvdxyz"};
char C[N] = {"0156 0821 1616 0041 0140 2130 1616 0793"};
int B[N];
int n = 2537, e = 13, d = 937, q, p;
int init_prim()
{
    for (int i = 2; i <= 100;i++){
        if(pp[i]==0){
            tot++;
            pri[tot] = i;
        }
        for (int j = 1; j <= tot&&i*pri[j]<=100;j++){
            int t = pri[j];
            pp[t * i] = 1;
            if(i%t==0)
                break;
        }
    }
}
void get_pq(){
    for (int i = 1; i <= tot;i++){
        int t = pri[i];
        if((n%t)==0){
            p = t;
            q = n / t;
            break;
        }
    }
}
int init()
{
    int tt = strlen(C);
    for (int i = 0; i < tt;i++){
        if(C[i]!=' '){
            B[m] = C[i] - '0';
            m++;
        }
    }
}
int pow(int a,int b){
    int temp = a;
    int ans=1;
    while(b){
        if(b&1){
            ans *= temp;
            ans %= n;
        }
        temp *=temp;
        temp %= n;
        b >>= 1;
    }
    return ans;
}
int main(){
    init();
    init_prim();
    get_pq();
    for (int i = 0; i < m;i+=4){
        int t = i,k=0,m=1000;
        int sum = 0;
        while(k<4){
            sum += B[i + k]*m;
            m /= 10;
            k++;
        }
        //cout << sum << " ";
        char c = pow(sum, d);
        cout <<A[c];

    }
}

相關文章