从不同程序设置模块中的变量

2024-04-20 15:29:23 发布

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

我正在努力将这段代码转换成一个模块,在这个模块中我可以使用一个外部程序来设置这段代码中的变量。如何在一个程序中设置变量,在另一个程序中设置变量(用作模块),并将所述程序的结果输入第一个程序

这是代码,任何建议/帮助都将不胜感激

import Crypto.Random
from Crypto.Cipher import AES
import hashlib

SALT_SIZE = 16 
iterations = 64000
salt = 'h5eE0b814M'
password = 'fortytwo'
text = 'What do you mean'
padded_text = ''
ciphertext = ''
key = ''
ciphertext_with_salt = ''


def key_generation(password, salt, iterations):
    global key
    assert iterations > 0
    key = password + salt
    for i in range(iterations):
        key = hashlib.sha256(key).digest()
    print '\nKey: ' + key #Debug Print
    return key

def pad_text(text, SALT_SIZE):
    print '\nUnpadded Text: ' + text #Debug Print
    global padded_text
    extra_bytes = len(text) % SALT_SIZE
    pad_size = SALT_SIZE - extra_bytes
    pad = chr(pad_size) * pad_size
    padded_text = text + pad
    print '\nPadded Text: ' + padded_text #Debug Print
    return padded_text

def encryption(text, password):
    global ciphertext
    global key
    salt1 = Crypto.Random.get_random_bytes(SALT_SIZE)
    cipher = AES.new(key, AES.MODE_ECB)
    padded_plaintext = pad_text(text, SALT_SIZE)
    ciphertext = cipher.encrypt(padded_text)
    ciphertext_with_salt = salt + ciphertext

    #debug script
    print '\nSalt: ' + salt #Debug Print
    print '\nEncrypted Text: ' + ciphertext #Debug Print
    print '\nEncrypted Text with Salt: ' + ciphertext_with_salt #Debug Print
    return ciphertext_with_salt

def decryption(ciphertext, password):
    salt = ciphertext[0:SALT_SIZE]
    ciphertext_sans_salt = ciphertext[SALT_SIZE:]
    key = key_generation(password, salt, iterations)
    cipher = AES.new(key, AES.MODE_ECB)
    padded_plaintext = cipher.decrypt(ciphertext_sans_salt)
    print '\nUnencrypted Text: ' + text #Debug Print
    return text


key_generation(password, salt, iterations)
encryption(text, password)
decryption(ciphertext, password)

Tags: keytextdebug程序sizepasswordaessalt
1条回答
网友
1楼 · 发布于 2024-04-20 15:29:23

简单地说

if __name__ == '__main__':

在你最后三行之前。然后,您可以像导入任何其他模块一样导入它,并使用例如yourmodulename.encryption(文本、密码)调用函数

相关问题 更多 >