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

时间:2014-04-01 20:16:35

标签: python encryption module

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

以下是代码,非常感谢任何建议/帮助。

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)

1 个答案:

答案 0 :(得分:1)

简单地说

if __name__ == '__main__':

在最后3行之前。然后您可以像任何其他模块一样导入它,并使用例如yourmodulename.encryption(text,password)。