c++文件简单加密

        简单加密方式为将要加密的文件,通过设置的密码加和计算一个值,将这个值与原始文件相加,并将初始的密码存入文件的前十个字节。

        解密为读取文件的前十个字节,加和,将加密值减和写入文件。

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
 
int encryption(const char * file_in,const char * file_out,char *sec);
int decrypt(const char * file_in,const char * file_out);
 
int main()
{
    string x;
    cout << "    1.加密     2.解密" << endl;
    cout << ">> ";
    cin >> x;
 
    if (x == "1")
    {
        encryption("src.zip","src.zip.in","positec001");
    }
    else if (x == "2")
    {
        decrypt("src.zip.in","src.zip");
    }
    else
    {
        cout << "请按照要求输入。。。。" << endl;
    }
    return 0;
}
 
int encryption(const char * file_in,const char * file_out,char *sec)
{
    fstream fp01,fp02;
    fp01.open(file_in, ios::in | ios::binary);
    if (fp01.fail())
    {
        cout << " 输入文件读取异常,请检查文件名是否有误";
        return -1;
    }
    fp02.open(file_out, ios::out | ios::binary);
    if (fp02.fail())
    {
        cout << "输出文件读取异常,请检查文件名是否有误";
        return -2;
    }
    size_t Size = strlen(sec);
    if(Size<10)
    {
        cout << "secret too short";
        return -3;
    }
    char ch_m = 0,ch=0;
    for(int i=0;i<10;i++)
    {
        fp02.write(&sec[i], 1);//将加密写入前十位
        ch_m+=sec[i];//累加结果
    }
    while (true)
    {
        fp01.read(&ch, 1);
        if (fp01.eof())
        {
            break;
        }
        ch=ch+ch_m;
        fp02.write(&ch, 1);
    }
    fp01.close();
    fp02.close();
    return 1;
}
 
int decrypt(const char * file_in,const char * file_out)
{
    fstream fp01(file_in, ios::in | ios::binary);
    if (fp01.fail())
    {
        cout << "输入文件读取异常,请检查文件名是否有误";
        return -2;
    }
    fstream fp02(file_out, ios::out | ios::binary);
    if (fp02.fail())
    {
        cout << "输出文件读取异常,请检查文件名是否有误";
        return -1;
    }
    char ch_m = 0,ch=0;
    for(int i=0;i<10;i++)
    {
        fp01.read(&ch, 1);//将加密写入前十位
        ch_m+=ch;//累加结果
    }
    while (true)
    {
        fp01.read(&ch, 1);
        if (fp01.eof())
        {
            break;
        }
        ch=ch-ch_m;
        fp02.write(&ch, 1);
    }
    fp01.close();
    fp02.close();
    return 1;
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值