Python加密函数和全局变量

时间:2013-05-11 13:18:34

标签: python function global-variables encryption

好的,所以我正在写一个python加密代码。代码比它需要的时间长,所以我把它的一部分切换到了函数。一旦我开始这样做,就说它无法找到变量。为了解决这个问题,我将变量设置为全局变量。但是,它仍然无效,并给我错误:

Traceback (most recent call last):
  File "C:/Users/Alex/Desktop/Encryptor.py", line 272, in <module>
    startup()
  File "C:/Users/Alex/Desktop/Encryptor.py", line 257, in startup
    encrypt()
  File "C:/Users/Alex/Desktop/Encryptor.py", line 44, in encrypt
    maincrypt(2)
  File "C:/Users/Alex/Desktop/Encryptor.py", line 12, in maincrypt
    print newtext
UnboundLocalError: local variable 'newtext' referenced before assignment

这是我的代码:

letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def maincrypt(num):
    print otext
    print textlist
    print newtextlist
    print newtext
    print times
    print i
    add = times + num
    while add > 25:
        add = add - 25
        if ord(i) >= 65 and ord(i) <= 90:
            newtext += letters[add].uppercase
        else:
            newtext += letters[add]
def encrypt():
    global otext
    global textlist
    global newtextlist
    global newtext
    global times
    global i
    otext = raw_input("Text?")
    textlist = []
    newtextlist = []
    newtext= ""
    times = 0
    for i in otext:
        textlist.append(i)
    for i in textlist:
        if i == 'a' or i == 'A':
            maincrypt(0)
        elif i == 'b' or i == 'B':
            maincrypt(1)
        elif i == 'c' or i == 'C':
            maincrypt(2)
        elif i == 'd' or i == 'D':
            maincrypt(3)
        elif i == 'e' or i == 'E':
            maincrypt(4)
        elif i == 'f' or i == 'F':
            maincrypt(5)
        elif i == 'g' or i == 'G':
            maincrypt(6)
        elif i == 'h' or i == 'H':
            maincrypt(7)
        elif i == 'i' or i == 'I':
            maincrypt(8)
        elif i == 'j' or i == 'J':
            maincrypt(9)
        elif i == 'k' or i == 'K':
            maincrypt(10)
        elif i == 'l' or i == 'L':
            maincrypt(11)
        elif i == 'm' or i == 'M':
            maincrypt(12)
        elif i == 'n' or i == 'N':
            maincrypt(13)
        elif i == 'o' or i == 'O':
            maincrypt(14)
        elif i == 'p' or i == 'P':
            maincrypt(15)
        elif i == 'q' or i == 'Q':
            maincrypt(16)
        elif i == 'r' or i == 'R':
            maincrypt(17)
        elif i == 's' or i == 'S':
            maincrypt(18)
        elif i == 't' or i == 'T':
            maincrypt(19)
        elif i == 'u' or i == 'U':
            maincrypt(20)
        elif i == 'v' or i == 'V':
            maincrypt(21)
        elif i == 'w' or i == 'W':
            maincrypt(22)
        elif i == 'x' or i == 'X':
            maincrypt(23)
        elif i == 'y' or i == 'Y':
            maincrypt(24)
        elif i == 'z' or i == 'Z':
            maincrypt(25)
        else:
            newtext += i
        times += 1
    print newtext

def decrypt():
    otext = raw_input("Text?")
    textlist = []
    newtextlist = []
    newtext= ""
    times = 0
    for i in otext:
        textlist.append(i)
    for i in textlist:
        if i == 'a' or i == 'A':
            add = 0 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'b' or i == 'B':
            add = 1 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'c' or i == 'C':
            add = 2 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'd' or i == 'D':
            add = 3 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'e' or i == 'E':
            add = 4 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'f' or i == 'F':
            add = 5 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'g' or i == 'G':
            add = 6 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'h' or i == 'H':
            add = 7 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'i' or i == 'I':
            add = 8 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'j' or i == 'J':
            add = 9 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'k' or i == 'K':
            add = 10 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'l' or i == 'L':
            add = 11 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'm' or i == 'M':
            add = 12 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'n' or i == 'N':
            add = 13 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'o' or i == 'O':
            add = 14 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'p' or i == 'P':
            add = 15 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'q' or i == 'Q':
            add = 16 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'r' or i == 'R':
            add = 17 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 's' or i == 'S':
            add = 18 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 't' or i == 'T':
            add = 19 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'u' or i == 'U':
            add = 20 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'v' or i == 'V':
            add = 21 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'w' or i == 'W':
            add = 22 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'x' or i == 'X':
            add = 23 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'y' or i == 'Y':
            add = 24 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'z' or i == 'Z':
            add = 25 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        else:
            newtext += i
        times += 1
    print newtext

def startup():
    upass = raw_input("Password: ")
    if upass == "astrocrypt":
        print """Welcome!
1: Encrypt
2: Decrypt
3: Credits
4: Quit"""
        try:
            choice = input()
        except SyntaxError:
            print "Oops! That's not a valid number! Try again!"
            startup()
        except NameError:
            print "Oops! That's not a valid number! Try again!"
            startup()
        if choice == 1:
            encrypt()
            startup()
        elif choice == 2:
            decrypt()
            startup()
        elif choice == 3:
            print "Made by Alex Taber"
            startup()
        elif choice == 4:
            pass
        else:
            print "Unknown number"
            startup()
    else:
        print "Incorrect password!"
startup()

2 个答案:

答案 0 :(得分:3)

首先,有非常强大且几乎不可破解的加密算法,其中一些预先包装有python,如hmac

import hmac

def Hash_string(ref):
        cypher = hmac.new('you secret word', 'plain-text')
        return cypher.hexdigest()

简单易用,更强大。你也可以使用blowfish来获得更高级和更安全的项目,虽然默认情况下没有python,但设置起来很简单。

现在到您的代码,这里是如何在python中使用全局变量

# declare variables as global
global num1
global num2
num2=22    # give initial value to num2

def foo():
   # bind variable names to the ones in global scope
   global num2
   print num2   # output: 22
   num2 = 88
   print num2   # output: 88
   global num1
   num1 = num2

def bar():
   print num1   # output: 88
   print num2   # output 88

foo()
bar()

所以你需要将newtext绑定到声明为gobal的文本

我还建议你重写加密看起来像这样

alpha = ['a','b','c','d','e','f','g','h','i','j','k', 'L', 'M', 'N', '0', 'p', 'q', 'R', 'S', 'T', 'U', 'v', 'W','× ”, 'Y', 'Z']

数字= [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21, 22,23,24,25]

def map (ch):
   chr = ch.lower()
   return numeric[alpha.index(chr)]

这会在数字和字母之间创建一个映射,因此您不需要很长的elif列表

希望这有帮助。

EDIT 您可以使用global关键字访问全局变量,但是如果要修改它们,首先需要绑定到全局变量,然后才能更改它们。

EDIT 更改返回数字[index(chr)]返回数字[alpha.index(chr)] 抱歉这个错误:)

答案 1 :(得分:2)

为了保护程序员免受全局变量的影响,在声明它们与global variablename一起使用之前,不会认为全局变量存在于函数中。在maincrypt中,您不会声明global newtext,也不会通过分配来创建本地newtext。 <=运算符要求左手已存在 - 它尚未存在,因此抛出异常。

顺便说一句,如果你计划在其他任何地方重用这个程序,最好使用类变量而不是全局变量,所以1)如果其他人使用相同的全局变量名称,则一切正常2)你可以有两个实例加密器/解密器代码运行和加密/解密不同的东西,甚至在不同的线程上并行,而不会破坏彼此的全局。

此外,此代码:ord(i.upper()) - ord('A')将为'a'和'A'提供0,为'b'和'B'提供1,为'c'和'C'提供2 ...等等在,所以你不需要如此巨大的if / elif链。 (为什么这有效是因为'A','B','C'等在ASCII中是连续的,所以'B' - 'A'是1,依此类推)