1. Introduction to Caesar Cipher:
English letters are processed in a replacement manner, and each English character is cyclically replaced with the third character after the character in the alphabet sequence, that is, a cyclic right shift of 3 bits.
Plain text alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Cipher text alphabet: DEFGHIJKLMNOPQRSTUVWXYZABC
If the offset bit is set to n, the encryption and decryption formula can be obtained:
2. Algorithm implementation
1. Simple version (only encryption of lowercase English strings is implemented)
def encrypt(s):
ciphertext = ''
for i in s:
i = chr(ord('a')+(ord(i) - ord('a') + 3) % 26)
ciphertext += i
return ciphertext
def decrypt(s):
message = ''
for i in s:
i = chr(ord('a')+(ord(i) - ord('a') - 3) % 26)
message += i
return message
if __name__ == '__main__':
s = input('请输入一串小写字母组成的字符串:')
print(f'将{s}加密后的密文 =', encrypt(s))
print(f'将{s}解密后的明文 =' , decrypt(s))
2. Upgraded version (encryption of Chinese and English)
def encrypt(s):
ciphertext = ''
for i in s:
if 'a' <= i <= 'z':
# 判断小写字母
i = chr(ord('a') + (ord(i) - ord('a') + 3) % 26)
elif 'A' <= i <= 'Z':
# 判断大写字母
i = chr(ord('A') + (ord(i) - ord('A') + 3) % 26)
elif 0x4E00 <= ord(i) <= 0x9FA5:
# 判断中文字符
i = chr(ord(i) + 3)
else:
# 其他字符不做加密
pass
# 生成密文
ciphertext += i
return ciphertext
def decrypt(s):
message = ''
for i in s:
if 'a' <= i <= 'z':
# 判断小写字母
i = chr(ord('a') + (ord(i) - ord('a') - 3) % 26)
elif 'A' <= i <= 'Z':
# 判断大写字母
i = chr(ord('A') + (ord(i) - ord('A') - 3) % 26)
elif 0x4E00 <= ord(i) <= 0x9FA5:
# 判断中文字符
i = chr(ord(i) - 3)
else:
# 其他字符不做加密
pass
# 生成密文
message += i
return message
if __name__ == '__main__':
s = input('请输入一串小写字母组成的字符串:')
print(f'将"{s}"加密后的密文 =', encrypt(s))
print(f'将"{s}"解密后的明文 =' , decrypt(s))