我会推荐使用模数运算符来做你想要的。在python中是%字符。在模数学中。 X%Y告诉我们X/Y的剩余部分是什么。例如。 27%26是1.使用这个你可以得到你想要的包装。这里是一个代码示例位,如果我们喂字符“A”进入我们的加密算法的13关键,我们得到“N”,如到现在为止加密单个字符
def encrypt_character(valToEncrypt, keyVal):
# Update the character to be our standard Alphabet mapping
# A -> 0; B->1 ... Z -> 25
x = ord(valToEncrypt) - ord('A')
# Perform the Encryption
retVal = (x + keyVal) % 26
# Translate back to the standard ASCII mapping of the character
# for display in python and translate it back into a string
retVal = chr(retVal + ord('A'))
return retVal
# end encrypt_character
:
>>> encrypt_character("A", 13)
'N'
解密算法是非常相似的,除非你做减法而不是addtion
def decrypt_character(valToDecrypt, keyVal):
# Update the character to be our standard Alphabet mapping
# A -> 0; B->1 ... Z -> 25
x = ord(valToDecrypt) - ord('A')
retVal = (x - keyVal) % 26
# Translate back to the standard ASCII mapping of the character
# for display in python and translate it back into a string
retVal = chr(retVal + ord('A'))
return retVal
要加密,你可以使用下面的函数的字符串: 从重新进口苏b def encrypt_message(消息,密钥): #将消息文本转换为纯文本,其中包含所有空格,并删除 #标点符号。 明文=子(R '[^ AZ]', '',message.upper()) 密文= “”
charIndex = 0
# Encrypt the message 1 character at a time
while charIndex < len(plainText):
cipherText += \
encrypt_character(plainText[charIndex], key)
charIndex += 1
return cipherText
此功能可被称为:
>>> encrypt_message("HELLO World!", key=23)
'EBIILTLOIA'
解密函数与加密函数非常相似,除了调用解密实用程序而不是加密实用程序。
我想你需要提供一些示例输入。 –
var2 = 30,var1 = zzzz使它^^^^ –