如何在python .py运行代码中输入文件

时间:2015-07-05 09:41:49

标签: python

代码是假设解密和加密随机文件,但我无法弄清楚如何输入它。

import array
import hashlib
import random

from Crypto.Cipher import Blowfish


MH3G_JP = 0
MH3G_NA = 1
MH3G_EU = 2
MH4_JP = 3
MH4_NA = 4
MH4_EU = 5
MH4G_JP = 6
MH4G_NA = 7
MH4G_EU = 8


class SavedataCipher:
def __init__(self, game):
    if game in (MH4G_JP, MH4G_NA, MH4G_EU):
        self._cipher = Blowfish.new(b'blowfish key
iorajegqmrna4itjeangmb agmwgtobjteowhv9mope')
    else:
        raise ValueError('Ivalid game selected.')

def _xor(self, buff, key):
    buff = array.array('H', buff)
    for i in range(len(buff)):
        if key == 0:
            key = 1
        key = key * 0xb0 % 0xff53
        buff[i] ^= key
    return buff.tostring()
def encrypt(self, buff):
    csum = sum(buff) & 0xffffffff
    buff = array.array('I', buff)
    buff.insert(0, csum)
    seed = random.getrandbits(16)
    buff = array.array('I', self._xor(buff.tostring(), seed))
    buff.insert(0, (seed << 16) + 0x10)
    buff.byteswap()
    buff = array.array('I', self._cipher.encrypt(buff.tostring()))
    buff.byteswap()
    return buff.tostring()

def decrypt(self, buff):
    buff = array.array('I', buff)
    buff.byteswap()
    buff = array.array('I', self._cipher.decrypt(buff.tostring()))
    buff.byteswap()
    seed = buff.pop(0) >> 16
    buff = array.array('I', self._xor(buff.tostring(), seed))
    csum = buff.pop(0)
    buff = buff.tostring()
    if csum != (sum(buff) & 0xffffffff):
        raise ValueError('Invalid checksum in header.')
    return buff

def encrypt_file(self, savedata_file, out_file):
    savedata = open(savedata_file, 'rb').read()
    savedata = self.encrypt(savedata)
    open(out_file, 'wb').write(savedata)

def decrypt_file(self, savedata_file, out_file):
    savedata = open(savedata_file, 'rb').read()
    savedata = self.decrypt(savedata)
    open(out_file, 'wb').write(savedata)

1 个答案:

答案 0 :(得分:0)

这段代码是一个类,你应该创建一个调用这个调用的函数。您可以在同一文件或不同文件中执行此操作并导入该类。

if __name__ == "__main__":
    cipher = SavedataCipher(MH4G_JP) # or use different parameter
    # do something else