仿射密码加密解密文件流

#include<iostream>
#include<string>
#include<fstream>
#include<Windows.h>
using namespace std;
class PWoper
{
    string inpatch;
    string outpatch;
public:
    PWoper(string in, string out)
    {
        inpatch = in;
        outpatch = out;
    }
    void encrypt()
    {
        ifstream init(inpatch, ios::binary);
        ofstream outit(outpatch, ios::binary);
        if (!init || !outit)
        {
            cout << "IN ERROR OR OUT ERROR!" << endl;
        }
        int *initp = new int();
        int *outitp = new int();
        while (init.read((char*)initp, 1)){
            //cout << *initp << endl;
            *outitp = (*initp * 177 + 135) % 311;
            //cout << "out--"<<*outitp << endl;

            //一个字节8位,最大256;这里的 "*outitp mod 311" 数值最大311,如果以1个字读进来运算以后write装不下。
            outit.write((char*)outitp, 2);
        }
        cout << "encrypt success!\n";
        init.close();
        outit.close();
        //delete original data
        
        string temp = "del ";
        temp += inpatch;
        //system命令只接受一个参数,以下代码实现system("del 变量")。
        const char *link = temp.data();
        system(link);
    }
    void decrypt()
    {
        ofstream init(inpatch, ios::binary);
        ifstream outit(outpatch, ios::binary);
        if (!init || !outit)
        {
            cout << "IN ERROR OR OUT ERROR!" << endl;
        }
        int *ini = new int();
        int *outi = new int();
        while (outit.read((char*)outi, 2)){
            //cout << *outi << endl;
            *ini = ((*outi - 135 + 311) * 123) % 311;
            //cout <<"out"<< *ini <<endl;

            //
            init.write((char*)ini, 1);
        }
        cout << "decrypt success!\n";
        init.close();
        outit.close();
    }
};
int main()
{

    string inpatch, outpatch, str;
    cout << "input InPtach: ";
    cin >> inpatch;
    cout << "input OutPatch: ";
    cin >> outpatch;
    PWoper pwoper(inpatch, outpatch);
    pwoper.encrypt();
    cout << "input ok to decrypt: ";
    cin >> str;
    //system("cls");
    if (str == "ok")
        pwoper.decrypt();
    else {
        cout << "input error!";
        system("pause");
    }
    system("pause");

}

 

posted @ 2015-01-05 12:19  remly  阅读(520)  评论(0编辑  收藏  举报