Encryption and decryption of Caesar cipher using Python language
introduce
In cryptography, Caesar cipher (English: Caesar cipher), or Caesar encryption, Caesar transformation, transformation encryption, is one of the simplest and most well-known encryption techniques. It is a technique of substitution encryption. All letters in the plaintext are offset backwards (or forwards) by a fixed number on the alphabet and then replaced with ciphertext. For example, when the offset is 3, all letters A will be replaced with D, B with E, and so on. This encryption method is named after Caesar during the Roman Republic, who used this method to communicate with his generals.
Literacy: The decimal ASCII codes corresponding to uppercase letters A to Z are 65 to 90, and the decimal ASCII codes corresponding to lowercase letters a to z are 97 to 122.
method one
The chr() function takes an integer within the range (256) (that is, 0~255) as a parameter, and returns a corresponding character. The return value is the ASCII character corresponding to the current integer. The return value of this function is in the form of a string, for example, input chr(90), the output is 'Z'.
The ord() function corresponds to the chr() function, which inputs the string form of the character in the ASCII character table and returns its sorting position in the character table. For example, input ord('a'), the output is 97.
encryption
str=input("请输入明文:")
n=int(input("请输入密钥:"))
str_encrypt=""
for letter in str:
if letter==" ": #遇到空格选择不加密
letter_encrypt=" "
else:
letter_encrypt=chr((ord(letter)-ord("a") +n) %26 +ord("a"))
str_encrypt += letter_encrypt
print("密文为:",str_encrypt)
decrypt
str=input("请输入密文:")
n=int(input("请输入密钥:"))
str_decrypt=""
for word in str:
if word==" ": #遇到空格选择不解密
word_decrypt=" "
else:
word_decrypt=chr((ord(word)-ord("A") -n) %26 +ord("A"))
str_decrypt = str_decrypt+word_decrypt
print("明文为:",str_decrypt)
advanced
We embed a multi-branch structure so that the program can determine uppercase and lowercase letters at the same time. Only the encryption code is listed here. To decrypt, just replace "+n" with "-n".
str=input("请输入明文:")
n=int(input("请输入密钥:"))
str_encrypt=""
for letter in str:
if "a"<=letter<="z":
str_encrypt +=chr((ord(letter)-ord("a") +n) %26 +ord("a"))
elif "A"<=letter<="Z":
str_encrypt +=chr((ord(letter)-ord("A") +n) %26 +ord("A"))
else:
str_encrypt += letter
print("密文为:",str_encrypt)
Method Two
Use the multi-branch structure to execute commands such as uppercase and lowercase letter determination, encryption, and decryption in the same program.
str = input("请输入一段英文:")
key = int(input("请输入密钥:"))
enc = int(input("0 - 解密\n1 - 加密\n请选择 0 或者 1: "))
str_enc = ""
str_dec = ""
if enc == 1: #加密
for i in str: #用i进行遍历
if i.isupper(): #isupper函数判断i是否为大写字母
i_unicode = ord(i) #找到“i”对应的Unicode码
i_index = ord(i) - ord("A") #计算字母“i”到A(起始)的间距
new_index = (i_index + key) % 26
new_unicode = new_index + ord("A")
new_character = chr(new_unicode) #将Unicode码转换为字符
str_enc += new_character
elif i.islower(): #如果“i”为小写字母
i_unicode = ord(i)
i_index = ord(i) - ord("a")
new_index = (i_index + key) % 26
new_unicode = new_index + ord("a")
new_character = chr(new_unicode)
str_enc = str_enc + new_character
else: #数字或符号
str_enc += i #直接返回“i”
print("密文为:",str_enc)
else: #解密
for k in str:
if k.isupper():
k_unicode = ord(k)
k_index = ord(k) - ord("A")
new_index = (k_index - key) % 26
new_unicode = new_index + ord("A")
new_character = chr(new_unicode)
str_dec = str_dec + new_character
elif k.islower():
k_unicode = ord(k)
k_index = ord(k) - ord("a")
new_index = (k_index - key) % 26
new_unicode = new_index + ord("a")
new_character = chr(new_unicode)
str_dec += new_character
else:
str_dec += k
print("明文为:",str_dec)
Method Three
Using functions to realize the encryption and decryption of Caesar cipher.
def encrypt(str, key):
ciphertext=""
for word in str:
if word.isupper():
ciphertext += chr((ord(word) - 65 + key) % 26 + 65)
elif word.islower():
ciphertext += chr((ord(word) - 97 + key) % 26 + 97)
else:
ciphertext = ciphertext + word
return ciphertext
def decrypt(str, key):
plaintext=""
for word in str:
if word.isupper():
plaintext += chr((ord(word) - 65 - key) % 26 + 65)
elif word.islower():
plaintext += chr((ord(word) - 97 - key) % 26 + 97)
else:
plaintext = plaintext + word
return plaintext
option = int(input("请选择0(解密)或1(加密): "))
if option == 1:
text1=input("请输入明文:")
s1=int(input("请输入密钥:"))
print("密文为:", encrypt(text1, s1))
else:
text2=input("请输入密文:")
s2=int(input("请输入密钥:"))
print("明文为:", decrypt(text2, s2))
Method four
Use other algorithms to encrypt through the function, and also encrypt spaces and symbols.
def option():
while True:
print("请输入enc(加密)或dec(解密),退出请输入q")
mode=input("选择:").lower()
if mode in "enc dec q".split():
return mode
else:
print("请输入正确选项!")
def getKey(mode):
key=0
while key<=0 or key>=26:
try:
key=int(input("请输入密钥(1-26):"))
except:
print("请输入正确密钥!")
if mode=="dec":
key=-key #对密钥进行变换
return key
def getMessage(key):
text=input("请输入一段英文:")
message=""
for i in text:
num=ord(i)
num=num+key
if i.isupper():
if num>ord("Z"):
num=num-26
elif num<ord("A"):
num=num+26
elif i.islower():
if num>ord("z"):
num=num-26
elif num<ord("a"):
num=num+26
message += chr(num)
return message
mode = option()
if mode == "q":
print("欢迎下次使用!")
elif mode == "enc":
key=getKey(mode)
str1=getMessage(key)
print("密文为:",str1)
elif mode == "dec":
key=getKey(mode)
str2=getMessage(key)
print("明文为:",str2)
Brute force cracking Caesar cipher method 1
LETTERS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
LETTERS1="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LETTERS2="abcdefghijklmnopqrstuvwxyz"
text=input("请输入密文:")
for key in range(len(LETTERS)):
str=""
for i in text:
if i in LETTERS:
if i.isupper(): #密文字母为大写
num = LETTERS1.find(i) #在字母里搜索到密文字符的位置
num = num - key
if num<0:
num = num + len(LETTERS1)
str = str + LETTERS1[num] #将解密后字符追加到字符串末尾
elif i.islower(): #密文字母为小写
num = LETTERS2.find(i) #在字母里搜索到密文字符的位置
num = num - key
if num<0:
num = num + len(LETTERS2)
str = str + LETTERS2[num] #将解密后字符追加到字符串末尾
else:
str = str + i #如果密文中内容不在字母里则不解密,直接追加
print('第%d把钥匙的结果是%s' %(key, str)) #显示每一个可能的值
Brute force cracking Caesar cipher method 2
def unlock(text):
for i in text:
if 65+key<=ord(text)<92 or 97+key<=ord(text)<123:
text=chr(ord(text)-key)
elif 65<=ord(text)<65+key or 97<=ord(text)<97+key:
text=chr(ord(text)-key+26)
else:
text=text
return text
text=input("请输入密文:")
plaintext=""
for key in range(1,27):
for k in list(map(unlock,text)):
plaintext=plaintext+k
print("第%d把钥匙的结果是%s"%(key,plaintext))
plaintext=""
that's all.