You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.8 KiB

7 months ago
import base64
import hashlib
from Crypto.Cipher import AES, DES3, PKCS1_v1_5
from Crypto.Hash import SHA1
7 months ago
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
7 months ago
from Crypto.Util.Padding import pad, unpad
from sanic import Sanic
7 months ago
7 months ago
def md5(orig: bytes) -> bytes:
h = hashlib.md5()
h.update(orig)
return bytes.fromhex(h.hexdigest())
7 months ago
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:
7 months ago
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)
7 months ago
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)
7 months ago
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)) ])