Understanding Permutation Cipher and How To Implement With Python
Understanding Permutation Cipher and How To Implement With Python
Here is an example:
1. We want to encrypt the message THE HACKING BLOG ROCKS and the key is
31254.
2. The length of the key is 5, so divide the message into blocks of 5 characters:
THE H, ACKIN, G BLO, G ROC, KS . Note that the last block has only 2
character, so we pad it with 3 spaces to make the block contains 5 characters.
3. For each block, we need to rearrange the position of the characters. The key is
31254, so we put the 3rd char into the 1st position, the 1st char to the 2nd position,
the 2nd char to the 3rd position, the 5th char to the 4th position, and the 4th char
to the 5th position.
To decrypt the message, we use the same algorithm but reversing the character
placement:
1. We want to decrypt the message ETHH KACNIBG OLRG CO KS and the key
is 31254.
nashruddinamin.com
Web Development and AI - Python, React, Rust. 1
2. We divide the message into blocks of 5 characters: ETHH , KACNI, BG OL, RG
CO, KS .
3. For each block, rearrange the position of the characters. The key is 31254, so
we put the 1st char into the 3rd position, the 2nd char to the 1st position, the 3rd
char into the 2nd position, the 4th char into the 5th position, and the 5th char into
the 4th position.
return result
nashruddinamin.com
Web Development and AI - Python, React, Rust. 2
# Usage example
key = 31254
message = 'THE HACKING BLOG ROCKS'
First, the input message is padded with spaces to make the blocks contain equal
number of characters. Then for each block, a new block is created and filled with the
input characters based on the given key. The new blocks then joined together and
returned as output.
Key Takeaways
In this blog post, we have learned how the permutation cipher works and how to
implement it in Python. Permutation ciphers are a simple and effective way to encrypt
short messages.
Keep in mind that they should not be used for encrypting sensitive information. If you
are looking for a more secure way to encrypt your messages, you should look into the
more modern and secure algorithms such as RSA and AES.
nashruddinamin.com
Web Development and AI - Python, React, Rust. 3