utils.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from cryptography.hazmat.primitives import serialization, hashes
  2. from cryptography.hazmat.primitives.asymmetric import rsa, padding
  3. from cryptography.hazmat.backends import default_backend
  4. from cryptography.exceptions import InvalidSignature
  5. def generate_keys(private_key_password):
  6. ''' Generating the keys pair. Cryptographic algorithm used is for demostranation porpuses only. '''
  7. private_key = rsa.generate_private_key(
  8. public_exponent=65537,
  9. key_size=2048
  10. )
  11. encrypted_pem_private_key = private_key.private_bytes(
  12. encoding=serialization.Encoding.PEM,
  13. format=serialization.PrivateFormat.PKCS8,
  14. encryption_algorithm=serialization.BestAvailableEncryption(
  15. private_key_password.encode()))
  16. pem_public_key = private_key.public_key().public_bytes(
  17. encoding=serialization.Encoding.PEM,
  18. format=serialization.PublicFormat.SubjectPublicKeyInfo
  19. )
  20. return encrypted_pem_private_key, pem_public_key
  21. def sign_message(password, private_key, message):
  22. ''' Signs a message using private_key. '''
  23. privkey = serialization.load_pem_private_key(
  24. private_key, password=password.encode(), backend=default_backend())
  25. signed_message = privkey.sign(
  26. message.encode(),
  27. padding.PSS(
  28. mgf=padding.MGF1(hashes.SHA256()),
  29. salt_length=padding.PSS.MAX_LENGTH),
  30. hashes.SHA256()
  31. )
  32. return signed_message
  33. def verify_signature(public_key, message, signed_message):
  34. ''' Verifies a message against a public key. '''
  35. pubkey = serialization.load_pem_public_key(
  36. public_key, backend=default_backend())
  37. try:
  38. pubkey.verify(
  39. signed_message,
  40. message.encode(),
  41. padding.PSS(
  42. mgf=padding.MGF1(hashes.SHA256()),
  43. salt_length=padding.PSS.MAX_LENGTH),
  44. hashes.SHA256())
  45. return True
  46. except InvalidSignature:
  47. return False