Python ARC4加密
ARCFour.py#!/usr/bin/env python# -*- coding: utf-8 -*-import osimport sysimport structimport codecsg_magic = 0x48594c5adef ArcFourSecurity(text, password):keylen = len(password)j ...
·
#!/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
@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
@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
更多推荐
已为社区贡献1条内容
所有评论(0)