99 lines
2.4 KiB
Python
99 lines
2.4 KiB
Python
import base64
|
|
import hashlib
|
|
import io
|
|
from urllib import parse
|
|
|
|
|
|
def base64_encode(i, output=None):
|
|
if isinstance(i, bytes):
|
|
return base64.b64encode(i)
|
|
if isinstance(i, str):
|
|
return base64.b64encode(bytes(i, encoding='utf-8')).decode()
|
|
else:
|
|
return base64.encode(i, output)
|
|
|
|
|
|
def base64_decode(i, output=None):
|
|
if isinstance(i, bytes):
|
|
return base64.b64decode(i)
|
|
if isinstance(i, str):
|
|
return base64.b64decode(bytes(i, encoding='utf-8')).decode()
|
|
else:
|
|
return base64.decode(i, output)
|
|
|
|
|
|
def hash_sum(method, i):
|
|
hashChoose = getattr(hashlib, method)
|
|
if isinstance(i, bytes):
|
|
return hashChoose(i).hexdigest()
|
|
if isinstance(i, str):
|
|
return hashChoose(bytes(i, encoding='utf-8')).hexdigest()
|
|
else:
|
|
hashObject = hashChoose()
|
|
bufferSize = io.DEFAULT_BUFFER_SIZE
|
|
while 1:
|
|
data = i.read(bufferSize)
|
|
if data:
|
|
hashObject.update(data)
|
|
else:
|
|
break
|
|
return hashObject.hexdigest()
|
|
|
|
|
|
def md5(i):
|
|
import inspect
|
|
return hash_sum(inspect.stack()[0][3], i)
|
|
|
|
|
|
def sha1(i):
|
|
import inspect
|
|
return hash_sum(inspect.stack()[0][3], i)
|
|
|
|
|
|
def sha224(i):
|
|
import inspect
|
|
return hash_sum(inspect.stack()[0][3], i)
|
|
|
|
|
|
def sha256(i):
|
|
import inspect
|
|
return hash_sum(inspect.stack()[0][3], i)
|
|
|
|
|
|
def sha384(i):
|
|
import inspect
|
|
return hash_sum(inspect.stack()[0][3], i)
|
|
|
|
|
|
def sha512(i):
|
|
import inspect
|
|
return hash_sum(inspect.stack()[0][3], i)
|
|
|
|
|
|
def urlencode(string):
|
|
return parse.quote(str(string))
|
|
|
|
|
|
def urldecode(string):
|
|
return parse.unquote(string)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# Example.
|
|
# print(base64_encode(open('./example', 'rb'), open('./example.base64', 'wb')))
|
|
# print(base64_decode(open('./example.base64', 'rb'), open('./example.base64.decode', 'wb')))
|
|
print(base64_encode('root'))
|
|
print(base64_encode(bytes('root', encoding='utf-8')))
|
|
print(base64_decode('cm9vdA=='))
|
|
print(base64_decode(bytes('cm9vdA==', encoding='utf-8')))
|
|
print(sha1('root'))
|
|
print(sha224('root'))
|
|
print(sha256('root'))
|
|
print(sha384('root'))
|
|
print(sha512('root'))
|
|
# print(md5('root'))
|
|
# print(md5(bytes('root', encoding='utf-8')))
|
|
# print(md5(open('./example', 'rb')))
|
|
print(urlencode('百度一下'))
|
|
print(urldecode('%E7%99%BE%E5%BA%A6%E4%B8%80%E4%B8%8B'))
|