python实现移位加密和解密

yipeiwu_com6年前Python基础

本文实例为大家分享了python实现移位加密和解密的具体代码,供大家参考,具体内容如下

代码很简单,就不多做解释啦。主要思路是将字符串转为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()

效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

对django views中 request, response的常用操作详解

request 获取post请求中的json数据 def hello(request): data = json.loads(request.body) ... json格式还...

详解python做UI界面的方法

详解python做UI界面的方法

一直以来都是用python脚本,执行的时候就是在终端直接命令执行,或者直接输入代码执行,最近为了方便他人使用,想做个界面,可以通过里面的控件菜单直接点击执行程序功能。 在文件夹中创建一...

Python 中的with关键字使用详解

在 Python 2.5 中, with 关键字被加入。它将常用的 try ... except ... finally ... 模式很方便的被复用。看一个最经典的例子: with...

Python根据服务获取端口号的方法

根据服务获取端口号 首先需要下载一个psutil库 然后根据服务名找到PID 找到PID之后,通过pid获取端口号 # -*- encoding=utf8 -*- import ps...

python requests post多层字典的方法

pyhton requests模块post方法传参为多层字典时,转换错误, 如,表单传参 { “a”:1, “b”:{ “A”:2, “B”:3 } } post请求...