RC4無損加密和解密圖片

前言

  RC4加密算法的特點在於其簡單易且高效,一個簡單的異或運算就能夠對文本進行加密。而且RC4的加密算法是對稱的,即原圖經過一次RC4操作即得到加密圖片,加密圖片經過一次RC4操作,即得到解密圖片。

代碼

# -*- coding: utf-8 -*-
'''
date:2019/11/2
功能:主要用於RC4的加密和解密
算法介紹:RC4是經典的對稱加密算法
即RC4(原文+密鑰)=密文
RC4(密文+密鑰)=原文
'''
import numpy as np
import cv2
MOD=256

#密鑰填充至256位
def KSA(key):
    keylen = len(key)
    # create the array S
    S = list(range(MOD))
    i = 0
    j = 0
    for i in range(MOD):
        j = (j+S[i]+key[i % keylen]) % MOD
        S[i],S[j] = S[j],S[i]
    return S

class RC4:
    def __init__(self,_key =np.random.randint(0,255,(256))):      
        self.key = KSA(_key)

    #使用RC4_img加密圖片
    def RC4_img(self,filepath):
        frame = cv2.imread(filepath)
        height = frame.shape[0]
        weight = frame.shape[1]
        channels = frame.shape[2]
        i = 0
        for row in range(height):            #遍歷高
            for col in range(weight):         #遍歷寬
                for c in range(channels):     #便利通道
                    frame[row, col, c] =frame[row, col, c] ^ self.key[i%MOD]
                    i+=1
        return frame
      

    def RC4(self,data):
        new_data = []
        for i in range(data):
            _ = data[i]^self.key[i%MOD]
            new_data.append(_)
            return new_data
    #記錄下當前的密鑰
    def write_key(self,filepath="./keytxt"):
        file = open(filepath,'w')
        for i in range(len(self.key)):
            file.write(str(self.key[i]))
            file.write('\n')
        file.close()
    #讀取密鑰
    def read_key(self,filepath="./keytxt"):
        file = open(filepath,'r')
        _key = []
        for line in file:
            _key.append(int(line))
        self.key = KSA(_key)
if __name__=="__main__":
    enimg = RC4()
    enimg.write_key()
    frame = enimg.RC4_img("./liuyifei.bmp")
    cv2.imwrite("myRC4en.bmp",frame)
    frame = enimg.RC4_img("myRC4en.bmp")
    cv2.imwrite("myRC4de.bmp",frame)

加密前
在這裏插入圖片描述
加密後
在這裏插入圖片描述
解密後
在這裏插入圖片描述

如果你對Python學習感興趣

  你可以通過此鏈接購買我們的學習課程,課程對python語法和算法有深入的講解。
  你也可以加入我們的QQ羣(916372346),學習Python。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章