找回密码
 立即注册
注册 登录
×
热搜: 活动 交友 discuz
查看: 62|回复: 0

用python做了个加密解密小程序

[复制链接]

2

主题

3

帖子

7

积分

新手上路

Rank: 1

积分
7
发表于 2022-12-21 09:51:59 | 显示全部楼层 |阅读模式
最近在学python。突然想到了小时候看《查理九世》里面的一个加密方法:


我不知道这种加密方法应该叫什么名字,但是简单来说就是先给出要加密的英文文字,然后再给出密钥a=(一个字母),
e.g.
要加密的文字是Iamgoodkid
我们给出一个密钥a=w
加密过程就是按字母表顺序,
原文字中的a对应w,b对应x,c对应y,d对应z,e再对应a...
于是我做了个程序:



用a=w的密钥加密Iamgoodkid

同时,由加密过程很容易得出解密过程,只要有密钥,于是我也做了解密程序:



用a=t的密钥还原密码GhBtfghmtzhhwdbw

然而有时候我们可能只拥有密码不知道密钥,但是密钥只有二十六中可能性(其实是二十五种,毕竟a=a相当于没加密),于是我们可以把所有密钥都是一遍来找出可能的答案



KFCCrazyThursdayVme50

从这些图片中可以看出,这个程序对于大小写是通用的。
刚学了一学期python,目前感觉很肝很好玩^_^
alphabet="abcdefghijklmnopqrstuvwxyz"
ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encryption():
    global key
   
    step=alphabet.index(key)
    textout=""
    for i in range(len(textin)):
        if textin in alphabet:
            letter = alphabet[(alphabet.index(textin)+step)%26]
            textout = textout + letter
        elif textin in ALPHABET:
            letter = ALPHABET[(ALPHABET.index(textin)+step)%26]
            textout = textout + letter
        else:
            textout = textout + textin
    print(textout)
   
def decryption():
    global key   
    step=alphabet.index(key)
    textout=""
    for i in range(len(textin)):
        if textin in alphabet:
            letter = alphabet[(alphabet.index(textin)-step)%26]
            textout = textout + letter
        elif textin in ALPHABET:
            letter = ALPHABET[(ALPHABET.index(textin)-step)%26]
            textout = textout + letter
        else:
            textout = textout + textin
    print(textout)
   
        
while True:
    answer=int(input("Please select the mode: Encryptionion mode - 1, Decryption mode - 2, Stop the program - 3"))
    if answer == 1:
        textin=input("Please type the text to be encrypted:")
        key = input("Please input the key: a=? (a to z)")
        if key in alphabet:
            encryption()
        else:
            print("Invalid Key!")
            continue
    elif answer == 2:
        textin =input("Please type the text to be decrypted:")
        answer2=int(input("Do you know the key? Yes-1, No-2"))
        if answer2 ==1:
            key = input("Please input the key: a=? (a to z)")
            if key in alphabet:
                decryption()
            else:
                print("Invalid Key!")
                continue
        elif answer2 == 2:
            print("Then all the possible answers will be shown.")
            for key in alphabet:
                decryption()
        else:
            continue
    elif answer == 3:
        break
    else:
        continue




KFCCrazyThursdayVme50

明天就是final啦~
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋| 黑客通

GMT+8, 2025-10-14 01:57 , Processed in 0.386701 second(s), 22 queries .

Powered by Discuz! X3.4

Copyright © 2020, LianLian.

快速回复 返回顶部 返回列表