
ClickBlueWord to Follow Us

Spring
Festival
Happy
SPRING FESTIVAL
Simple encryption algorithms generally include substitution ciphers, transposition ciphers, and simple XOR. The following content consists of two parts: algorithm interpretation and algorithm programming.

KAI
Caesar
SA
Shift
MI
Cipher
MA
Code

Algorithm
Details
Explanation
CAESAR CIPHER
The Caesar cipher algorithm is a typical example of a substitution cipher. The basic idea of the substitution encryption method is to replace each character in the plaintext with another character.
The Caesar cipher, also known as the Caesar shift cipher, is one of the most famous encryption techniques in history. It is named after Julius Caesar, the ruler of ancient Rome, who reportedly used this cipher to protect military information. The basic idea of the Caesar cipher is very simple: shift each letter in the alphabet by a fixed number of positions to achieve encryption.
For example, if we set the shift number to 3, then the original message “HELLO” will be encrypted as “KHOOR”. Each letter is shifted 3 positions to the right, as shown below.


WORKING
PRINCIPLE
1

Determine the Shift Number: First, the sender and receiver need to agree on a shift number, which can be any integer from 1 to 25.

2

Encryption Process: For each letter in the plaintext, convert it to its position in the alphabet (A=0, B=1, …, Z=25), then add the shift number, and take modulo 26 (modulo means remainder), the result is converted back to a letter, which corresponds to the letter in the ciphertext.

3

Decryption Process: In contrast to the encryption process, convert each letter in the ciphertext to its position, subtract the shift number, and take modulo 26 to get the result back to the letter, which corresponds to the letter in the plaintext.


Procedure
Sequence
Writing

1. We need to prepare 3 variables, representing plaintext s1, ciphertext s2, and shift number k.
s1 = input("Please enter plaintext:")
k = 3
s2 = ""
2. We process each character (i) in s1 through iteration, using if-elif-else statements to determine the character due to case differences, and concatenate the processed character to s2.
“chr((ord(i)-65)%26+65+k)” is written as follows:
1. We need to obtain the ASCII value of the current character, thus ord(i), then add the shift number k, completing a simple shift.
2. However, if this letter moves beyond the range of 26 letters, we need to return to the original position, so we should calculate the difference between i and A or a, which may exceed 26, so we take the remainder, and adding 65 gives the character we can move to, i.e., (ord(i)-65)%26.
for i in s1:
if "A" <= i <= "Z":
s2 += chr((ord(i)-65)%26+65+k)
elif "a" <= i <= "z":
s2 += chr((ord(i)-97)+97+k)
else:
print("There are incorrect characters in the plaintext.")
break
3. Finally, output s2, which is the ciphertext.
print(s2)

Complete
Whole
Substitution
Cipher

s1 = input("Please enter plaintext:")
k = 3
s2 = ""
for i in s1:
if "A" <= i <= "Z":
s2 += chr((ord(i)-65)%26+65+k)
elif "a" <= i <= "z":
s2 += chr((ord(i)-97)+97+k)
else:
print("There are incorrect characters in the plaintext.")
break
print(s2)
Expand
Part
The expansion part is to create a program that can both encrypt and decrypt, while utilizing custom functions. The idea is as follows:
The program is divided into four modules: character conversion, encryption, decryption, and main function call, which can be realized through four custom functions change(), encrypt(), decrypt(), main().
1. Custom character conversion function change(), this function converts the input string code into a lowercase letter string between a-z.
2. Custom encryption function encrypt(), encrypts based on the input plaintext string code and key key, generating ciphertext code_new.
3. Custom decryption function decrypt(), decrypts based on the input ciphertext string code and key key, generating plaintext code_new.
4. Custom main function main(). Running main(), allows for encryption and decryption selection through 1 and 2.
[Program Segment]
def change(code,key):
code=code.lower()
m=ord(code)
if m >=97 and m<=122:
m =97+((m-97)+key)%26
return chr(m)
def encrypt(code,key):
code_new=""
for s in code:
code_new+=change(s,key)
print(code_new)
return code_new
def decrypt(code,key):
code_new=""
for s in code:
m=ord(s)-key
if m<97:
m=m+26
code_new+=chr(m)
print(code_new)
return code_new
def main():
print("Please select number 1 or 2:")
print("1: Encrypt")
print("2: Decrypt")
select =input()
if select =="1":
code =input("Please enter the string to encrypt:")
key =int(input("Please enter the shift number:"))
encrypt(code,key)
elif select =="2":
code =input("Please enter the string to decrypt:")
key =int(input("Please enter the shift number:"))
decrypt(code,key)
else:
print("Input error, please try again!")
if __name__=='__main__':
main()
TRANSPOSITION
CIPHER
Algorithm
Details
EXPLANATION
Transposition cipher’s basic idea is to rearrange the positions of characters in the plaintext according to certain rules. The simplest transposition is the reverse method, which outputs the characters in plaintext in reverse order. For example:
Plaintext: ZHENZHOU Ciphertext: UOHZNEHZ

Procedure
Sequence
Writing

Complete
Whole
Substitution
CIPHER

s=input("Please enter plaintext:")
print("Ciphertext is:"+s[::-1])

Simple
Single
XOR
Operation
XOR operation is a logical operation, denoted by the symbol “⊕”. During the operation, the numbers involved in the operation are converted to binary before performing bitwise operations. If two values are different, the XOR result is 1. If two values are the same, the XOR result is 0. The XOR operation has the following characteristics: 0⊕0=0, 0⊕1=1, 1⊕0=1, 1⊕1=0.
For any character, it can be represented in binary encoding form, and the XOR operation of characters is performed on each bit. For example, the string “Hello” (8-bit ASCII representation: 01001000 01100101 01101100 01101100 01101111) can be encrypted using the key 10110001 as follows:
01001000 01100101 01101100 01101100 01101111 (P—plaintext)
⊕ 10110001 10110001 10110001 10110001 10110001 (K—key)
= 11111001 11010100 11011101 11011101 11011110 (C—ciphertext)
(Download the document for a better reading experience)
Simple XOR encryption is performed by XORing the plaintext with the key, and decryption is done by XORing the ciphertext with the same key. That is: P⊕K=C, C⊕K=P.

Procedure
Sequence
Writing

1. First, use input() to get the required plaintext s and key k.
s = input("Please enter plaintext:")
k = input("Please enter the key (8 bits):")
2. Then define a function tentotwo to convert decimal to binary, as detailed in [Number System] Conversion of Number Bases.
def tentotwo(num):
r = 0
s1 = ""
while num != 0:
r = num % 2
s1 = str(r) + s1
num = num // 2
return s1
2. Call the tentotwo function to convert decimal to binary. Note that you need to iterate through s to get the ASCII value of each character in the string and convert it to binary, storing the resulting binary number in s1.
s1=""
for i in s:
s1 += tentotwo(ord(i))
3. Since the binary number obtained may not be a multiple of 8, padding with zeros at the front does not affect the result.
n = len(s1)
while n % 8 != 0:
s1 = "0" + s1
n += 1
4. Then repeat the key so that its length matches s1.
k = k * (len(s1)//8)
5. Define a string s2 as the final result, and loop through the length of s1 (using k’s length won’t affect) to check if the two numbers at the same position are the same, if so, add 0 to s2, otherwise add 1.
s2 = ""
for i in range(len(s1)):
if s1[i] == k[i]:
s2 += "0"
else:
s2 += "1"
4. Finally, output s2, which is the ciphertext.
print(s2)

Complete
Whole
Substitution
CIPHER

s = input("Please enter plaintext:")
k = input("Please enter the key (8 bits):")
def tentotwo(num):
r = 0
s1 = ""
while num != 0:
r = num % 2
s1 = str(r) + s1
num = num // 2
return s1
s1=""
for i in s:
s1 += tentotwo(ord(i))
n = len(s1)
while n % 8 != 0:
s1 = "0" + s1
n += 1
k = k * (len(s1)//8)
s2 = ""
for i in range(len(s1)):
if s1[i] == k[i]:
s2 += "0"
else:
s2 += "1"
print(s2)
PADDING
WITH
EXPAND
DECRYPTION
ALGORITHM
DETAILS
EXPLANATION
The plaintext refers to the original information that has not been encrypted, while the ciphertext refers to the information that has been encrypted. The steps of a certain encryption algorithm are as follows:
I. Remove spaces from the plaintext;
II. Append lowercase letters in alphabetical order at the end of the string to make its length a multiple of k (1<k<=26);
III. Rearrange the string into k groups, extracting elements from the same position in each group and concatenating them to form the ciphertext.
For example: k=3, s=”i am okay”, the encryption process is shown in the figure.

Please answer the following questions:
(1) In the figure, the plaintext is ▲ (Single choice, fill in the letter).
A.i am okay
B.iamokay
C.iamokayab
D.ioyakamab
(2) If s=”today”, k=4, according to the question, after the letter padding step, the new string content is ▲ (Single choice, fill in the letter).
A.todaya
B.todayab
C.todayabc
(3) Define the following append function. The function’s purpose is to remove spaces from the string according to step I, append letters according to step II, making its length a multiple of k, and return the new string after padding. Please fill in the appropriate code in the underlined part.
def append(s,k):
st=space(s) # The space function removes spaces from the string s and returns the string without spaces
n=len(st)
i=ord("a")
while n%k!=0:
st+=chr(i)
i+=1
__________
return st
The code to fill in the underlined part is ▲ (Single choice, fill in the letter: A.n-=1/B.n+=1)
(4) Define the following function place. The function’s function is to rearrange the string according to step III to form a new string, generating ciphertext. Please fill in the appropriate code in the underlined part.
def place(news,k):
n=len(news)
m=n//k
i,j=0,0
ct=""
while i<m:
if j<n:
ct=__①__
j=j+m
else:
i+=1
__②__
return ct
# Main program
s=input("Please enter plaintext:")
k=int(input("Please enter k:"))
news=append(s,k)
print("Ciphertext is:",place(news,k))

Details
Explanation
Frequency

Shenzhen
Group

WeChat Official Account丨Shenzhen Group
Author丨Qilin Chuan Kirinen