<s> import os <EOL> import sys <EOL> import hashlib <EOL> from cryptography . hazmat . primitives import ciphers , serialization <EOL> from cryptography . hazmat . primitives . ciphers import algorithms , modes <EOL> from cryptography . hazmat . primitives . asymmetric import rsa , padding <EOL> from cryptography . hazmat . backends import default_backend <EOL> backend = default_backend ( ) <EOL> PY3 = sys . version_info > ( <NUM_LIT:3> , ) <EOL> class Cipher : <EOL> def __init__ ( self ) : <EOL> self . disable ( ) <EOL> def enable ( self , key ) : <EOL> cipher = ciphers . Cipher ( algorithms . AES ( key ) , modes . CFB8 ( key ) , backend = backend ) <EOL> self . encryptor = cipher . encryptor ( ) <EOL> self . decryptor = cipher . decryptor ( ) <EOL> def disable ( self ) : <EOL> self . encryptor = None <EOL> self . decryptor = None <EOL> def encrypt ( self , data ) : <EOL> if self . encryptor : <EOL> return self . encryptor . update ( data ) <EOL> else : <EOL> return data <EOL> def decrypt ( self , data ) : <EOL> if self . decryptor : <EOL> return self . decryptor . update ( data ) <EOL> else : <EOL> return data <EOL> def make_keypair ( ) : <EOL> return rsa . generate_private_key ( <EOL> public_exponent = <NUM_LIT> , <EOL> key_size = <NUM_LIT> , <EOL> backend = default_backend ( ) ) <EOL> def make_server_id ( ) : <EOL> data = os . urandom ( <NUM_LIT:10> ) <EOL> if PY3 : <EOL> parts = [ "<STR_LIT>" % c for c in data ] <EOL> else : <EOL> parts = [ "<STR_LIT>" % ord ( c ) for c in data ] <EOL> return "<STR_LIT>" . join ( parts ) <EOL> def make_verify_token ( ) : <EOL> return os . urandom ( <NUM_LIT:4> ) <EOL> def make_shared_secret ( ) : <EOL> return os . urandom ( <NUM_LIT:16> ) <EOL> def make_digest ( * data ) : <EOL> sha1 = hashlib . sha1 ( ) <EOL> for d in data : sha1 . update ( d ) <EOL> digest = int ( sha1 . hexdigest ( ) , <NUM_LIT:16> ) <EOL> if digest >> <NUM_LIT> * <NUM_LIT:4> & <NUM_LIT> : <EOL> return "<STR_LIT>" % ( ( - digest ) & ( <NUM_LIT:2> ** ( <NUM_LIT> * <NUM_LIT:4> ) - <NUM_LIT:1> ) ) <EOL> else : <EOL> return "<STR_LIT>" % digest <EOL> def export_public_key ( keypair ) : <EOL> return keypair . public_key ( ) . public_bytes ( <EOL> encoding = serialization . Encoding . DER , <EOL> format = serialization . PublicFormat . SubjectPublicKeyInfo ) <EOL> def import_public_key ( data ) : <EOL> return serialization . load_der_public_key ( <EOL> data = data , <EOL> backend = default_backend ( ) ) <EOL> def encrypt_secret ( public_key , shared_secret ) : <EOL> return public_key . encrypt ( <EOL> plaintext = shared_secret , <EOL> padding = padding . PKCS1v15 ( ) ) <EOL> def decrypt_secret ( keypair , data ) : <EOL> return keypair . decrypt ( <EOL> ciphertext = data , <EOL> padding = padding . PKCS1v15 ( ) ) </s>
