密码学_凯撒

1至26全解密

加密为1至26的顺序全部解密,解密后寻找自己想要的明文(只解密字母)

# -*- coding:UTF-8-*-
from __future__ import print_function
import string

str = raw_input('MESSAGE: ')
for shift in range(26):
    new_str = ''
    for i in str:
        if i >= 'A' and i <= 'Z':  # or i>='a'and i<='z':
            i = ord(i)
            i = ((i + shift) - 65) % 26 + 65
            i = chr(i)
        if i >= 'a' and i <= 'z':  # or i>='a'and i<='z':
            i = ord(i)
            i = ((i + shift) - 97) % 26 + 97
            i = chr(i)
        new_str = new_str + i
    print(new_str)

只加解密字母

def encryption(str, n):
    cipher = []
    for i in range(len(str)):
        if str[i].islower():
            if ord(str[i]) < 123-n:
                c = chr(ord(str[i]) + n)
                cipher.append(c)
            else:
                c = chr(ord(str[i]) + n - 26)
                cipher.append(c)
        elif str[i].isupper():
            if ord(str[i]) < 91-n:
                c = chr(ord(str[i]) + n)
                cipher.append(c)
            else:
                c = chr(ord(str[i]) + n - 26)
                cipher.append(c)
        else:
            c = str[i]
            cipher.append(c)
    cipherstr = ('').join(cipher)
    return cipherstr

#获得用户输入的明文
#此代码只对字母进行转换
print("请输入字符串:")
plaintext = input()
#下面这句中的数字要自己改完再运行,位移多少位就写多少,可以为负数(负数相当于解密)
ciphertext = encryption(plaintext, 7)
print(ciphertext)

所有字符都进行加解密

#import os
#-*-coding:utf-8-*-
#============================================================================
#   凯撒密码(caesar)是最早的代换密码,对称密码的一种,本代码是字母数字符号统统转          
#   算法:将每个字母用字母表中它之后的第k个字母(称作位移值)替代     
#============================================================================
def encryption():
    str_raw = input("请输入明文:")
    k = int(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 = input("请输入密文:")
    k = int(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 = input("请选择:")
    if choice == "1":
        encryption()
    elif choice == "2":
        decryption()
    else:
        print (u"您的输入有误!")

你可能感兴趣的:(Python收集)