Demo entry 6686972

7

   

Submitted by 环境 on Dec 25, 2017 at 16:24
Language: C. Code size: 2.3 kB.

#include <iostream>
#include <NTL/ZZ.h>
#include <gmp.h>
#include <fstream>
#include <math.h>
using namespace std;
using namespace NTL;
ZZ gcd(ZZ a,ZZ b)
{
    if(b==0)
        return a;
    else
        return gcd(b,a%b);
}
int mod(int a,int b){
    int n=0,res=0;
    n=a/b;
    res=a-n*b;
    return res;
}
ZZ Mod(ZZ a,ZZ b){
    ZZ n;n=0;
    ZZ res;res=0;
    n=a/b;
    res=a-n*b;
    return res;
}
int Pow_mod(int a,int b,int c){
    int res=1;
    if(b!=0){
        int 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<<","<<n<<")"<<endl;
}
void Key_Decryption(int K[64]){
    int KE[64],d=0,n=0;
    cout<<"开始对K进行解密:"<<endl;
    cout<<"请输入私钥对:";
    cin>>d>>n;
    cout<<"请输入K的密文:"<<endl;
    int i=0;
    for(i=0;i<64;i++)cin>>KE[i];
    for(i=0;i<64;i++)K[i]=Pow_mod(KE[i],d,n)-i;
}
void File_decryption(int K[64]){
    ifstream infile("/Users/apple/Desktop/密码学第三次实验/c_text.txt");
    ofstream outfile("/Users/apple/Desktop/密码学第三次实验/p1_text.txt");
    int i=0,j=0;
    int k[8];
    cout<<"请输入密码加密密钥k:";
    for(i=0;i<8;i++)cin>>k[i];
    int cipher;
    while (!infile.eof()){
        infile>>cipher;
        if(infile.eof())break;
        int Left[28],Right[28];
        for(i=0;i<28;i++)Right[i]=K[i];
        for(i=28,j=0;i<56&&j<28;i++,j++)Left[j]=K[i];
        int eight[8];
        for(i=0;i<8;i++)eight[i]=k[i]^Left[i];
        for(i=0;i<56;i++)K[i]=K[i+8];
        for(i=56,j=0;i<64&&j<8;i++,j++)K[i]=eight[j];
        int res=0;
        for(i=0;i<8;i++){
            if(eight[i]!=0)res=res+pow(2,7-i);
        }
        int C;
        C=res^cipher;
        char c;
        c=C;
        outfile<<c;
    }
    infile.close();
    cout<<"文件解密完成."<<endl;
}
int main(void){
    int K[64];
    Key_generation();
    Key_Decryption(K);
    File_decryption(K);
    return 0;
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).