RSA算法的c++实现(简化版)

#include
#include
using namespace std;


//encrypt
void encrypt(char *str,int pk,int n,int *a1){
    int i=0;
    while(1){
            if(str[i]>='a'&&str[i]<='z'){
                str[i]=str[i]-97;//97
            }
            if(str[i]>='A'&&str[i]<='Z'){
                str[i]=str[i]-65;//65
            }
            if(str[i]=='#'){
                break;
            }
            int b=pow((int)str[i],(float)pk);
            a1[i]=b%n;
            i++;
        }
}


//decipher
void decipher(char* str,int sk,int n,int* a2,int& length){
            for(int i=0;iint b=pow(a2[i],(float)sk);
            str[i]=char((b%n)+97);          
    }
        str[length]='#';
}


int main(){
    int p,q,sk,pk,r,i,length;
    char str1[100],str2[100];
    int a1[100]={0},a2[100]={0};
    cout<<"please input two different prime:"<cin>>p>>q;
    int n=p*q;
    int M=(p-1)*(q-1);
    cout<<"please input sk,sk<"<cin>>sk;
    cout<<"please input pk,pk=sk^(-1)mod"<cin>>pk;
    cout<<"choose encrypt(input 1) or decipher(input 2)"<cin>>r;
    switch(r){
        case 1:
            cout<<"please input your plaintext!(end with '#')"<while(1){
                str1[i]=getchar();
                if(str1[i]=='#'){
                    break;
                }
                i++;
            }
            encrypt(str1,pk,n,a1);
            cout<<"the ciphertext is:"<for(int j=0;jcout<"\t";
            }
            break;
        case 2:
            cout<<"please input the length of your ciphertext!"<cin>>length;
            cout<<"please input your ciphertext!"<for(i=0;icin>>a2[i];
            }
            decipher(str2,sk,n,a2,length);
            cout<<"the plaintext is:"<for(i=0;i<=length;i++){
                if(str2[i]=='#')
                    break;
                cout<"\t";
            }
            break;
        default:
            break;
    }
    Sleep(100000);
    return 0;
}

你可能感兴趣的:(算法)