桓楠百科网

编程知识、经典语录与百科知识分享平台

来了,Python终于可以不用源码发布了,代码加密2种思想

我们在使用Python做完项目后,给客户去部署,但是又不想让客户看到自己的代码,这时我们怎么办?

下面就来介绍不使用Python源码发布的两种思想:

发布编译版本

我们可以让Python的源码直接生成2进制的文件,从而达到避免源码暴露的问题,编译方式有以下几种:

pyc文件

.pyc文件是.py文件动态编译后生成的能够被Cpython解释器解释的二进制代码,可以直接在.py引入,就像我们引用模块一样使用,非常简单方便,使用方法:

$ python3 -m compileall -b .      // -b添加生成.pyc文件具有版本号
$ python3 -O -m compileall -b .	 // 进行优化

生成.pyc后我们可以直接将.py的源码文件删除掉了

find <src> -name '*.py' -type f -print -exec rm {} \;

优点

  • 为破解提高了一点点门槛儿
  • 兼容性好,.py能运行,.pyc就能运行

缺点

  • 解释器兼容性差,.pyc 只能在特定版本的解释器上运行
  • 有现成的反编译工具,破解成本低

python-uncompyle6 工具可以将.pyc文件反向编译成.py文件,效果很好。

生成可执行文件

我们可以利用pyinstall和py2exe将python代码直接编译成可执行文件,具体方法可以自行百度查询。

优点

  • 破解难度增加
  • 方便目标机器运行

缺点

  • 兼容性差,容易引起.so文件未找到的问题
  • 可以按照规则找到.pyc文件进行反编译

编译生成.so文件

我们可以将python代码翻译成C代码,并且进一步进行编译生成.so动态链接文件,我们可以使用.py文件直接引用这个文件中的模块儿。

这个我们需要更换另一种解释器Cython解释器,Cython使用方法请大家自行百度,这里篇幅有限,不再赘述。

优点

  • 二进制文件难以破解
  • 可以突破python中的GIL的限制
  • 引用方便

缺点

  • 兼容性差,更换平台需要重新进行编译
  • 对于python代码的支持不是100%的完美,可能会有方法未定义的问题

利用其他虚拟机

Jython和IronPython两种解释器,利用了Java和.net的平台,编译生成的包可以直接使用jvm和.net进行运行,除了这两个平台还有其他的第三方解释器。

优点

  • 文件破解难
  • 可以突破GIL的限制

缺点

  • 支持的第三方包少,如果要使用可能会进行二次开发
  • 需要借助其他平台

代码混淆

代码混淆的本质就是让代码变得谁都看不懂,但是代码逻辑还是之前的逻辑,其中比较出色的代码混淆工具给大家介绍两款。

具体命令我就不给大家介绍了,主要贴出混淆前后的代码对比。

  • oxyry

源代码

"""The n queens puzzle.

https://github.com/sol-prog/N-Queens-Puzzle/blob/master/nqueens.py
"""

__all__ = []

class NQueens:
    """Generate all valid solutions for the n queens puzzle"""
    
    def __init__(self, size):
        # Store the puzzle (problem) size and the number of valid solutions
        self.__size = size
        self.__solutions = 0
        self.__solve()

    def __solve(self):
        """Solve the n queens puzzle and print the number of solutions"""
        positions = [-1] * self.__size
        self.__put_queen(positions, 0)
        print("Found", self.__solutions, "solutions.")

    def __put_queen(self, positions, target_row):
        """
        Try to place a queen on target_row by checking all N possible cases.
        If a valid place is found the function calls itself trying to place a queen
        on the next row until all N queens are placed on the NxN board.
        """
        # Base (stop) case - all N rows are occupied
        if target_row == self.__size:
            self.__show_full_board(positions)
            self.__solutions += 1
        else:
            # For all N columns positions try to place a queen
            for column in range(self.__size):
                # Reject all invalid positions
                if self.__check_place(positions, target_row, column):
                    positions[target_row] = column
                    self.__put_queen(positions, target_row + 1)


    def __check_place(self, positions, ocuppied_rows, column):
        """
        Check if a given position is under attack from any of
        the previously placed queens (check column and diagonal positions)
        """
        for i in range(ocuppied_rows):
            if positions[i] == column or \
                positions[i] - i == column - ocuppied_rows or \
                positions[i] + i == column + ocuppied_rows:

                return False
        return True

    def __show_full_board(self, positions):
        """Show the full NxN board"""
        for row in range(self.__size):
            line = ""
            for column in range(self.__size):
                if positions[row] == column:
                    line += "Q "
                else:
                    line += ". "
            print(line)
        print("\n")

    def __show_short_board(self, positions):
        """
        Show the queens positions on the board in compressed form,
        each number represent the occupied column position in the corresponding row.
        """
        line = ""
        for i in range(self.__size):
            line += str(positions[i]) + " "
        print(line)

def main():
    """Initialize and solve the n queens puzzle"""
    NQueens(8)

if __name__ == "__main__":
    # execute only if run as a script
    main()

混淆后

""#line:4
__all__ =[]#line:6
class OOO000O0OOOO0O0O0 :#line:8
    ""#line:9
    def __init__ (O0OO0O00OOOO00OO0 ,O0000OO0OO0OO0OOO ):#line:11
        O0OO0O00OOOO00OO0 .__OO0O0O000OO00O000 =O0000OO0OO0OO0OOO #line:13
        O0OO0O00OOOO00OO0 .__OOOOOOO0O0OOO00O0 =0 #line:14
        O0OO0O00OOOO00OO0 .__OO000OO0O00OOOOOO ()#line:15
    def __OO000OO0O00OOOOOO (OO00OOO000O0OOO0O ):#line:17
        ""#line:18
        OO00OO00O000000O0 =[-1 ]*OO00OOO000O0OOO0O .__OO0O0O000OO00O000 #line:19
        OO00OOO000O0OOO0O .__OO0O000OO0OOO0O0O (OO00OO00O000000O0 ,0 )#line:20
        print ("Found",OO00OOO000O0OOO0O .__OOOOOOO0O0OOO00O0 ,"solutions.")#line:21
    def __OO0O000OO0OOO0O0O (O0O00OOOOOOO00OO0 ,OOOOO0O0O0OOOO0OO ,OOO00O00O00OOO0O0 ):#line:23
        ""#line:28
        if OOO00O00O00OOO0O0 ==O0O00OOOOOOO00OO0 .__OO0O0O000OO00O000 :#line:30
            O0O00OOOOOOO00OO0 .__O0O0O0O0O0O00O0OO (OOOOO0O0O0OOOO0OO )#line:31
            O0O00OOOOOOO00OO0 .__OOOOOOO0O0OOO00O0 +=1 #line:32
        else :#line:33
            for OOO00O0O0OOOOO0O0 in range (O0O00OOOOOOO00OO0 .__OO0O0O000OO00O000 ):#line:35
                if O0O00OOOOOOO00OO0 .__O0O000O0O0O0OOO00 (OOOOO0O0O0OOOO0OO ,OOO00O00O00OOO0O0 ,OOO00O0O0OOOOO0O0 ):#line:37
                    OOOOO0O0O0OOOO0OO [OOO00O00O00OOO0O0 ]=OOO00O0O0OOOOO0O0 #line:38
                    O0O00OOOOOOO00OO0 .__OO0O000OO0OOO0O0O (OOOOO0O0O0OOOO0OO ,OOO00O00O00OOO0O0 +1 )#line:39
    def __O0O000O0O0O0OOO00 (OOO0000O0OOO00O00 ,O0000OO00O0OOOOO0 ,O0O00000OOO0OOOO0 ,OO0OOO00OO000OO0O ):#line:42
        ""#line:46
        for OOO00O0OO0O00000O in range (O0O00000OOO0OOOO0 ):#line:47
            if O0000OO00O0OOOOO0 [OOO00O0OO0O00000O ]==OO0OOO00OO000OO0O or O0000OO00O0OOOOO0 [OOO00O0OO0O00000O ]-OOO00O0OO0O00000O ==OO0OOO00OO000OO0O -O0O00000OOO0OOOO0 or O0000OO00O0OOOOO0 [OOO00O0OO0O00000O ]+OOO00O0OO0O00000O ==OO0OOO00OO000OO0O +O0O00000OOO0OOOO0 :#line:50
                return False #line:52
        return True #line:53
    def __O0O0O0O0O0O00O0OO (OOO0O0O000O0OOOO0 ,O0OOOO00000000O0O ):#line:55
        ""#line:56
        for O0O00O000O0O00O0O in range (OOO0O0O000O0OOOO0 .__OO0O0O000OO00O000 ):#line:57
            OOO0O00OOOOO0O00O =""#line:58
            for OOOOOO00OO0O00O00 in range (OOO0O0O000O0OOOO0 .__OO0O0O000OO00O000 ):#line:59
                if O0OOOO00000000O0O [O0O00O000O0O00O0O ]==OOOOOO00OO0O00O00 :#line:60
                    OOO0O00OOOOO0O00O +="Q "#line:61
                else :#line:62
                    OOO0O00OOOOO0O00O +=". "#line:63
            print (OOO0O00OOOOO0O00O )#line:64
        print ("\n")#line:65
    def __O000OOOO0OO000O00 (OOOO00O0000O00000 ,OOOO0O0OO0O00O00O ):#line:67
        ""#line:71
        O0OO0OO0000O00OO0 =""#line:72
        for OO0O000O0O000OO00 in range (OOOO00O0000O00000 .__OO0O0O000OO00O000 ):#line:73
            O0OO0OO0000O00OO0 +=str (OOOO0O0OO0O00O00O [OO0O000O0O000OO00 ])+" "#line:74
        print (O0OO0OO0000O00OO0 )#line:75
def O000O0O00O00OO0OO ():#line:77
    ""#line:78
    OOO000O0OOOO0O0O0 (8 )#line:79
if __name__ =="__main__":#line:81
    O000O0O00O00OO0OO ()#line:83

看到代码我们是这样的表情

  • pyminifier

源代码

#!/usr/bin/env python
"""
tumult.py - Because everyone needs a little chaos every now and again.
"""

try:
    import demiurgic
except ImportError:
    print("Warning: You're not demiurgic. Actually, I think that's normal.")
try:
    import mystificate
except ImportError:
    print("Warning: Dark voodoo may be unreliable.")

# Globals
ATLAS = False # Nothing holds up the world by default

class Foo(object):
    """
    The Foo class is an abstract flabbergaster that when instantiated
    represents a discrete dextrogyratory inversion of a cattywompus
    octothorp.
    """
    def __init__(self, *args, **kwargs):
        """
        The initialization vector whereby the ineffably obstreperous
        becomes paramount.
        """
        # TODO.  BTW: What happens if we remove that docstring? :)

    def demiurgic_mystificator(self, dactyl):
        """
        A vainglorious implementation of bedizenment.
        """
        inception = demiurgic.palpitation(dactyl) # Note the imported call
        demarcation = mystificate.dark_voodoo(inception)
        return demarcation

    def test(self, whatever):
        """
        This test method tests the test by testing your patience.
        """
        print(whatever)

if __name__ == "__main__":
    print("Forming...")
    f = Foo("epicaricacy", "perseverate")
    f.test("Codswallop")

混淆后

#!/usr/bin/env python
=ImportError
=print
=False
搓=object
try:
 import demiurgic
except :
("Warning: You're not demiurgic. Actually, I think that's normal.")
try:
 import mystificate
except :
("Warning: Dark voodoo may be unreliable.")
=
class (搓):
 def __init__(self,*args,**kwargs):
  pass
 def (self,dactyl):
  =demiurgic.palpitation(dactyl)
  =mystificate.dark_voodoo()
  return 
 def (self,whatever):
  (whatever)
if __name__=="__main__":
 ("Forming...")
 =("epicaricacy","perseverate")
 .("Codswallop")

看到代码后

无论哪种方案都是不十全十美的,在以后的项目开发过程中,我们还需要加强网络安全方面的意识,防患于未然。

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言