<s> import os <EOL> from hashlib import sha1 <EOL> from cryptography . hazmat . backends import default_backend <EOL> from cryptography . hazmat . primitives . asymmetric . padding import PKCS1v15 <EOL> from cryptography . hazmat . primitives . serialization import load_der_public_key <EOL> from cryptography . hazmat . primitives . ciphers import Cipher , algorithms , modes <EOL> def generate_shared_secret ( ) : <EOL> return os . urandom ( <NUM_LIT:16> ) <EOL> def create_AES_cipher ( shared_secret ) : <EOL> cipher = Cipher ( algorithms . AES ( shared_secret ) , modes . CFB8 ( shared_secret ) , <EOL> backend = default_backend ( ) ) <EOL> return cipher <EOL> def encrypt_token_and_secret ( pubkey , verification_token , shared_secret ) : <EOL> """<STR_LIT>""" <EOL> pubkey = load_der_public_key ( pubkey , default_backend ( ) ) <EOL> encrypted_token = pubkey . encrypt ( verification_token , PKCS1v15 ( ) ) <EOL> encrypted_secret = pubkey . encrypt ( shared_secret , PKCS1v15 ( ) ) <EOL> return encrypted_token , encrypted_secret <EOL> def generate_verification_hash ( server_id , shared_secret , public_key ) : <EOL> verification_hash = sha1 ( ) <EOL> verification_hash . update ( server_id . encode ( '<STR_LIT:utf-8>' ) ) <EOL> verification_hash . update ( shared_secret ) <EOL> verification_hash . update ( public_key ) <EOL> return minecraft_sha1_hash_digest ( verification_hash ) <EOL> def minecraft_sha1_hash_digest ( sha1_hash ) : <EOL> number_representation = _number_from_bytes ( sha1_hash . digest ( ) , signed = True ) <EOL> return format ( number_representation , '<STR_LIT:x>' ) <EOL> def _number_from_bytes ( b , signed = False ) : <EOL> try : <EOL> return int . from_bytes ( b , byteorder = '<STR_LIT>' , signed = signed ) <EOL> except AttributeError : <EOL> if len ( b ) == <NUM_LIT:0> : <EOL> b = b'<STR_LIT:\x00>' <EOL> num = int ( str ( b ) . encode ( '<STR_LIT>' ) , <NUM_LIT:16> ) <EOL> if signed and ( ord ( b [ <NUM_LIT:0> ] ) & <NUM_LIT> ) : <EOL> num -= <NUM_LIT:2> ** ( len ( b ) * <NUM_LIT:8> ) <EOL> return num <EOL> class EncryptedFileObjectWrapper ( object ) : <EOL> def __init__ ( self , file_object , decryptor ) : <EOL> self . actual_file_object = file_object <EOL> self . decryptor = decryptor <EOL> def read ( self , length ) : <EOL> return self . decryptor . update ( self . actual_file_object . read ( length ) ) <EOL> class EncryptedSocketWrapper ( object ) : <EOL> def __init__ ( self , socket , encryptor , decryptor ) : <EOL> self . actual_socket = socket <EOL> self . encryptor = encryptor <EOL> self . decryptor = decryptor <EOL> def recv ( self , length ) : <EOL> return self . decryptor . update ( self . actual_socket . recv ( length ) ) <EOL> def send ( self , data ) : <EOL> self . actual_socket . send ( self . encryptor . update ( data ) ) <EOL> def fileno ( self ) : <EOL> return self . actual_socket . fileno ( ) </s>
