持续的字节输出计数器C

Persistent Byte Output Counter C++

本文关键字:计数器 输出 字节      更新时间:2023-10-16

我正在研究一个项目,我需要跟踪软件盘式的字体。

该软件将偶尔打开和关闭,因此我必须实施一种以某种方式存储输出的字节数的方法,以便管理员或其他用户不能简单地打开文件并更改输出的字节数。

实施此功能的最佳方法是什么?

另外,我无法使用任何库(例如:Boost(。

以下是使用https://en.wikipedia.org/wiki/tiny_encryption_algorithm

的示例
#include <iostream>
#include <fstream>
void encrypt(uint32_t* v, uint32_t* k) {
    uint32_t v0 = v[0], v1 = v[1], sum = 0, i;           /* set up */
    uint32_t delta = 0x9e3779b9;                     /* a key schedule constant */
    uint32_t k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3];   /* cache key */
    for (i = 0; i < 32; i++) {                       /* basic cycle start */
        sum += delta;
        v0 += ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1);
        v1 += ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3);
    }                                              /* end cycle */
    v[0] = v0; v[1] = v1;
}
void decrypt(uint32_t* v, uint32_t* k) {
    uint32_t v0 = v[0], v1 = v[1], sum = 0xC6EF3720, i;  /* set up */
    uint32_t delta = 0x9e3779b9;                     /* a key schedule constant */
    uint32_t k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3];   /* cache key */
    for (i = 0; i<32; i++) {                         /* basic cycle start */
        v1 -= ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3);
        v0 -= ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1);
        sum -= delta;
    }                                              /* end cycle */
    v[0] = v0; v[1] = v1;
}
int main()
{
    uint32_t k[4] = { 123,456,789,10 }; // key
    uint32_t v[2] = { 1000000, 1000000 }; // data

    // save into file
    std::ofstream ofs("save.dat", std::ios::binary);
    encrypt(v, k);
    ofs << v[0] << " " << v[1] << std::endl;

    // read from file
    std::ifstream ifs("save.dat", std::ios::binary);
    uint32_t v2[2];
    if (ifs >> v2[0] >> v2[1])
    {
        std::cout << "Filedata: " << v2[0] << " " << v2[1] << std::endl;
        decrypt(v2, k);
        if (v2[0] == v2[1])
            std::cout << "Decrypted: " << v2[0] << std::endl;
        else
            std::cout << "Data was tampered with!" << std::endl;
    }
}

http://coliru.stacked-crooked.com/view?id=d725bf798ff8ca12

效果很好,不需要任何库。这是低水平的保护,但应该足够难以阻止您的用户。