fork download
  1. from cryptography.hazmat.backends import default_backend
  2. from cryptography.hazmat.primitives.asymmetric import rsa
  3. from cryptography.hazmat.primitives import serialization
  4. from cryptography.hazmat.primitives import hashes
  5. from cryptography.hazmat.primitives.asymmetric import padding
  6. import base64
  7.  
  8. # 1. Tạo cặp khóa RSA
  9. private_key = rsa.generate_private_key(
  10. public_exponent=65537,
  11. key_size=2048,
  12. backend=default_backend()
  13. )
  14.  
  15. public_key = private_key.public_key()
  16.  
  17. # 2. Mã hóa tin nhắn
  18. message = b"i love you" # Chuyển tin nhắn thành bytes
  19. ciphertext = public_key.encrypt(
  20. message,
  21. padding.OAEP(
  22. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  23. algorithm=hashes.SHA256(),
  24. label=None
  25. )
  26. )
  27.  
  28. # Chuyển ciphertext thành chuỗi base64 để dễ dàng lưu trữ và truyền tải
  29. ciphertext_base64 = base64.b64encode(ciphertext).decode('utf-8')
  30. print("Ciphertext (base64):", ciphertext_base64)
  31.  
  32. # 3. Giải mã tin nhắn
  33. ciphertext_bytes = base64.b64decode(ciphertext_base64) # Chuyển ciphertext base64 về bytes
  34. plaintext = private_key.decrypt(
  35. ciphertext_bytes,
  36. padding.OAEP(
  37. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  38. algorithm=hashes.SHA256(),
  39. label=None
  40. )
  41. )
  42.  
  43. print("Plaintext:", plaintext.decode('utf-8')) # Chuyển plaintext bytes về string
Success #stdin #stdout 0.18s 21288KB
stdin
Standard input is empty
stdout
('Ciphertext (base64):', u'Oj2O4YkcT58ijsc0MkgjElZMGyv3hjXhcb6O+noNY5a74skvq7FuDPuQMLHzLXLi+I2wVm/yOOKxNVUMakse9oBBT+qkT4XST/eubwo6FgmBbmxvRHkQPRXEVBJcokmbtYY91wsSWxQb8rr9jWnIyoG4NQOkCGaVQ8ICGOiGp9P9NJBt8CrR8dXX9KRHqhrcrSwFCcr12PqzXon1p1ASd3ReRmNuke4vaewRJCTlfdydvYR5nl33dhLCs/Qa4qV9pTF0IFit4bKnuJOZJ6tChSqlH1fRzSEwzrBiASfFYkjDbUOdAMViDAT+GHa9ns9vGy5zTqXOyISQoUtqgdIk9Q==')
('Plaintext:', u'i love you')