Python实现的凯撒密码算法示例


当前第2页 返回上一页

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

# -*- coding:utf-8 -*-

import os

#==================================================================#

#     凯撒密码(caesar)是最早的代换密码,对称密码的一种        #

#  算法:将每个字母用字母表中它之后的第k个字母(称作位移值)替代      #

#==================================================================#

def encryption():

  str_raw = raw_input("请输入明文:")

  k = int(raw_input("请输入位移值:"))

  str_change = str_raw.lower()

  str_list = list(str_change)

  str_list_encry = str_list

  i = 0

  while i < len(str_list):

    if ord(str_list[i]) < 123-k:

      str_list_encry[i] = chr(ord(str_list[i]) + k)

    else:

      str_list_encry[i] = chr(ord(str_list[i]) + k - 26)

    i = i+1

  print ("加密结果为:"+"".join(str_list_encry))

def decryption():

  str_raw = raw_input("请输入密文:")

  k = int(raw_input("请输入位移值:"))

  str_change = str_raw.lower()

  str_list = list(str_change)

  str_list_decry = str_list

  i = 0

  while i < len(str_list):

    if ord(str_list[i]) >= 97+k:

      str_list_decry[i] = chr(ord(str_list[i]) - k)

    else:

      str_list_decry[i] = chr(ord(str_list[i]) + 26 - k)

    i = i+1

  print ("解密结果为:"+"".join(str_list_decry))

while True:

  print (u"1. 加密")

  print (u"2. 解密")

  choice = raw_input("请选择:")

  if choice == "1":

    encryption()

  elif choice == "2":

    decryption()

  else:

    print (u"您的输入有误!")

三 运行结果

相关推荐:

Python实现求一个集合所有子集的示例

Python实现LR经典算法

以上就是Python实现的凯撒密码算法示例的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python中如何求列表list的平均数

Python基础学习if语句

Python之正则表达式中的贪心模式和非贪心模式的用法和区别

Python缩进是强制吗

Python图像处理的基础和opencv的入门函数

什么叫Python字符串的格式化

Python哪年出来的

Python中一些常用的运算符和内置函数

Python十进制小数和二进制小数相互转换的实现方式

关于Python中的__init__与__new__以及__call__三个方法的简单介绍

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...