Python ARC4加密

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24459491/article/details/84875650

ARCFour.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import struct
import codecs

g_magic = 0x48594c5a

def ArcFourSecurity(text, password):
    keylen = len(password)
    j = 0
    perm = {}
    for i in range(0, 256):
        perm[i] = i

    for i in range(0, 256):
        j += perm[i]
        j += ord(password[i%keylen])
        k = perm[i]
        perm[i] = perm[j & 0xff]
        perm[j & 0xff] = k

    index1 = 0
    index2 = 0

    codetext=""
    textlen = len(text)
    for i in range(0, textlen):
        index1 = index1 + 1
        index2 += perm[index1 & 0xff]
        k = perm[index1 & 0xff]
        perm[index1 & 0xff] = perm[index2 & 0xff]
        perm[index2 & 0xff] = k
        j = perm[index1 & 0xff] + perm[index2 & 0xff]
        j = j & 0xff
        codetext = codetext + chr((ord(text[i]) ^ perm[j & 0xff]))

    return codetext


def WriteEncryptFileText(srcFilePath, dstFilePath, password):
    fo = open(srcFilePath, "r")
    text = fo.read()
    fo.close()

    codetext = ArcFourSecurity(text, password)

    fo = open(dstFilePath, "wb")
    fo.write(struct.pack('i', g_magic))
    fo.write(struct.pack('i', len(text)))
    fo.write(struct.pack('i', len(codetext)))
    fo.write(codetext)
    fo.write(struct.pack('i', g_magic))
    fo.close()

def ReadEncryptFileText(srcFilePath, dstFilePath, password):
    fo = open(srcFilePath, "rb")

    magic, = struct.unpack('i', fo.read(4))
    if magic != g_magic:
        fo.close()
        return 1
    srclen, = struct.unpack('i', fo.read(4))
    dstlen, = struct.unpack('i', fo.read(4))
    
    codetext = fo.read(dstlen)

    magic, = struct.unpack('i', fo.read(4))
    if magic != g_magic:
        fo.close()
        return 2
    fo.close()

    text = ArcFourSecurity(codetext, password)
    fo = open(dstFilePath, "w")
    fo.write(text)
    fo.close()

#执行命令行
if __name__ == "__main__":
    if len(sys.argv) >= 1 and sys.argv[1] != "":srcFilePath=sys.argv[1]
    if len(sys.argv) >= 2 and sys.argv[2] != "":dstFilePath=sys.argv[2]
    if len(sys.argv) >= 3 and sys.argv[3] != "":flag=sys.argv[3]

    if flag=="encode":
        WriteEncryptFileText(srcFilePath, dstFilePath, "secretkey")
    else:
        ReadEncryptFileText(srcFilePath, dstFilePath, "secretkey")

encode

ARCFourEncode.bat

@echo off
rem 将要加密的文件拖到这里就行

set inputfiletxt=%1
for %%i in ("%inputfiletxt%") do set inputfile=%%~ni
for %%a in ("%inputfiletxt%") do set suffix=%%~xa
set outputfile=%inputfile%_e%suffix%
python ARCFour.py %inputfiletxt% %outputfile% encode

decode

ARCFourDecode.bat

@echo off
rem 将要解密的文件拖到这里就行

set inputfiletxt=%1
for %%i in ("%inputfiletxt%") do set inputfile=%%~ni
for %%a in ("%inputfiletxt%") do set suffix=%%~xa
set outputfile=%inputfile%_d%suffix%
python ARCFour.py %inputfiletxt% %outputfile% decode

猜你喜欢

转载自blog.csdn.net/qq_24459491/article/details/84875650