[PYTHON] False encryption of images when squeezing

what's this

A guy who calculates noise based on a predetermined code and puts it in an image. Decryptable.

table of contents

  1. Encryption
  2. Decryption
  3. Get the code applied 4, postscript

encryption

Decide the encryption of the character string and calculate the ascii code. Calculate the number of lines and the remainder of the cipher length for each line of the image to make the noise value. Adds noise to all pixels in the row.

For example, my code is "ore mo waru katta" (I was also bad) → _ →. The ascii code is [111, 114, 101, 95, 109, 111, 95, 119, 97, 114, 117, 95, 107, 97, 116, 116, 97]. gmag.jpg ↑ I'll add noise to this

encode.py


def encode(x,key):
    return ((255,x+key) if x+key<=255 else (0,x-255+key))

↑ With this, the value of the noise to be put in the pixel is calculated. Add noise to the pixel value, subtract 255 if it exceeds 255, and return 0 and the result of the calculation. If it does not exceed 1, return 1 and the result. I'm sorry it's too simple. .. .. So, for the whole image, do this.

encode_img.py


def encode_image(img):
    ori_img = plt.imread(img)
    encode_img = np.array(ori_img,dtype='uint8')
    with open('{}_code.txt'.format(img[:-4]),'w') as f:
        for sub_array in encode_img[:,:,-1]:
            f.write(str(list(sub_array)).replace('[','').replace(']','')+',')
    f.close()
    for x in range(encode_img.shape[0]):
        for y in encode_img[x]:
            y[-1] == 255
            key = password[x%len(password)]
            y[-1],y[1] = (encode(y[1],key))
    img_name = 'encode_'+img[:-4]+'.png'
    plt.imshow(encode_img)
    print(img_name)
    plt.imsave(img_name,encode_img)

Noise is added to the second channel of the pixel, and the fourth channel is used as a'flag for subtracting '255'. By setting it to 0 if it is subtracted and 1 if it is not subtracted, it is decided whether to add 255 based on the value of the 4th channel when decoding. (By the way, this method seems to be stupid ...) (Since I have to know the 4th channel of the original image for perfect decoding, I saved it in txt ...) (It's becoming more like a fool ...) When! After encrypting, the previous image looks like this! ↓ gmag.png Alright, you can't use it anymore!

Decryption

Subtract the value added to the 2nd channel and copy the 4th channel of the original image directly to the 4th channel ... (It seems to be really stupid here) By the way, the 4th channel of the original image is'Image name_code I saved it in .txt'.

decode.py


def decode(x,flag,key):
    return (x-key if flag==255 else x+255-key)

↑ By the way, this flag is the numerical value of the 4th channel. So, here, ask the other party to enter the encryption and use the input ascii code as the decryption key. In other words, you can't decrypt correctly unless you enter the correct cipher.

decode_img.py


def test(input_):
    for file in os.listdir():
        if file.endswith('.png'):
            encode_img = plt.imread(file)
            encode_img = np.array(encode_img*255,dtype='uint8')
            img = copy.deepcopy(encode_img)
            with open (file[:-4]+'_code.txt','r') as f:
                txt = f.read()
            f.close()
            code_array = np.fromstring(txt, dtype=int, sep=',')
            code_array = code_array.reshape(encode_img.shape[:2])
            input_password = []
            for i in str(input_):
                input_password.append(ord(str(i)))
            print('password:',input_password)
            for x in range(img.shape[0]):
                for y in img[x]:
                    key = input_password[x%len(input_password)]
                    y[1] = decode(y[1],y[-1],key)
            img[:,:,-1] = code_array
            plt.imsave('result/{}.jpg'.format(file[:-4]+input_),img)
            print('result saved as /result/{}.jpg'.format(file[:-4]+input_))

if __name__=='__main__':
    test(input('please input the password:\n'))

So, for example, if you enter "'onigunsou'" (demon sergeant) gmagonigunsou.jpg I did this! What if I enter "'ore mo waru katta'"? gmagore mo waru katta.jpg well done.

Get the code applied

The rest is easy.

guess_password.py


password = [111, 114, 101, 95, 109, 111, 95, 119, 97, 114, 117, 95, 107, 97, 116, 116, 97]
init = '---_--_----_-----'

def guess_password(ate):
    guess = input('please guess the password\n')
    for i in guess:
        if ord(i) in password and  i not in ate:
            ate.append(i)
    print(ate)
    result = ''
    for  j in range(len(password)):
        result +=(chr(password[j]) if chr(password[j]) in ate else init[j])
    print(result)
    return result

def start():
    init = '---_--_----_-----'
    ate = ['_']
    result = guess_password(ate)
    while not all(chr(k) in ate for k in password):
        result = guess_password(ate)
    print('Congrats! PIN is{}you know.\n I was also bad.'.format(result))

if __name__ == '__main__':
    start()

I will ask you to apply the code. By the way, it looks like this. スクリーンショット 2020-01-16 17.18.04.png Even if you enter all the English letters with violence, you can solve it ... It's a cryptographic system that is kind to the other party, isn't it?

Postscript

S-kun asked me to make a graph, but the next day I got into a fight. Of course I was bad, but my opponent was also a demon sergeant. .. .. To be honest, I was a little angry and didn't want to send it. but! Even if you say that you are lonely, you will do what you should do. If you don't, you'll become a person without a sense of responsibility. I thought, I sent one of the graphs I made, admitted my fault, and said, "I'm sorry. I'm sorry." However, the other party's reply was late, and he proudly wrote, "Please give me another one."

I don't think anyone will use it, so I wrote the code moderately. Well, it was a programming practice and it was fun! I feel like I've used all the wisdom of my life ...

Recommended Posts

False encryption of images when squeezing
Behavior when Trainable = False of Container in Keras
List of self-made Docker images
Optimal placement of multiple images
Faster loading of Python images