The bitwise exclusive or

To realize image encryption and decryption, we need to master the bitwise xor method in mathematics first.

Xor is also called half addition, and its operation is similar to binary addition without carry. In Python, xOR calculations are performed with the ^ symbol. Here’s a table that explains bitwise XOR:

Count 1 Count 2 The results of Python code
0 0 0 0 ^ 0
0 1 1 0 ^ 1
1 0 1 1 ^ 0
1 1 0 1 ^ 1

A simple generalization of the bitwise xOR operation is that the same two numbers are treated as 0, and different two numbers are treated as 1. Bitwise or not only used for image encryption and decryption, but also through its statistics of different numbers.

What is image encryption and decryption

Image encryption definition: by bitwise xOR operation of the original image and the key image.

Image decryption definition: the encryption of the image and the key image by xOR operation.

From the image encryption and decryption can be seen, they are the same operation.

We now specify xOR as the literal symbol. Based on the bitwise XOR operation above, we assume:

xor(a,b)=c

Then we can get:

xor(c,b)=a

Or:

xor(c,a)=b

To sum up, we assume that A is the original image data and B is the key, so C calculated by XOR (a, C) is the encrypted ciphertext. Simple summary of encryption and decryption.

Encryption process: Perform bitwise xOR operation between image A and key B to complete encryption and obtain ciphertext C.

Decryption process: perform bitwise xOR operation between ciphertext C and key B to complete decryption and obtain image A.

Encrypt the image

Now that we have fully mastered the principle of image encryption and decryption, let’s achieve an image encryption through the code. Again, here we get a grayscale image.

import cv2
import numpy as np

img = cv2.imread("4.jpg".0)
r, c = img.shape
key = np.random.randint(0.256, size=[r, c], dtype=np.uint8)
encryption = cv2.bitwise_xor(img, key)

cv2.imshow("111", encryption)
cv2.waitKey()
cv2.destroyAllWindows()
Copy the code

After running, we get a garbled image:

Decrypt the image

Decrypt the image through bitwise xOR operation, here we only need to use the encrypted image and key to carry out bitwise Xor, the complete code is as follows:

import cv2
import numpy as np

img = cv2.imread("4.jpg".0)
r, c = img.shape
key = np.random.randint(0.256, size=[r, c], dtype=np.uint8)
encryption = cv2.bitwise_xor(img, key)
decryption = cv2.bitwise_xor(encryption, key)
cv2.imshow("111", encryption)
cv2.imshow("222", decryption )
cv2.waitKey()
cv2.destroyAllWindows()
Copy the code

After running, we can get the original image and the encrypted image: