fork download
  1. import base64
  2. import os
  3. from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  4.  
  5. base64_key = "nCrksJzTgZCK3zPYH2z0oHDM6Py2mThHcjqxGPpR6nA="
  6.  
  7. def encrypt(plaintext):
  8. key = base64.b64decode(base64_key)
  9. aesgcm = AESGCM(key)
  10.  
  11. nonce = os.urandom(12)
  12. plaintext_bytes = plaintext.encode('utf-8')
  13.  
  14. ciphertext = aesgcm.encrypt(nonce, plaintext_bytes, None)
  15. encrypted = nonce + ciphertext
  16.  
  17. return base64.b64encode(encrypted)
  18.  
  19. def decrypt(encrypted_base64):
  20. try:
  21. if not encrypted_base64:
  22. print("Encrypted input is null or empty")
  23. return ""
  24.  
  25. key = base64.b64decode(base64_key)
  26. encrypted_bytes = base64.b64decode(encrypted_base64)
  27.  
  28. if len(encrypted_bytes) < 13:
  29. print("Encrypted input too short")
  30. return ""
  31.  
  32. nonce = encrypted_bytes[:12]
  33. ciphertext = encrypted_bytes[12:]
  34.  
  35. aesgcm = AESGCM(key)
  36. plaintext_bytes = aesgcm.decrypt(nonce, ciphertext, None)
  37.  
  38. return plaintext_bytes.decode('utf-8')
  39.  
  40. except Exception as e:
  41. print("Decryption failed:", e)
  42. return ""
  43.  
  44. # Test
  45. if __name__ == "__main__":
  46. original_text = "Hello from Python AES-GCM!"
  47. print("Original:", original_text)
  48.  
  49. encrypted = encrypt(original_text)
  50. print("Encrypted:", encrypted)
  51.  
  52. decrypted = decrypt(encrypted)
  53. print("Decrypted:", decrypted)
  54.  
Success #stdin #stdout 0.12s 21288KB
stdin
Standard input is empty
stdout
('Original:', 'Hello from Python AES-GCM!')
('Encrypted:', 'ZwwKMe9dvDy8tcz/u5Ho8St2sZ2E3nwy0UZn1BPzsPZviayg3DtW7JJDTbxsSW66Pw/T+s7G')
('Decrypted:', u'Hello from Python AES-GCM!')