utils.py 871 B

12345678910111213141516171819202122232425262728293031
  1. import os
  2. from Crypto.Cipher import PKCS1_OAEP
  3. from Crypto.PublicKey import RSA
  4. def generate_random_key(bits=256):
  5. """
  6. Generate a random encryption key. Sizes is given in bits and must be in increments of 32.
  7. """
  8. if bits % 32:
  9. raise Exception("Invalid key size ({}). Key sizes must be in increments of 32 bits.".format(bits))
  10. return os.urandom(int(bits / 8))
  11. def encrypt_master_key(master_key, public_key):
  12. """
  13. Encrypt a secret key with the provided public RSA key.
  14. """
  15. key = RSA.importKey(public_key)
  16. cipher = PKCS1_OAEP.new(key)
  17. return cipher.encrypt(master_key)
  18. def decrypt_master_key(master_key_cipher, private_key):
  19. """
  20. Decrypt a secret key with the provided private RSA key.
  21. """
  22. key = RSA.importKey(private_key)
  23. cipher = PKCS1_OAEP.new(key)
  24. return cipher.decrypt(master_key_cipher)