python - 使用循环密码加密消息

标签 python python-3.x ascii encryption cyclic

这是一个例子:

  • 普通:ABCDEFGHIJKLMNOPQRSTUVWXYZ
  • Shift = 4
  • 密码:DEFGHIJKLMNOPQRSTUVWXYZABC

代码如下:

print ("This is a cyclic cipher program that will encrypt messages.")

#phrase = input("Please enter a phrase to encrypt.")
phrase = "ABCDEFG"
#shift_value = int(input ("Please enter a shift value between 1 - 5."))
shift_value = 1
encoded_phrase = ""
ascii_codes = 0
x = ""
#accepted_ascii_codes = range(65,90) and range(97,122)

for c in phrase:
ascii_codes = ord(c) # find ascii codes for each charcter in phrase
ascii_codes = ascii_codes + shift_value # add an integer (shift value) to ascii codes
phrase_rest = chr(ascii_codes) # convert ascii codes back to characters
encoded_phrase = encoded_phrase + c # stores the phrase character in a new variable
encoded_phrase = encoded_phrase.replace(c,phrase_rest) # replace original character

print (phrase) # prints "ABCDEFG"
print (encoded_phrase) # prints "HHHHHHH"

最佳答案

你在每个循环中重新编码你的加密字母,这可以达到目的:

for c in phrase:
  ascii_codes = ord(c) # find ascii codes for each charcter in phrase
  ascii_codes = ascii_codes + shift_value # add an integer (shift value) to ascii codes
  phrase_rest = chr(ascii_codes) # convert ascii codes back to characters
  encoded_phrase = encoded_phrase + phrase_rest # stores the phrase character in a new variable

但是,您可能想用原始字母和加密字母建立字典。然后你会遍历它们并得到加密的句子。例如:

cypher = {'a': 'x', 'b': 'y', ... }
encoded = ''
for c in phrase:
  encoded += cypher[c]

关于python - 使用循环密码加密消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9525771/

相关文章:

python - R 的 Jupyter 笔记本出现 Anaconda 库错误

python - 为什么从Python 3子进程读取实时输出需要按回车键才能输出数据?

python - 统一码编码错误 : 'ascii' codec can't encode character u'\xe4'

c - 在 32 位或 64 位的一个字节中检测 ascii 字符

Python 模拟 : How to inject an object at a specific point in a function?

python - flask 管理员/ flask -SQLAlchemy : set user_id = current_user for INSERT

python - 从 Python 打开交互式 telnet session

python-3.x - 带有索引的 scikit-learn StratifiedShuffleSplit KeyError

python - 更改当前工作目录将不起作用

c++ - 在 C++ 中创建同时支持 Unicode 和 ASCII 的库的最佳实践是什么?