凯撒密码加密、解密过程(python、C++实现)

凯撒密码
单表替代密码 ——凯撒(Caesar)密码,又叫循环移位密码。它的加密方法就是将明文中的每个字母用字母表中该字母后的第R个字母来替换,达到加密的目的。
加密过程可以表示为下面的函数:
E(x) = (x + key) mod n
其中,E表示加密函数,x表示为明文;n为字母表中的字母个数;key为密钥, 为密文字母在字母表中对应的位置数。
解密过程可以表示为下面函数:
D(y) = (y - key) mod n
其中,D表示解密函数,y为密文,n为字母表中的字母个数;key为密钥, 为密文字母在字母表中对应的位置数。
加密示意图
假设key为3
在这里插入图片描述
注:解密是加密的反过程

加密函数

def Encryption(plaintext, key):
    print("加密后为:")
    for i in range(len(plaintext)):
        #ord():把字符转ASCII码,chr():把ASCII码转字符
        if ord('a') <= ord(plaintext[i]) <= ord('z'):  
            print(chr((ord(plaintext[i]) + key - ord('a')) % 26 + ord('a')),end="")
        elif ord('A') <= ord(plaintext[i]) <= ord('Z'):
            print(chr((ord(plaintext[i]) + key - ord('A')) % 26 + ord('A')),end="")

解密函数

def Decrypt(ciphertext, key):
    print("解密后为:")
    for i in range(len(ciphertext)):
    	#ord():把字符转ASCII码,chr():把ASCII码转字符
        if ord('a') <= ord(ciphertext[i]) <= ord('z'):
            print(chr((ord(ciphertext[i]) + (0 - key) - ord('a')) % 26 + ord('a')),end="")
        elif ord('A') <= ord(ciphertext[i]) <= ord('Z'):
            print(chr((ord(ciphertext[i]) + (0 - key) - ord('A')) % 26 + ord('A')),end="")            

凯撒密码pyhton实现过程

# -*- coding: GB2312 -*-
def isNum(str):
    for i in str:
        if not(i.isdigit()): #判断是否全为数字,非数字返回false
            return False
    return True    #返回TRUE表示全为数字组成
def isChar(str):
    chars = list(str) #将字符串str转换为字符数组
    isPhontic = False
    for i in chars:
        isPhontic = (i >= 'a' and i <= 'z') or (i >= 'A' and i <= 'Z')
        if not isPhontic:
            return False
    return True   
def Encryption(plaintext, key):
    print("加密后为:")
    for i in range(len(plaintext)):
        #ord():把字符转ASCII码,chr():把ASCII码转字符
        if ord('a') <= ord(plaintext[i]) <= ord('z'):  
            print(chr((ord(plaintext[i]) + key - ord('a')) % 26 + ord('a')),end="")
        elif ord('A') <= ord(plaintext[i]) <= ord('Z'):
            print(chr((ord(plaintext[i]) + key - ord('A')) % 26 + ord('A')),end="")
def Decrypt(ciphertext, key):
    print("解密后为:")
    for i in range(len(ciphertext)):
        if ord('a') <= ord(ciphertext[i]) <= ord('z'):
            print(chr((ord(ciphertext[i]) + (0 - key) - ord('a')) % 26 + ord('a')),end="")
        elif ord('A') <= ord(ciphertext[i]) <= ord('Z'):
            print(chr((ord(ciphertext[i]) + (0 - key) - ord('A')) % 26 + ord('A')),end="")            
def operate1():
    plaintext = input("请输入明文:") #plaintext明文
    plaintext = plaintext.replace(" ","") #去除ciphertext密文中的空格
    while(isChar(plaintext) == False): #判断plaintext明文是否全为字母字符
        plaintext = input("请重新输入全字母字符明文:") #输入明文
    key = input("请输入秘钥:")
    while(isNum(key) == False): #如果秘钥key非全为数字
        key = input("秘钥必须是数字,请重新选择:") 
    Encryption(plaintext,int(key)) #使用key对明文plaintext加密
def operate2():
    ciphertext = input("请输入密文:")
    ciphertext = ciphertext.replace(" ","")
    while(isChar(ciphertext) == False): #如果密文中含有非字母字符符号
        ciphertext = input("请重新输入全字母字符密文:")
    key = input("请输入秘钥:")
    while(isNum(key) == False): #如果秘钥key非全为数字
        key = input("秘钥必须是数字,请重新选择:")
    Decrypt(ciphertext,int(key)) #使用key对密文ciphertext解密
def operate3():
    print("谢谢您的使用!")
    print("系统退出成功。。。")
    exit(0)
###################主函数############
operateType = "0"
OperateAll = {"1" : operate1, "2" : operate2, "3" : operate3} #字典操作
while(operateType != 3):
    print("\n")
    print("**********CaesarCipher(python)**********")
    print("    1.明文加密     2.密文解密      3.退出 ")
    print("****************************************")
    operateType = input("请选择菜单功能:")
    while(isNum(operateType) == False): #如果输入的operateType字符非数字
        operateType = input("请重新选择1,2,3数字选项:")
    OperateAll[operateType]() #调用函数

C++实现过程

#include <iostream>
#include <algorithm>
using namespace std;
//判断str字符串是否全为字母字符组成
bool isChar(string s)
{
  bool isPhontic = false; //先假设为非字母组成
  for (int i = 0; i < s.size(); i++){
    char str = s[i];
    isPhontic = (str >= 'a' && str <= 'z') || (str >= 'A' && str <= 'Z');
    if (!isPhontic){ //遍历过程中只要出现了一个非字母字符,则返回非字母字符(false)
      return false; //返回false,表示出现了非字母字符
    }
  }
  return true; //遍历完后没有出现非字母字符,返回true
}
bool isNum(string str)
{
  for (int i = 0; i < str.size(); i++){
    int tmp = (int)str[i];
    if (tmp >= 48 && tmp <= 57)
        continue;
    else
      return false;
  }
  return true;
}
void Encryption(string plaintext, int key)
{
    cout << "加密后为:" << endl;
    for (int i = 0; i < plaintext.size(); i++){
        if ('a' <= plaintext[i] && plaintext[i]<= 'z')  
            cout << char((plaintext[i] + key - 'a') % 26 + 'a');
        else if ('A' <= plaintext[i] && plaintext[i] <= 'Z')
            cout << char((plaintext[i] + key - 'A')% 26 + 'A');
    }
    cout << endl;
}
void Decrypt(string ciphertext, int key)
{
    int k = 0 - key; //k=负key代表解密,其他与加密类似
     string plaintext="";//plaintext表示明文
    for (int i = 0;i < ciphertext.size();i++) {//遍历密文
        char c = ciphertext[i];//通过下标i读取字符
        if (c >= 'a' && c <= 'z'){ //如果字符串中的某个字符是小写字母
            c += k % 26;//移动key%26位
            if (c < 'a')
                c += 26;//向左超界
            if (c > 'z')
                c -= 26;//向右超界
        }else if (c >= 'A' && c <= 'Z'){ //如果字符串中的某个字符是大写字母
            c += k % 26;//移动key%26位
            if(c < 'A')
                c += 26;//向左超界
            if(c > 'Z')
                c -= 26;//向右超界
      }
      plaintext += c;//将解密后的字符c连成字符串
    }
    cout << "解密后为:" << plaintext << endl;
}
string trimAll(string str)
{
    string::iterator pos = str.begin();
    while(1){
        pos = find(pos, str.end(), ' ');
        if(pos == str.end()) break;
        str.erase(pos);
    }
    return str;
}

int main()
{
    int operateType = 0;
    while (operateType != 3){
        cout << "*************CaesarCipher(C++)**********" << endl;
        cout << "1.明文加密      2.密文解密      3.退出    " << endl;
        cout << "****************************************" << endl;
        cin >> operateType;
        switch (operateType){
        case 1:
        {
            cout << "请输入明文:" << endl;
            string plaintext;//plaintext明文
            cin >> plaintext;
            plaintext = trimAll(plaintext);//去除明文中的空格!!!!!!
            while(isChar(plaintext)==false){//判断plaintext明文是否全为字母字符
                cout << "请重新输入全字母字符明文:" << endl;
                cin >> plaintext;//输入明文
            }
            cout << "请输入秘钥:" << endl;
            string key;
            cin >> key;//key为秘钥
            while(isNum(key)==false){   //判断秘钥key是否全为数字
                cout << "秘钥必须是数字,请重新选择:" << endl;
                cin >> key;//重新输入秘钥
            }
            Encryption(plaintext,atoi(key.c_str()));//使用key对明文plaintext加密
            cout << endl;
            break;
        }
        case 2:
        {
            cout << "请输入密文:" << endl;//与加密类似
            string ciphertext;//ciphertext表示密文
            cin >> ciphertext;
            ciphertext = trimAll(ciphertext); //去除ciphertext密文中的空格
            while(isChar(ciphertext)==false){   //如果密文中含有非字母字符符号
                cout << "请重新输入全字母字符密文:" << endl;
                cin >> ciphertext;//重新输入密文ciphertext
            }
            cout << "请输入秘钥:" << endl;
            string key;
            cin >> key;
            while(isNum(key)==false){   //如果秘钥key非数字
                cout << "秘钥必须是数字,请重新选择:" << endl;
                cin >> key;//重新输入数字秘钥
            }
            Decrypt(ciphertext,atoi(key.c_str()));//使用key对密文ciphertext解密
            cout << endl;
            break;
        }
        case 3:
            cout << "谢谢您的使用!" << endl;
            cout << "系统退出成功。。。" << endl;
        break;
        default:
            cout << "请选择1,2,3号数字菜单" << endl;
        break;
        }
    }
}
  • 19
    点赞
  • 87
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值