crypt_tools.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. from cryptography.hazmat.primitives.asymmetric import rsa, padding
  2. from cryptography.hazmat.primitives import serialization, hashes
  3. from cryptography.hazmat.backends import default_backend
  4. import os
  5. import base64
  6. import getpass
  7. def init_keys(private_key_file="private_key.pem", public_key_file="public_key.pem"):
  8. """
  9. Generate a new RSA private/public key pair and save them to files.
  10. """
  11. # Check if keys already exist
  12. if os.path.exists(private_key_file) and os.path.exists(public_key_file):
  13. print("Keys already exist. Skipping key generation.")
  14. return
  15. # Generate a private key
  16. private_key = rsa.generate_private_key(
  17. public_exponent=65537,
  18. key_size=2048,
  19. backend=default_backend()
  20. )
  21. # Generate the public key
  22. public_key = private_key.public_key()
  23. # Serialize and save the private key
  24. with open(private_key_file, "wb") as f:
  25. f.write(
  26. private_key.private_bytes(
  27. encoding=serialization.Encoding.PEM,
  28. format=serialization.PrivateFormat.PKCS8,
  29. encryption_algorithm=serialization.NoEncryption()
  30. )
  31. )
  32. # Serialize and save the public key
  33. with open(public_key_file, "wb") as f:
  34. f.write(
  35. public_key.public_bytes(
  36. encoding=serialization.Encoding.PEM,
  37. format=serialization.PublicFormat.SubjectPublicKeyInfo
  38. )
  39. )
  40. print(f"Private key saved to {private_key_file}")
  41. print(f"Public key saved to {public_key_file}")
  42. def encrypt_passphrase(passphrase, public_key_file="public_key.pem"):
  43. """
  44. Encrypt a passphrase using the public key.
  45. Returns the encrypted passphrase as a base64-encoded string.
  46. """
  47. # Load the public key
  48. with open(public_key_file, "rb") as f:
  49. public_key = serialization.load_pem_public_key(
  50. f.read(),
  51. backend=default_backend()
  52. )
  53. # Encrypt the passphrase
  54. encrypted = public_key.encrypt(
  55. passphrase.encode(),
  56. padding.OAEP(
  57. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  58. algorithm=hashes.SHA256(),
  59. label=None
  60. )
  61. )
  62. # Return the encrypted passphrase as a base64-encoded string
  63. return base64.b64encode(encrypted).decode()
  64. def decrypt_passphrase(encrypted_passphrase, private_key_file="private_key.pem"):
  65. """
  66. Decrypt an encrypted passphrase using the private key.
  67. Returns the decrypted passphrase as a string.
  68. """
  69. # Load the private key
  70. with open(private_key_file, "rb") as f:
  71. private_key = serialization.load_pem_private_key(
  72. f.read(),
  73. password=None,
  74. backend=default_backend()
  75. )
  76. # Decode the base64-encoded encrypted passphrase
  77. encrypted = base64.b64decode(encrypted_passphrase.encode())
  78. # Decrypt the passphrase
  79. decrypted = private_key.decrypt(
  80. encrypted,
  81. padding.OAEP(
  82. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  83. algorithm=hashes.SHA256(),
  84. label=None
  85. )
  86. )
  87. # Return the decrypted passphrase
  88. return decrypted.decode()
  89. def create_luks_mount_config(config_file="luks_mount.conf", public_key_file="public_key.pem"):
  90. """
  91. Create a new luks_mount.conf file by interactively prompting for device, mount point, and password.
  92. If the configuration file already exists, provide an option to quit or append to the existing file.
  93. """
  94. mode = "w"
  95. if os.path.exists(config_file):
  96. print(f"Configuration file '{config_file}' already exists.")
  97. choice = input("Do you want to (a)ppend to it or (q)uit? ").strip().lower()
  98. if choice == 'q':
  99. print("Exiting without making changes.")
  100. return
  101. elif choice == 'a':
  102. mode = "a"
  103. else:
  104. print("Invalid choice. Exiting without making changes.")
  105. return
  106. with open(config_file, mode) as f:
  107. if mode == "w":
  108. f.write("# LUKS mount configuration file\n")
  109. f.write("# Format: UUID mount_point encrypted_passphrase\n")
  110. while True:
  111. device = input("Enter the device UUID (e.g., UUID): ").strip()
  112. mount_point = input("Enter the mount point (e.g., /media/<username>/luks-<UUID>): ").strip()
  113. passphrase = getpass.getpass("Enter the passphrase: ").strip()
  114. encrypted_passphrase = encrypt_passphrase(passphrase, public_key_file)
  115. f.write(f"{device} {mount_point} {encrypted_passphrase}\n")
  116. another = input("Do you want to add another entry? (y/n): ").strip().lower()
  117. if another != 'y':
  118. break
  119. print(f"Configuration saved to {config_file}")
  120. # Example usage
  121. if __name__ == "__main__":
  122. # Initialize keys (run this once to generate keys)
  123. init_keys()
  124. # Encrypt a passphrase
  125. #passphrases = ["5khbS4JFN25tPVrkzv2b2Q==", "kT3vPK09f+KhNWp7LpU1jg==", "3fhbN/Nt1YFPM5AUbJ4ERg=="]
  126. passphrases= ["4d6d6a45a6ae0cc673ca050767946158", "e104a9a052774d10b3c3dfbed6109435", "aac5ceb8a015c424951422f93dce68c5", "418e2ffba5f0af55b537311f2bd16574"]
  127. # print(decrypt_passphrase('fAqe02nfx1L+YZK/kLFbsd1nVCl5w/LJxxMeSRXLsEm+vq49dRI4eYSzjl3w2YqyPb4JeVXfMDWCTm523k9e/KI+GF8zAPisI1icWM/k+yzMCrW9Ga7rzwW092Uepm7IU4z7LwU4Z9t2wmQkeb6ulso6lcaYzVoCcIHRJ0gCkBZBb0nA1lXQvf2UNFfe9kkzX+DR1MCovY9SAsIndisCh6y0IxEBbfCTASU5VYIcngiKayS6flVtGuLOz/3S6Z+T5GDN7dLC97wf/yVBQJ2lPdgTcawv2qV59OcxDGUeHjwi340+UIramslrxmGpFMyBkmLYqcjKkWsVD6HF2msu6w=='))
  128. for passphrase in passphrases:
  129. encrypted = encrypt_passphrase(passphrase)
  130. print(f"Encrypted passphrase: {encrypted}")
  131. # Decrypt the passphrase
  132. decrypted = decrypt_passphrase(encrypted)
  133. print(f"Decrypted passphrase: {decrypted}")