Last active
August 9, 2019 13:38
-
-
Save lawrencechen0921/61cd0e0b719ed7def78462f8d4b3f8b5 to your computer and use it in GitHub Desktop.
USE ASCII TO ENCRYPT 學會如何加密解密
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _move_leter(letter, n): | |
""" | |
把字母變為字母表後n位的字母,z后面接a | |
:param letter: 小写字母 | |
:param n: 要移動的字母 | |
:return: 移動的结果 | |
""" | |
return chr((ord(letter) - ord('a') + n) % 26 + ord('a')) | |
def Encrypt(k, p): | |
""" | |
移位密碼加密函数E | |
:param k: 秘钥k,每個字母在字母表中移動k位 | |
:param p: 明文p | |
:return: 密文c | |
""" | |
letter_list = list(p.lower()) | |
c = ''.join([_move_leter(x, k) for x in letter_list]) | |
return c | |
def Decrypt(k, c): | |
""" | |
移位密碼解密函数D | |
:param k: 秘钥k,每個字母在字母表中移動k位 | |
:param c: 密文c | |
:return: 明文p | |
""" | |
letter_list = list(c.lower()) | |
p = ''.join([_move_leter(x, -k) for x in letter_list]) | |
return p | |
if __name__ == '__main__': | |
p = 'Beauty is better than ugly.' | |
print('明文:' + p) | |
print('密文:' + Encrypt(1, p)) | |
print('解密:' + Decrypt(1, Encrypt(1, p))) | |
assert Decrypt(1, Encrypt(1, p)) == p | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment