import base64 import hashlib from Crypto.Cipher import AES, DES3, PKCS1_v1_5 from Crypto.Hash import SHA1 from Crypto.PublicKey import RSA from Crypto.Signature import pkcs1_15 from Crypto.Util.Padding import pad, unpad from sanic import Sanic def md5(orig: bytes) -> bytes: h = hashlib.md5() h.update(orig) return bytes.fromhex(h.hexdigest()) def base64_decode(b64: str) -> bytes: return base64.b64decode(b64) def base64_encode(orig: bytes) -> str: return base64.b64encode(orig).decode() def get_rsa_privkey(): with open(Sanic.get_app().config["PRIVKEY_PATH"], "r") as f: return f.read() def rsa_decrypt(cipher_text: bytes, private_key: str) -> bytes: cipher = PKCS1_v1_5.new(RSA.importKey(private_key)) return cipher.decrypt(cipher_text, b"rsa") def rsa_encrypt(origin_text: bytes, private_key: str) -> bytes: cipher = PKCS1_v1_5.new(RSA.importKey(private_key)) return cipher.encrypt(origin_text) def rsa_sha1_sign(message: bytes, private_key: str) -> bytes: key = RSA.import_key(private_key) h = SHA1.new(message) return pkcs1_15.new(key).sign(h) def des3_decrypt(cipher_text: bytes, key: bytes) -> bytes: cipher = DES3.new(key, DES3.MODE_ECB) return cipher.decrypt(cipher_text) # return unpad(cipher.decrypt(cipher_text), 16) def des3_encrypt(origin_text: bytes, key: bytes) -> bytes: cipher = DES3.new(key, DES3.MODE_ECB) return cipher.encrypt(pad(origin_text, 16)) def aes_cbc_decrypt(cipher_text: bytes, key: bytes) -> bytes: cipher = AES.new(key, AES.MODE_CBC) return unpad(cipher.decrypt(cipher_text), 16) def aes_cbc_encrypt(origin_text: bytes, key: bytes) -> bytes: cipher = AES.new(key, AES.MODE_CBC) return cipher.encrypt(pad(origin_text, 16)) def xor(a: bytes, b: bytes) -> bytes: return bytes([ i ^ j for (i, j) in zip(bytearray(a), bytearray(b)) ])