序
对python不熟,找到一本用python实现古典密码学算法的书.
对密码算法的应用很感兴趣. 将密码算法实验做完,python也该熟悉了:)
边用边学,学习效率是最高的。有些细节问题,只有在用的时候才会发现。
实验
@echo off
rem @file run.bat
python main.py
pause
@echo off
rem @file debug.bat
python -m pdb main.py
pause
# @file main.py
# @brief caesar cipher
#
# for debug : python -m pdb main.py
# debug same to gdb, ref : https://docs.python.org/2/library/pdb.html
# n is step over
# s is step in
# view val is type the val name and ENTER
# ENTER is execute last debug command
# q is quit python debug
"""
run result
Python 3.6.2
cipher text = guvF vF CynvA GrKG:)
plain text = This is plain text:)
END
"""
from subprocess import call
# @fn caesar_cipher
# @brief caesar cipher encrypt or decrypt
# @param b_encryp, True = encrypt; False = decrypt
# @param msg,
# when (b_encryp == True), msg is plain text
# when (b_encryp == False), msg is cipher text
# @param cipher_key, the cipher key by caesar cipher
# @return string, the result string
# when (b_encryp == True), return cipher text
# when (b_encryp == False), return plain text
def caesar_cipher(b_encryp, msg, cipher_key):
sz_cipher_charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
i_len_cipher_charset = len(sz_cipher_charset)
sz_cipher_msg = ""
c_letter = ''
i_pos = 0
i_num = 0
for c_letter in msg:
if c_letter in sz_cipher_charset:
# 求字符在字符集数组中的索引
i_pos = sz_cipher_charset.find(c_letter)
i_num = i_pos
# print("i_pos = ", i_pos, "c_letter = ", c_letter)
if b_encryp == True:
i_num += cipher_key
else:
i_num -= cipher_key
if i_num >= i_len_cipher_charset:
i_num -= i_len_cipher_charset
elif i_num < 0:
i_num += i_len_cipher_charset
sz_cipher_msg += sz_cipher_charset[i_num]
else:
# if letter not on charset, don't cipher
sz_cipher_msg += c_letter
return sz_cipher_msg
if __name__ == "__main__":
cipher_key = 13
sz_cipher_msg = ""
# print python version
call(["python", "-V"])
# caesar encrypt
sz_cipher_msg = caesar_cipher(True, "This is plain text:)", cipher_key)
print("cipher text =", sz_cipher_msg)
# caesar decrypt
sz_cipher_msg = caesar_cipher(False, "guvF vF CynvA GrKG:)", cipher_key)
print("plain text =", sz_cipher_msg)
print("END")
749



被折叠的 条评论
为什么被折叠?



