Closed. This question needs to be more focused。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
                        
                        去年关闭。
                                                                                            
                
        
我正在做一个项目,在该项目中,我需要跟踪软件抛出的字节数。
该软件偶尔会打开和关闭,因此我必须实现一种存储输出字节数的方法,以便管理员或其他用户不能简单地打开文件并更改输出字节数。
实现此目的的最佳方法是什么?
另外,我无法使用任何库(例如: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

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

10-08 07:20
查看更多