简单文件加密解密

1. 异或运算

二进制运算符^对两个操作数逐位进行比较。对于每个位,如果操作数中的对应位有一个为1(但是不都为1),那么结果为1(用真/假来描述,如果两个两个操作数中有一个为真,但不都为真,那么结果为真)。
因此:

(10010011) ^ (00111101) 
= (10101110)

而且异或运算还拥有交换律,结合律:

A ^ B = B ^ A
A ^ B ^ C = (A ^ B) ^ C = A ^ (B ^ C)
A ^B = C ==> A = B ^ C; B = A ^ C

两个相同的数运算结果为0:

A ^ A = 0
0 ^ num = num
1 ^ num(BITE) = ~num(BITE)
0xffffffff ^ INT = ~INT

2. 文件加密解密思路

加密:

a). 定义一个char型字符串KEY作为加密密匙
b). 读取文件in.dat
c). 将in.dat按字节读出,与KEY进行异或(^)操作,作为加密后的字符
d). 加密后的字符,输出到out.dat
in.dat和out.dat分别为加密文件和加密后的文件名称,可随意。

解密:

解密操作只需将out.dat再和KEY异或一次,便恢复到了初始状态。

实例代码:
#include <iostream>
#include <fstream>
const int Key = 0xaf7;  //密匙

bool FileConvert(char szOldFile[], char szNewFile[])
{
    std::ifstream pOldFile;
    std::ofstream pNewFile;
    char cTemp;

    if (NULL == szOldFile || NULL == szNewFile)
    {
        return false;
    }

    pOldFile.open(szOldFile, std::ios_base::in | std::ios_base::binary);
    if (!pOldFile.is_open())
    {
        return false;
    }

    pNewFile.open(szNewFile, std::ios_base::out | std::ios_base::binary);
    if (!pNewFile.is_open())
    {
        pOldFile.close();
        return false;
    }

    //一定要先读,然后做文件末尾判断
    cTemp = pOldFile.get() ^ Key;
    while (!pOldFile.eof())  //判断是否到了文件末尾
    {
        pNewFile.put(cTemp);
        cTemp = pOldFile.get() ^ Key;
    }

    pOldFile.close();
    pNewFile.close();
    return true;
}

int main()
{
    char srcFile[FILENAME_MAX];
    char dstFile[FILENAME_MAX];
    std::cout << "Please input the filename that you want to encrypt/decrypt:";
    std::cin >> srcFile;
    std::cout << "Please input the encrypted/decrypted filename:";
    std::cin >> dstFile;
    std::cout << (FileConvert(srcFile, dstFile) ? "encrypt/decrtpt succeed!" : "encrypt/decrypt failed!") << std::endl;

    system("pause");
    return 0;
}

转载于:https://www.cnblogs.com/coolcpp/p/file-encrypt-decrypt.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值