Demo entry 6684551

123

   

Submitted by 123 on Dec 16, 2017 at 04:01
Language: C++. Code size: 1.9 kB.

#include <iostream>
#include <NTL/ZZ.h>
#include <gmp.h>
using namespace std;
using namespace NTL;
ZZ gcd(ZZ a,ZZ b){
    if(b==0)return a;
    else return gcd(b,a%b);
}
ZZ mod(ZZ a,ZZ b){
    ZZ n,res;
    n=0;res=0;
    n=a/b;
    res=a-n*b;
    return res;
}
ZZ pow_mod(ZZ a,ZZ b,ZZ c){
    ZZ res;
    res=1;
    if(b!=0){
        ZZ i;i=0;
        for(i=b;i>0;i--)res=mod(res*a,c);
    }
    return res;
}
void Key_generation(void){
    ZZ p,q,n,l,e,d;p=0;q=0;n=0;l=0;e=0;d=0;
    cout<<"开始生成密钥:"<<endl;
    cout<<"请输入p,q的值:";
    cin>>p>>q;
    n=p*q;
    l=(p-1)*(q-1);
    ZZ i;i=1;
    for(i=2;i<l&&e==0;i++){
        if(gcd(i,l)==1)e=i;
    }
    for(i=2;i<l&&d==0;i++){
        if(mod((i*e),l)==1)d=i;
    }
    cout<<"公钥对为("<<e<<","<<n<<")"<<endl;
    cout<<"私钥为("<<d<<","<<p<<","<<q<<")"<<endl;
}
void Encrypt(void){
    ZZ e,n;e=0;n=0;
    cout<<"请输入公钥对:";
    cin>>e>>n;
    ZZ plain[100];
    int i=0;
    for(i=0;i<100;i++)plain[i]=0;
    cout<<"请输入明文:";
    for(i=0;;i++){
        cin>>plain[i];
        if(getchar()=='\n')
            break;
    }
    ZZ cipher[100];
    for(i=0;i<100;i++)cipher[i]=0;
    for(i=0;plain[i]!=0;i++)cipher[i]=pow_mod(plain[i],e,n);
    cout<<"密文为:";
    for(i=0;cipher[i]!=0;i++)cout<<cipher[i]<<" ";
    cout<<endl;
}
void Decrypt(void){
    ZZ d,p,q;d=0;p=0;q=0;
    cout<<"请输入私钥:";
    cin>>d>>p>>q;
    ZZ cipher[100];
    int i=0;
    for(i=0;i<100;i++)cipher[i]=0;
    cout<<"请输入密文:";
    for(i=0;;i++){
        cin>>cipher[i];
        if(getchar()=='\n')
            break;
    }
    ZZ plain[100];
    for(i=0;i<100;i++)plain[i]=0;
    for(i=0;cipher[i]!=0;i++)plain[i]=pow_mod(cipher[i],d,p*q);
    cout<<"明文为:";
    for(i=0;plain[i]!=0;i++)cout<<plain[i]<<" ";
    cout<<endl;
}
int main(void)
{
    Key_generation();
    Encrypt();
    Decrypt();
    return 0;
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).