Cryptography With Python 简明教程
Cryptography with Python - Caesar Cipher
在上一章中,我们已经处理了反向密码。本章详细介绍了凯撒密码。
In the last chapter, we have dealt with reverse cipher. This chapter talks about Caesar cipher in detail.
Algorithm of Caesar Cipher
凯撒密码算法具有以下特征:
The algorithm of Caesar cipher holds the following features −
-
Caesar Cipher Technique is the simple and easy method of encryption technique.
-
It is simple type of substitution cipher.
-
Each letter of plain text is replaced by a letter with some fixed number of positions down with alphabet.
-
以下图表描述了凯撒密码算法实现的工作原理:
The following diagram depicts the working of Caesar cipher algorithm implementation −

凯撒密码算法的程序实现如下:
The program implementation of Caesar cipher algorithm is as follows −
def encrypt(text,s):
result = ""
# transverse the plain text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters in plain text
if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)
# Encrypt lowercase characters in plain text
else:
result += chr((ord(char) + s - 97) % 26 + 97)
return result
#check the above function
text = "CEASER CIPHER DEMO"
s = 4
print "Plain Text : " + text
print "Shift pattern : " + str(s)
print "Cipher: " + encrypt(text,s)
Output
你可以看到凯撒密码,即下图所示的输出−
You can see the Caesar cipher, that is the output as shown in the following image −

Explanation
一次遍历一个纯文本字符。
The plain text character is traversed one at a time.
-
For each character in the given plain text, transform the given character as per the rule depending on the procedure of encryption and decryption of text.
-
After the steps is followed, a new string is generated which is referred as cipher text.
Hacking of Caesar Cipher Algorithm
密文可以用各种可能性破解。其中一种可能性是 Brute Force Technique, ,它涉及尝试每个可能的解密密钥。此技术不需要太多精力,对于黑客来说相对简单。
The cipher text can be hacked with various possibilities. One of such possibility is Brute Force Technique, which involves trying every possible decryption key. This technique does not demand much effort and is relatively simple for a hacker.
破解凯撒密码算法的程序实现如下−
The program implementation for hacking Caesar cipher algorithm is as follows −
message = 'GIEWIVrGMTLIVrHIQS' #encrypted message
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for key in range(len(LETTERS)):
translated = ''
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
num = num - key
if num < 0:
num = num + len(LETTERS)
translated = translated + LETTERS[num]
else:
translated = translated + symbol
print('Hacking key #%s: %s' % (key, translated))
考虑在前一示例中加密的密文。然后,使用密钥并使用暴力攻击技术,可能的破解方法的输出如下−
Consider the cipher text encrypted in the previous example. Then, the output with possible hacking methods with the key and using brute force attack technique is as follows −
