目前正在开发RPG,我在问如何保护保存的数据,使玩家/用户无法轻松读取或修改。我的意思是,是的,一个有计算机和编程经验的人可以修改它,但我不希望lambda用户能够像修改纯文本xml文件一样轻松地修改它。
有没有一种方法可以让我用蟒蛇做到这一点?
仅pickle
或cpickle
一个压缩设置为最大值的配置对象是一个快速而简单的选项。
听起来你需要一个加密库。这将帮助您使用密钥加密或解密文件。好在已经有一个叫PyCrypto的了。你可以在这里下载。
要使用它,一旦你下载了它,这里有文档:
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有几个关于对称密码、AES和CBC的精彩视频。
您可以使用zlib压缩数据。
savedata="level=3"
import zlib
#when saving
compressedString = zlib.compress(savedata)
#when loading
loaddata = zlib.decompress(compressedString)
泡菜可能太大了。在某些情况下工作起来很奇怪。ZIP允许从归档的不同部分读写数据。
尝试使用密码压缩或更改文件的第一个字节以阻止正常解压缩
PS。制作一些不同的变体并检查的大小/速度