python Python中的Caesar密码实现。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python中的Caesar密码实现。相关的知识,希望对你有一定的参考价值。
import argparse
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def encrypt(message, key):
message = message.replace(':', '')
message = message.replace(';', '')
message = message.replace(',', '')
message = message.replace('.', '')
message = message.replace('?', '')
message = message.replace('!', '')
message = message.upper()
encrypted_message = ''
for c in message:
if c not in ALPHABET:
encrypted_message += c
continue
index_in_alphabet = ALPHABET.find(c)
shifted_index = ((index_in_alphabet + key) % len(ALPHABET))
encrypted_message += ALPHABET[shifted_index]
return encrypted_message
def decrypt(message, key):
message = message.replace(':', '')
message = message.replace(';', '')
message = message.replace(',', '')
message = message.replace('.', '')
message = message.replace('?', '')
message = message.replace('!', '')
message = message.upper()
decrypted_message = ''
for c in message:
if c not in ALPHABET:
decrypted_message += c
continue
index_in_alphabet = ALPHABET.find(c)
shifted_index = ((index_in_alphabet - key) % len(ALPHABET))
decrypted_message += ALPHABET[shifted_index]
return decrypted_message
def main():
usage = "python caesar_cipher.py -e -m \"secret\"\nor\n \ " \
"python caesar_cipher.py -d -m \"TFDSFU\""
description = "Command line program for demonstrating the Caesar cipher."
parser = argparse.ArgumentParser(usage=usage, description=description)
parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-e", "--encrypt", action="store_true", dest="encrypt", help="Encrypts the plain text message.")
group.add_argument("-d", "--decrypt", action="store_true", dest="decrypt", help="Decrypts the encrypted message.")
parser.add_argument("-m", "--message", action="store", required=True,
dest="message", help="You need to specify the message. Like this: -m \"secret\"")
parser.add_argument("-k", "--key", action="store", required=True, dest="key", type=int,
help="You need to specify the key as a number.")
options = parser.parse_args()
if options.encrypt:
print("The encrypted message is: " + encrypt(options.message, options.key))
elif options.decrypt:
print("The decrypted message is: " + decrypt(options.message, options.key))
if __name__ == '__main__':
main()
以上是关于python Python中的Caesar密码实现。的主要内容,如果未能解决你的问题,请参考以下文章
信息安全-1:python之playfair密码算法详解[原创]
Crypto - Caesar I
密码学——几种典型的古典密码体制(Caesar体制Playfair体制Vigenere体制Beaufort体制以及Hill体制)
python Python中的空密码实现。
密码学的做2个题目!
模块'caesar'没有属性'alphabet'