1. 程式人生 > 其它 >python3 實現RC4加解密

python3 實現RC4加解密

Python 實現RC4加解密

核心原理如下:

  • 匯入包ARC4 其中Crypto如果沒有可以網上搜索安裝
  • 主要就是利用ARC4的new(傳入key) 返回一個rc4物件
  • rc4物件在呼叫加密或者解密函式. 注意key必須是 bytes型別.如果不是要轉換為bytes
  • 對於base64編碼過的程式請先解碼.然後再用
    程式碼如下:
import sys
import base64
from Crypto.Cipher import  ARC4

class rc4util():
    def __init__(self,key):
        if isinstance(key,str):
            self.__keyGen = key.encode()
        elif isinstance(key,bytes):
            self.__keyGen = key
    def __encrypt(self,data)->bytes:
        rc4 = ARC4.new( self.__keyGen)
        res = rc4.encrypt(data)
        return res
    def __decrypt(self,data)->bytes:
        rc4 = ARC4.new(self.__keyGen)
        res = rc4.decrypt(data)
        #res = base64.b64encode(res)
        return res
    def EncryptFileToDst(self,src,dst)->bool:
        with open(src,"rb") as f_read:
            data = f_read.read()
            res = self.__decrypt(data)
            with open(dst,"wb") as f_write:
                f_write.write(res)
        return True
def Entry(src,dst):
    key = bytes([0xD8, 0x7e, 0x54, 0x32, 0x61, 0x47, 0x33, 0x55]);
    rc4 = rc4util(key)
    bret = rc4.EncryptFileToDst(src,dst)
    if bret:
        print("加密成功")
    else:
        print("加密失敗")
def Decry(src,dst):
    key = bytes([0xD8, 0x7e, 0x54, 0x32, 0x61, 0x47, 0x33, 0x55]);
    rc4 = rc4util(key)
    bret = rc4.EncryptFileToDst(src,dst)
    if bret:
        print("加密成功")
    else:
        print("加密失敗")

if __name__ == "__main__":
    src = r"xxxsrcFile"  #這裡是讀取src檔案資料,然後對其進行加密.加密的結果寫入到dst檔案中
    dst = r"xxxdstFile"
    Entry(src,dst);