Added libs
This commit is contained in:
17
fspn/utils/aes_util.py
Normal file
17
fspn/utils/aes_util.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from Crypto.Cipher import AES
|
||||
|
||||
def encrypt(data:bytes, key:bytes):
|
||||
cipher = AES.new(key, AES.MODE_EAX)
|
||||
nonce = cipher.nonce
|
||||
ciphertext, mac = cipher.encrypt_and_digest(data)
|
||||
return nonce, ciphertext, mac
|
||||
|
||||
def decrypt_and_verify(nonce:bytes, data:bytes, mac:bytes, key:bytes):
|
||||
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
|
||||
plaintext = cipher.decrypt(data)
|
||||
try:
|
||||
cipher.verify(mac)
|
||||
except ValueError:
|
||||
return None
|
||||
return plaintext
|
||||
|
||||
36
fspn/utils/ecdh_util.py
Normal file
36
fspn/utils/ecdh_util.py
Normal file
@@ -0,0 +1,36 @@
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||
from cryptography.hazmat.primitives.serialization import PublicFormat, Encoding, load_pem_public_key
|
||||
|
||||
def generate_keys():
|
||||
private_key = ec.generate_private_key(
|
||||
ec.SECP384R1()
|
||||
)
|
||||
public_key = private_key.public_key()
|
||||
return public_key, private_key
|
||||
|
||||
def generate_shared_key(private_key:ec.EllipticCurvePrivateKey, public_key:ec.EllipticCurvePublicKey):
|
||||
shared_key = private_key.exchange(ec.ECDH(), public_key)
|
||||
return shared_key
|
||||
|
||||
def generate_derived_key(shared_key:bytes):
|
||||
derived_key = HKDF(
|
||||
algorithm=hashes.SHA256(),
|
||||
length=32,
|
||||
salt=None,
|
||||
info=None,
|
||||
).derive(shared_key)
|
||||
return derived_key
|
||||
|
||||
def public_key_to_str(public_key:ec.EllipticCurvePublicKey, remove_header_and_footer=False):
|
||||
public_key_str = public_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo).decode()
|
||||
if(remove_header_and_footer):
|
||||
public_key_str = public_key_str.replace('-----BEGIN PUBLIC KEY-----\n','')
|
||||
public_key_str = public_key_str.replace('\n-----END PUBLIC KEY-----\n','')
|
||||
return public_key_str
|
||||
|
||||
def load_public_key_str(public_key_str:str, removed_header_and_footer=False):
|
||||
if(removed_header_and_footer):
|
||||
public_key_str = f'-----BEGIN PUBLIC KEY-----\n{public_key_str}\n-----END PUBLIC KEY-----\n'
|
||||
return load_pem_public_key(public_key_str.encode())
|
||||
62
fspn/utils/ecdsa_util.py
Normal file
62
fspn/utils/ecdsa_util.py
Normal file
@@ -0,0 +1,62 @@
|
||||
from ecdsa import SigningKey, VerifyingKey, SECP256k1, keys
|
||||
from hashlib import sha256
|
||||
# from ecies import encrypt, decrypt
|
||||
|
||||
def create_keys(password:bytes) -> tuple[VerifyingKey, SigningKey]: # type: ignore
|
||||
privateKey = SigningKey.from_string(password, curve=SECP256k1)
|
||||
publicKey:VerifyingKey = privateKey.get_verifying_key()
|
||||
return (publicKey, privateKey)
|
||||
|
||||
def create_pem(fullpath, privateKey:SigningKey, publicKey:VerifyingKey):
|
||||
with open(fullpath+"privateKey.pem", "wb") as f:
|
||||
f.write(privateKey.to_pem(format="pkcs8"))
|
||||
with open(fullpath+"publicKey.pem", "wb") as f:
|
||||
f.write(publicKey.to_pem())
|
||||
|
||||
def read_pem(fullpath):
|
||||
with open(fullpath+"privateKey.pem") as f:
|
||||
privateKey = SigningKey.from_pem(f.read())
|
||||
with open(fullpath+"publicKey.pem") as f:
|
||||
publicKey = VerifyingKey.from_pem(f.read())
|
||||
return (privateKey, publicKey)
|
||||
|
||||
def sign_message(message:str, privateKey:SigningKey) -> bytes:
|
||||
return privateKey.sign(message.encode('utf-8'), hashfunc=sha256)
|
||||
|
||||
def load_signing_key(signing_key:bytes) -> SigningKey:
|
||||
return SigningKey.from_string(signing_key, curve=SECP256k1, hashfunc=sha256)
|
||||
|
||||
def get_verifying_key(signing_key:SigningKey) -> VerifyingKey:
|
||||
return signing_key.get_verifying_key()
|
||||
|
||||
def load_verifying_key(verifying_key:bytes) -> VerifyingKey:
|
||||
return VerifyingKey.from_string(verifying_key, curve=SECP256k1, hashfunc=sha256)
|
||||
|
||||
def verify_message(message:bytes, signature:bytes, publicKey:VerifyingKey) -> bool:
|
||||
try:
|
||||
return publicKey.verify(signature, message, hashfunc=sha256)
|
||||
except keys.BadSignatureError:
|
||||
return False
|
||||
|
||||
# ecdsa_vk.to_string('compressed') or vk_bytes
|
||||
# def encrypt_message(verifying_key:bytes, message:bytes):
|
||||
# return encrypt(verifying_key, message)
|
||||
|
||||
# ecdsa_sk.to_string() or sk_bytes
|
||||
# def decrypt_message(signing_key:bytes, message:bytes):
|
||||
# return decrypt(signing_key, message)
|
||||
|
||||
# password = b'#LucasGabrielVazDosSantosInacio!'
|
||||
|
||||
# vk,sk = create_keys(password)
|
||||
# import base64
|
||||
|
||||
# print(base64.b64encode(vk.to_string('compressed')).decode())
|
||||
|
||||
# pk ='AuWgGLOi4VUxYQnZzcXqtzl1nA4H4MAL+fzLgjf+TX8C'
|
||||
# message= '{"text":"Hello","public_key":"AuWgGLOi4VUxYQnZzcXqtzl1nA4H4MAL+fzLgjf+TX8C","pof":"69201","signature":null,"files":[],"networks":["000"],"datetime":"2024-10-06T07:08:30.419000Z","parents":[]}'
|
||||
# sig = 'dRAyr67oZXblKEqS9EpghhS7mbl1DOoqCF8n8krQ2KsTcV9VRK6Hc4O2A27WkdjW2ZEaalp2PbPd1ZamAMJJ/A=='
|
||||
|
||||
# pk = load_verifying_key(base64.b64decode(pk))
|
||||
# sig = base64.b64decode(sig)
|
||||
# print(verify_message(message.encode(), sig, pk))
|
||||
44
fspn/utils/observable.py
Normal file
44
fspn/utils/observable.py
Normal file
@@ -0,0 +1,44 @@
|
||||
from .wrapper_util import threaded
|
||||
import logging, traceback
|
||||
|
||||
class Event(object):
|
||||
def __init__(self):
|
||||
self.source = self
|
||||
|
||||
class Observable(object):
|
||||
"""
|
||||
A simple publish-subscribe system.
|
||||
"""
|
||||
|
||||
def __init__(self, events = []):
|
||||
self.events: dict[str, list] = {}
|
||||
for event in events:
|
||||
self.register_event(event)
|
||||
|
||||
def register_event(self, event):
|
||||
if(event not in self.events):
|
||||
self.events[event] = []
|
||||
|
||||
def subscribe_event(self, event, callback):
|
||||
if(event not in self.events):
|
||||
self.register_event(event)
|
||||
self.events[event].append(callback)
|
||||
|
||||
@threaded
|
||||
def fire_event(self, event, **kwargs):
|
||||
e = Event()
|
||||
e.source = self
|
||||
for k, v in kwargs.items():
|
||||
setattr(e, k, v)
|
||||
if(event in self.events):
|
||||
for fn in self.events[event]:
|
||||
self.call_observer(fn, e)
|
||||
else:
|
||||
logging.warning(f"Event {event} without callback")
|
||||
|
||||
@threaded
|
||||
def call_observer(self, function, event):
|
||||
try:
|
||||
function(event)
|
||||
except Exception as ex:
|
||||
logging.exception(f'Error in event {event} to function {function.__name__}')
|
||||
67
fspn/utils/sha256_util.py
Normal file
67
fspn/utils/sha256_util.py
Normal file
@@ -0,0 +1,67 @@
|
||||
import hashlib
|
||||
|
||||
def hash_file(filepath):
|
||||
BUF_SIZE = 65 * 1024
|
||||
|
||||
sha = hashlib.sha256()
|
||||
|
||||
with open(filepath, 'rb') as f:
|
||||
while True:
|
||||
data = f.read(BUF_SIZE)
|
||||
if not data:
|
||||
break
|
||||
sha.update(data)
|
||||
return sha.hexdigest()
|
||||
|
||||
def hash_bytes(data):
|
||||
sha = hashlib.sha256()
|
||||
sha.update(data)
|
||||
return sha.hexdigest()
|
||||
|
||||
def hash_string(data:str):
|
||||
sha = hashlib.sha256()
|
||||
sha.update(str(data).encode('utf-8'))
|
||||
return sha.hexdigest()
|
||||
|
||||
# ---------------
|
||||
import datetime
|
||||
import string
|
||||
import itertools
|
||||
import random
|
||||
|
||||
def get_nonce(characters, lenght):
|
||||
yield from itertools.product(*([characters] * lenght))
|
||||
|
||||
def count_leading_zeros(text):
|
||||
n = 0
|
||||
for i in range(len(text)):
|
||||
if text[:i] == "0" * i:
|
||||
n = i
|
||||
else:
|
||||
break
|
||||
return n
|
||||
|
||||
def mine_user(data, force=4, nonce_lenght=4):
|
||||
characters = '[@_!#$%^&*()<>?/\|}{~:]'+string.ascii_letters+string.digits
|
||||
while True:
|
||||
for x in get_nonce(characters, nonce_lenght):
|
||||
nonce = ''.join(x)+random.choice(characters)
|
||||
hash = hash_string(data+ nonce)
|
||||
leading_zeros = count_leading_zeros(hash)
|
||||
if leading_zeros >= force:
|
||||
return nonce
|
||||
|
||||
|
||||
def test():
|
||||
print(datetime.datetime.now(), "EXECUTING HASH TEST - MINE USER")
|
||||
public_key_str = "A4DZSk+TlR+4w39MbiIAQbti+N0H1QlJEhRH2DI6Iubj"
|
||||
nonce, hash = mine_user(public_key_str)
|
||||
|
||||
print(nonce, hash)
|
||||
|
||||
# test()
|
||||
|
||||
# A4DZSk+TlR+4w39MbiIAQbti+N0H1QlJEhRH2DI6Iubj
|
||||
# 8
|
||||
# eYnU*@
|
||||
# [/Q#7r
|
||||
19
fspn/utils/wrapper_util.py
Normal file
19
fspn/utils/wrapper_util.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import functools
|
||||
from threading import Thread
|
||||
|
||||
def threaded(fn):
|
||||
"""Decorator to automatically launch a function in a thread"""
|
||||
@functools.wraps(fn)
|
||||
def wrapper(*args, **kwargs):
|
||||
thread = Thread(target=fn, args=args, kwargs=kwargs)
|
||||
thread.start()
|
||||
return thread
|
||||
return wrapper
|
||||
|
||||
def singleton(cls):
|
||||
instances = {}
|
||||
def getinstance(*args, **kwargs):
|
||||
if cls not in instances:
|
||||
instances[cls] = cls(*args, **kwargs)
|
||||
return instances[cls]
|
||||
return getinstance
|
||||
Reference in New Issue
Block a user