Demo entry 6686973

34

   

Submitted by 343 on Dec 25, 2017 at 16:27
Language: C. Code size: 1.9 kB.

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <math.h>
#include <time.h>
using namespace std;
int mod(int a,int b){
    int n=0,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 K_generation(int K[64]){
    srand(unsigned(time(NULL)));
    int i=0;
    for(i=0;i<64;i++)K[i]=rand()%2;
    cout<<"随机生成的K为:"<<endl;
    for(i=0;i<64;i++)cout<<K[i]<<" ";
    cout<<endl;
}
void Key_encryption(int K[64]){
    int EK[64],e=0,n=0;
    cout<<"开始对K进行加密:"<<endl;
    cout<<"请输入公钥对:";
    cin>>e>>n;
    int i=0;
    for(i=0;i<64;i++)EK[i]=Pow_mod(K[i]+i,e,n);
    cout<<"加密后的K为:"<<endl;
    for(i=0;i<64;i++)cout<<EK[i]<<" ";
    cout<<endl;
}
void File_encryption(int K[64]){
    ifstream infile("/Users/apple/Desktop/密码学第三次实验/p_text.txt");
    ofstream outfile("/Users/apple/Desktop/密码学第三次实验/c_text.txt");
    srand(unsigned(time(NULL)));
    int i=0,j=0;
    int k[8];
    for(i=0;i<8;i++)k[i]=rand()%2;
    cout<<"密码加密密钥k为:";
    for(i=0;i<8;i++)cout<<k[i]<<" ";
    char c;
    while (!infile.eof()){
        infile>>c;
        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^c;
        outfile<<C<<" ";
    }
    infile.close();
    cout<<endl;
    cout<<"文件加密完成."<<endl;
}
int main(void)
{
    int K[64];
    K_generation(K);
    Key_encryption(K);
    File_encryption(K);
    return 0;
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).