亲宝软件园·资讯

展开

python实现移位加密和解密 python实现移位加密和解密

吉米多的围棋 人气:0


代码很简单,就不多做解释啦。主要思路是将字符串转为Ascii码,将大小写字母分别移位密钥表示的位数,然后转回字符串。需要注意的是,当秘钥大于26的时候,我使用循环将其不断减去26,直到密钥等效小于26为止。

def encrypt():
  temp = raw_input("Please input your sentence: ")
  key = int(raw_input("Please input your key: "))
  listA = map(ord,temp)
  lens = len(listA)
  for i in range(lens):
    a = listA[i]
    if 65 <= a <= 90:
      a += key
      while a > 90:
        a -= 26
    elif 97 <= a <= 122:
      a += key
      while a > 122:
        a -= 26
    listA[i] = a
  listA = map(chr,listA)
  listA = ''.join(listA)
  print listA


def unencrypt():
  temp = raw_input("Please input your sentence: ")
  key = int(raw_input("Please input your key: "))
  listA = map(ord, temp)
  lens = len(listA)

  for i in range(lens):
    a = listA[i]
    if 65 <= a <= 90:
      a -= key
      while a < 65:
        a += 26
    elif 97 <= a <= 122:
      a -= key
      while a < 97:
        a += 26
    listA[i] = a
  listA = map(chr, listA)
  listA = ''.join(listA)
  print listA


a = int(raw_input("input 0 to encrypt and 1 to unencrypt"))

if a == 0:
  encrypt()
elif a == 1:
  unencrypt()

效果

加载全部内容

相关教程
猜你喜欢
用户评论