python2.7 实现 json文件 加密解密

79 阅读3分钟

目标

  • 输入原始路径,是否加密参数;
  • 输出加密/解密文件,删除临时文件夹
  • 加密方式采用base64 嵌套 字符异或
  • 自定义异或密钥,自定义加密标识
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import os.path
import re
import base64
import random
import string
import json
import shutil

encodeKey = 'secret'
preKey = 'secret'

ignoreFiles = [
    "A.json",
    "B.json"
]

def moveFile(infile, outfile):
    inBuffer = ""
    with open(infile, "rb+") as fr:
        inBuffer = fr.read()
    with open(outfile, "wb+") as fw:
        fw.write(inBuffer)

# zipJson
def zipFile(infile, outfile):
    inBuffer = ''
    outBuffer = ''

    with open(infile, 'rb+') as fr:
        inBuffer = fr.read()

    outBuffer = inBuffer.replace("\r\n", '')
    
    outBuffer = re.sub(re.compile(r'\{\s+'), '{', outBuffer)
    outBuffer = re.sub(re.compile(r'\[\s+'), '[', outBuffer)
    outBuffer = re.sub(re.compile(r'\s+\}'), '}', outBuffer)
    outBuffer = re.sub(re.compile(r',\s+'), ',', outBuffer)
    outBuffer = re.sub(re.compile(r':\s'), ':', outBuffer)

    with open(outfile,'wb+') as fw:
        fw.write(outBuffer)

    print infile, 'zip done '


def loadFile(infile, outfile):
    inBuffer = ''
    with open(infile, 'rb+') as fr:
        inBuffer = fr.read()

    outBuffer = json.loads(inBuffer)
    outBuffer = json.dumps(outBuffer, indent=4, encoding="utf-8", sort_keys=True, skipkeys=True, separators=(', ',': '), ensure_ascii=False)

    with open(outfile,'wb+') as fw:
        fw.write(outBuffer)

    print infile, 'load done '


def zipJsonDir(rootdir, outDir):
    for parent,dirnames,filenames in os.walk(rootdir):
        if len(filenames) > 0:
            for filename in filenames:
                if filename in ignoreFiles:
                    continue
                files = filename.partition(".")
                inPath=os.path.join(parent,filename)
                outDir2 = outDir+parent.replace(rootdir, "")
                if not os.path.exists(outDir2):
                    os.makedirs(outDir2)
                outPath=os.path.join(outDir2, filename)
                if len(files) > 2:
                    if files[len(files)-1] == "json":
                        zipFile(inPath, outPath)
                    else:
                        moveFile(inPath, outPath)


def loadJsonDir(rootdir, outDir):
    for parent,dirnames,filenames in os.walk(rootdir):
        if len(filenames) > 0:
            for filename in filenames:
                if filename in ignoreFiles:
                    continue
                files = filename.partition(".")
                inPath=os.path.join(parent,filename)
                outDir2 = outDir+parent.replace(rootdir, "")
                if not os.path.exists(outDir2):
                    os.makedirs(outDir2)
                outPath=os.path.join(outDir2, filename)
                if len(files) > 2:
                    if files[len(files)-1] == "json":
                        loadFile(inPath, outPath)
                    else:
                        moveFile(inPath, outPath)


def base64EncodeFile(infile, outfile):
    inBuffer = ''
    with open(infile, 'rb+') as fr:
        inBuffer = fr.read()

    outBuffer = str(base64.b64encode(inBuffer.encode("utf-8")))

    randomStr = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(2))
    outBuffer = randomStr + outBuffer
    randomStr = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(2))
    outBuffer = outBuffer + randomStr
    
    with open(outfile,'wb+') as fw:
        fw.write(outBuffer)
    print infile, 'base64 encode done '


def base64DecodeFile(infile, outfile):
    inBuffer = ''
    with open(infile, 'rb+') as fr:
        inBuffer = fr.read()

    inBuffer = inBuffer[2:-2]
    outBuffer = str(base64.b64decode(inBuffer))
    with open(outfile,'wb+') as fw:
        fw.write(outBuffer)

    print infile, 'base64 decode done '


def base64EncodeDir(rootdir, outDir):
    for parent,dirnames,filenames in os.walk(rootdir):
        if len(filenames) > 0:
            for filename in filenames:
                if filename in ignoreFiles:
                    continue
                files = filename.partition(".")
                inPath=os.path.join(parent,filename)
                outDir2 = outDir+parent.replace(rootdir, "")
                if not os.path.exists(outDir2):
                    os.makedirs(outDir2)
                outPath=os.path.join(outDir2, filename)
                if len(files) > 2:
                    if files[len(files)-1] == "png" or files[len(files)-1] == "jpg" or files[len(files)-1] == "json":
                        base64EncodeFile(inPath, outPath)
                    else:
                        moveFile(inPath, outPath)


def base64DecodeDir(rootdir, outDir):
    for parent,dirnames,filenames in os.walk(rootdir):
        if len(filenames) > 0:
            for filename in filenames:
                if filename in ignoreFiles:
                    continue
                files = filename.partition(".")
                inPath=os.path.join(parent,filename)
                outDir2 = outDir+parent.replace(rootdir, "")
                if not os.path.exists(outDir2):
                    os.makedirs(outDir2)
                outPath=os.path.join(outDir2, filename)
                if len(files) > 2:
                    if files[len(files)-1] == "png" or files[len(files)-1] == "jpg" or files[len(files)-1] == "json":
                        base64DecodeFile(inPath, outPath)
                    else:
                        moveFile(inPath, outPath)



def xorEncodeFile(infile, outfile):
    inBuffer = ''
    key = getEncodeKey().encode("UTF-8")
    outBuffer = []
    for b in preKey:
        outBuffer.append(b)
    with open(infile, 'rb+') as fr:
        inBuffer = fr.read()
    
    idx = 0
    for b in inBuffer:
        eb = (ord(b) ^ ord(key[idx % len(key)])) # encrypt xor 
        outBuffer.append(eb)
        idx = idx + 1
    
    if (len(outBuffer) - len(inBuffer)) != len(key):
        print("length: %d, out: %d,  outfile: %s" % (len(inBuffer), len(outBuffer), bytes(outBuffer)))
    with open(outfile,'wb+') as fw:
        fw.write(bytes(outBuffer))

    print infile, 'xor encrypt done '



def xorDecodeFile(infile, outfile):
    inBuffer = ''
    key = getEncodeKey().encode("UTF-8")
    outBuffer = ''
    with open(infile, 'rb+') as fr:
        inBuffer = fr.read()

    inBuffer = inBuffer[1:-1].split(',')

    for i in preKey:
        inBuffer.pop(0)
    
    idx = 0
    for b in inBuffer:
        eb = chr(int(b, 10) ^ ord(key[idx % len(key)])) # decrypt xor 
        outBuffer = outBuffer + eb
        idx = idx + 1
    
    with open(outfile,'wb+') as fw:
        fw.write(outBuffer)

    print infile, 'xor decrypt done '



def xorEncodeDir(rootdir, outDir):
    for parent,dirnames,filenames in os.walk(rootdir):
        if len(filenames) > 0:
            for filename in filenames:
                if filename in ignoreFiles:
                    continue
                files = filename.partition(".")
                inPath=os.path.join(parent,filename)
                outDir2 = outDir+parent.replace(rootdir, "")
                if not os.path.exists(outDir2):
                    os.makedirs(outDir2)
                outPath=os.path.join(outDir2, filename)
                # print("outFile: %s" % outPath)
                if len(files) > 2:
                    if files[len(files)-1] == "png" or files[len(files)-1] == "jpg" or files[len(files)-1] == "json":
                        xorEncodeFile(inPath, outPath)
                    else:
                        moveFile(inPath, outPath)


def xorDecodeDir(rootdir, outDir):
    for parent,dirnames,filenames in os.walk(rootdir):
        if len(filenames) > 0:
            for filename in filenames:
                if filename in ignoreFiles:
                    continue
                files = filename.partition(".")
                inPath=os.path.join(parent,filename)
                outDir2 = outDir+parent.replace(rootdir, "")
                if not os.path.exists(outDir2):
                    os.makedirs(outDir2)
                outPath=os.path.join(outDir2, filename)
                if len(files) > 2:
                    if files[len(files)-1] == "png" or files[len(files)-1] == "jpg" or files[len(files)-1] == "json":
                        xorDecodeFile(inPath, outPath)
                    else:
                        moveFile(inPath, outPath)


def moveDir(rootdir, outDir):
    for parent,dirnames,filenames in os.walk(rootdir):
        if len(filenames) > 0:
            for filename in filenames:
                if filename in ignoreFiles:
                    continue
                files = filename.partition(".")
                inPath=os.path.join(parent,filename)
                outDir2 = outDir+parent.replace(rootdir, "")
                if not os.path.exists(outDir2):
                    os.makedirs(outDir2)
                outPath=os.path.join(outDir2, filename)
                moveFile(inPath, outPath)
                print filename, ' move done '


def getEncodeKey():
    return encodeKey



def encodeDir(rootdir):
    folder = os.path.dirname(rootdir)
    src = os.path.basename(rootdir)
    outDir = folder + '\\' + src + "_en"
    
    zipJsonDir(rootdir, outDir)
    base64EncodeDir(outDir, rootdir)
    xorEncodeDir(rootdir, outDir)
    moveDir(outDir, rootdir)
    shutil.rmtree(outDir)


def decodeDir(rootdir):
    folder = os.path.dirname(rootdir)
    src = os.path.basename(rootdir)
    outDir = folder + '\\' + src + "_en"

    xorDecodeDir(rootdir, outDir)
    base64DecodeDir(outDir, rootdir)
    loadJsonDir(rootdir, outDir)
    moveDir(outDir, rootdir)
    shutil.rmtree(outDir)


if len(sys.argv) != 3:
    if len(sys.argv) < 2:
        print('please input import folder ')
    elif len(sys.argv) < 3:
        print('please make encrypt or decrypt ')
else:
    if sys.argv[2] == "true":
        encodeDir(sys.argv[1])
    else:
        decodeDir(sys.argv[1])
        

兼容参数,输入 true 或 false 可以实现 文件夹 下所有 json 加密、解密。