Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. import base64
  2. from cryptography.hazmat.backends import default_backend
  3. from cryptography.hazmat.primitives.asymmetric import rsa
  4. from cryptography.hazmat.primitives import serialization
  5. from cryptography.hazmat.primitives.asymmetric import padding
  6. from cryptography.hazmat.primitives import hashes
  7.  
  8.  
  9. # Create Private Key
  10. private_key = rsa.generate_private_key(
  11. public_exponent=65537,
  12. key_size=2048,
  13. backend=default_backend()
  14. )
  15.  
  16. private_key_str = private_key.private_bytes(
  17. encoding=serialization.Encoding.PEM,
  18. format=serialization.PrivateFormat.PKCS8,
  19. encryption_algorithm=serialization.NoEncryption()
  20. ).decode("utf-8")
  21.  
  22. public_key_str = private_key.public_key().public_bytes(
  23. encoding=serialization.Encoding.PEM,
  24. format=serialization.PublicFormat.SubjectPublicKeyInfo
  25. ).decode("utf-8")
  26.  
  27. print("=========================== PRIVATE KEY ===========================")
  28. print(private_key_str)
  29. print("=========================== PUBLIC KEY ===========================")
  30. print(public_key_str)
  31.  
  32. del(private_key)
  33.  
  34.  
  35. # Load Public Key & Public key
  36. public_key = serialization.load_pem_public_key(
  37. public_key_str.encode("utf-8"),
  38. backend=default_backend()
  39. )
  40.  
  41. private_key = serialization.load_pem_private_key(
  42. private_key_str.encode("utf-8"),
  43. backend=default_backend(),
  44. password=None,
  45. )
  46.  
  47. # Ciper & b64
  48. cipher_bytes = public_key.encrypt(
  49. "All your base are belong to us".encode('utf-8'),
  50. padding.OAEP(
  51. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  52. algorithm=hashes.SHA256(),
  53. label=None,
  54. )
  55. )
  56.  
  57. b64_ciphertext = base64.b64encode(cipher_bytes)
  58.  
  59. del(cipher_bytes)
  60.  
  61. cipher_bytes = base64.b64decode(b64_ciphertext)
  62.  
  63. plaintext = private_key.decrypt(
  64. cipher_bytes,
  65. padding.OAEP(
  66. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  67. algorithm=hashes.SHA256(),
  68. label=None
  69. )
  70. )
  71.  
  72. print("=" * 79)
  73. print(cipher_bytes)
  74. print("-" * 79)
  75. print(plaintext.decode("utf-8"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement