使用换位加密法加密
主要内容
- 使用def语句创建函数
- main()函数
- 参数
- 全局作用域和本地作用域,全局变量和本地变量
- 列表数据类型,列表与字符串的相似之处
- list()函数
- 列表的列表
- 增强赋值运算符(+=、-=、*=、/=)
- join()字符串方法
- 返回值和return语句
- 特殊的_name_变量
4.1 换位加密法
- 换位加密法不是把字符替换成其他字符,而是搞乱消息符号的顺序,使原来的消息不可读。换位加密法具有更多可能的密钥,更难暴力破译。
- 加密步骤如下:
- 1.数一下消息里的字符个数
- 2.画一行个数等于密钥的格子
- 3.从左到右填充格子,每个格子填一个字符
- 4.当用完格子还有字符剩下时,再加一行格子
- 5.把最后一行剩下不用的格子涂成灰色
- 6.从最上角开始往下写出字符,到达这一列的底部后,移到右边的那一列。跳过任何灰色的格子,这就是密文。
4.2 换位加密法加密程序
- 如果密文末尾右空格字符很难看出,所以程序会在密文末尾加上一个|字符(“管道”字符)
# Transposition Cipher Encryption
# 换位加密法加密程序的源代码
import pyperclip
def main():
myMessage = 'Common sense is not so common.'
myKey = 8
ciphertext = encryptMessage(myKey, myMessage)
# Print the encrypted string in ciphertext to the screen, with
# a | (called "pipe" character) after it in case there are spaces at
# the end of the encrypted message.
print(ciphertext + '|')
# Copy the cncrypted string in ciphertext to the clipboard.
pyperclip.copy(ciphertext)
def encryptMessage(key, message):
# Each string in ciphertext represents a column in the grid.
ciphertext = [''] * key
# Loop through each column in ciphertext.
for col in range(key):
pointer = col
# Keep looping until pointer goes past the length of the message.
while pointer < len(message):
# Place the character at pointer in message at the end of the
# current column in the ciphertext list.
ciphertext[col] += message[pointer]
# move pointer over
pointer += key
# Convert the ciphertext iist into a single string value and return it.
return ''.join(ciphertext)
# If transpositionEncrypt.py is run (instead of imported as a module) call
# the main() function
if __name__ == '__main__':
main()
4.3 运行换位加密法加密程序
运行以上代码,产生输出为:Cenoonommstmme oo snnio. s s c
4.4 使用def语句创建自己的函数
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FDcDFMX0-1601902506210)(attachment:image.png)]
def语句表示我们正在创建(或者说定义)一个新的名为main()的函数,我们会在程序后面调用它。
def hello():
print('Hello')
total = 42 + 1
print('42 plus 1 is %s' % (total))
print('Start!')
hello