- 论坛徽章:
- 0
|
简单文件压缩加密脚本 python - 001 #coding:utf-8
- 002
- 003 import sys
- 004 import getopt
- 005 import zlib
- 006 import base64
- 007 from cStringIO import StringIO
- 008
- 009 _move = 15
- 010 _line_sep = "\n"
- 011
- 012 class TMain:
- 013 def __init__(self):
- 014 options, args = 0,0
- 015 try:
- 016 options, args = getopt.getopt(sys.argv[1:], 'd')
- 017 except getopt.GetoptError, err:
- 018 print str(err)
- 019 self.usage()
- 020
- 021 mode = "serialize"
- 022 for opt, value in options:
- 023 if opt == "-d":
- 024 mode = 'deSerialize'
- 025 break
- 026
- 027 for filename in args:
- 028 f = getattr(self, mode)
- 029 s = f(self.readfile(filename))
- 030 fout = file(filename + ".out.py", 'wb')
- 031 fout.write(s)
- 032 fout.close()
- 033 print
- 034 print "##################################"
- 035 print s
- 036
- 037
- 038 def moveCode(self, strobj ):
- 039 result = ""
- 040 for i in strobj:
- 041 pass
- 042
- 043 def compress(self,strobj):
- 044 return zlib.compress(strobj, 9)
- 045
- 046 def decompress(self,strobj):
- 047 return zlib.decompress(strobj)
- 048
- 049 def serialize(self, strobj ):
- 050 '''serialize the string into encoded format'''
- 051 strobj = self.compress( strobj )
- 052 strobj = base64.standard_b64encode(strobj)
- 053 max_char_per_line = 40
- 054 c = 0
- 055 result = ""
- 056 for i in strobj:
- 057 c += 1
- 058 if c >= max_char_per_line:
- 059 c = 1
- 060 result += _line_sep
- 061 result += hex( ord( i ) #+ _move
- 062 )[2:]
- 063 return result
- 064
- 065 def deSerialize(self, strobj ):
- 066 strobj = strobj.replace( _line_sep, '' )
- 067 result = ""
- 068 strlen = len(strobj)
- 069 if strlen % 2 != 0 :
- 070 raise Exception("Bad value")
- 071 for i in xrange( 0, len( strobj ), 2 ):
- 072 c = strobj[i:i + 2]
- 073 try:
- 074 c = chr( int( c, 16 ) #- _move
- 075 )
- 076 tmp= hex( ord(c))[2:]
- 077 result += c
- 078 except ValueError, err:
- 079 print c, int( c, 16 ), int( c, 16 ) - _move
- 080 # for i in result:
- 081 # sys.stdout.write(i)
- 082 # print
- 083 result = base64.standard_b64decode(result)
- 084 #return compress(result)
- 085 return self.decompress( result )
- 086
- 087 def readfile(self, filename ):
- 088 return open( filename ).read()
- 089
- 090 def usage(self,):
- 091 usage_str= '''
- 092 {this_program} [-d] filename
- 093
- 094 if the -d option is given, program will try to decode file,
- 095 otherwise, program will encode file and print the result.
- 096 '''.format( this_program = sys.argv[0])
- 097 print usage_str
- 098 sys.exit()
- 099
- 100 def main():
- 101 m = TMain()
- 102
- 103 if __name__ == '__main__':
- 104 main()
复制代码 |
|