在游戏中保护保存文件不被修改?

2024-03-28 10:37:53 发布

您现在位置:Python中文网/ 问答频道 /正文

目前正在开发一个RPG,我在问如何保护保存的数据,这样播放器/用户就不能轻松地读取或修改它。我的意思是,一个有计算机和编程经验的人可以修改它,但我不希望lambda用户能够像修改纯文本xml文件一样容易地修改它。在

我能用python做到这一点吗?在


Tags: 文件数据lambda用户文本编程计算机经验
3条回答

听起来你需要一个密码库。这将帮助您使用密钥加密或解密文件。好在现在已经有一个叫PyCrypto的了。你可以下载它here。在

要使用它,请在下载后It is documented here

import string
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Random import random

def gen_cipher():
    # generates 32 letter long key
    key = ''.join(random.sample(string.ascii_letters, 32))
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(key, AES.MODE_CFB, iv)
    return cipher, iv

def write_data(data, rfile, cipher, iv):
    with open(rfile, 'w') as f:
        msg = iv + cipher.encrypt(b'Users cant edit this')
        f.write(msg)

def read_data(rfile, cipher):
    with open(rfile, 'r') as f:
        data = f.read()
        # first 16 bytes are IV
        return cipher.decrypt(data)[16:]

def encrypt_existing_file(infile, outfile, cipher, iv):
    with open(infile, 'r') as if:
        data = if.read()
        write_data(data, outfile, cipher, iv)

def decrypt_existing_file(infile, outfile, cipher, iv):
    with open(outfile, 'r') as of:
        data = read_data(infile)
        of.write(data)

if __name__ == '__main__':
    cipher, iv = gen_cipher()
    write_data(b"You didn't see anything...", 'file.txt', cipher, iv)
    # ...
    # outputs: You didn't see anything...
    print (read_data('file.txt', cipher))

它使用AES作为对称密钥密码。首先,我从32个随机选择的ascii字母中生成一个随机键。然后创建一个初始化向量(iv)。这在加密文件的开始时是必需的,以便正确初始化。然后是密码本身,它需要一个密钥、一个操作模式和一个初始化向量。CFB模式(密码反馈模式)只是意味着AES将以某种方式使用,下一个块在某种程度上依赖于上一个块。Udacity在Symmetric ciphersAES,和{a5}上有几段很棒的视频。在

可以使用zlib压缩数据。在

savedata="level=3"

import zlib

#when saving
compressedString = zlib.compress(savedata)

#when loading
loaddata = zlib.decompress(compressedString)

只要picklecpickle一个压缩设置为max的配置对象是一个快速而简单的选择。在

相关问题 更多 >