<s> from __future__ import absolute_import , division , print_function <EOL> import struct <EOL> from cryptography import utils <EOL> from cryptography . exceptions import ( <EOL> AlreadyFinalized , InvalidKey , UnsupportedAlgorithm , _Reasons <EOL> ) <EOL> from cryptography . hazmat . backends . interfaces import HashBackend <EOL> from cryptography . hazmat . primitives import constant_time , hashes <EOL> from cryptography . hazmat . primitives . kdf import KeyDerivationFunction <EOL> def _int_to_u32be ( n ) : <EOL> return struct . pack ( '<STR_LIT>' , n ) <EOL> @ utils . register_interface ( KeyDerivationFunction ) <EOL> class X963KDF ( object ) : <EOL> def __init__ ( self , algorithm , length , sharedinfo , backend ) : <EOL> max_len = algorithm . digest_size * ( <NUM_LIT:2> ** <NUM_LIT:32> - <NUM_LIT:1> ) <EOL> if length > max_len : <EOL> raise ValueError ( <EOL> "<STR_LIT>" . format ( max_len ) ) <EOL> if not ( sharedinfo is None or isinstance ( sharedinfo , bytes ) ) : <EOL> raise TypeError ( "<STR_LIT>" ) <EOL> self . _algorithm = algorithm <EOL> self . _length = length <EOL> self . _sharedinfo = sharedinfo <EOL> if not isinstance ( backend , HashBackend ) : <EOL> raise UnsupportedAlgorithm ( <EOL> "<STR_LIT>" , <EOL> _Reasons . BACKEND_MISSING_INTERFACE <EOL> ) <EOL> self . _backend = backend <EOL> self . _used = False <EOL> def derive ( self , key_material ) : <EOL> if self . _used : <EOL> raise AlreadyFinalized <EOL> self . _used = True <EOL> if not isinstance ( key_material , bytes ) : <EOL> raise TypeError ( "<STR_LIT>" ) <EOL> output = [ b"<STR_LIT>" ] <EOL> outlen = <NUM_LIT:0> <EOL> counter = <NUM_LIT:1> <EOL> while self . _length > outlen : <EOL> h = hashes . Hash ( self . _algorithm , self . _backend ) <EOL> h . update ( key_material ) <EOL> h . update ( _int_to_u32be ( counter ) ) <EOL> if self . _sharedinfo is not None : <EOL> h . update ( self . _sharedinfo ) <EOL> output . append ( h . finalize ( ) ) <EOL> outlen += len ( output [ - <NUM_LIT:1> ] ) <EOL> counter += <NUM_LIT:1> <EOL> return b"<STR_LIT>" . join ( output ) [ : self . _length ] <EOL> def verify ( self , key_material , expected_key ) : <EOL> if not constant_time . bytes_eq ( self . derive ( key_material ) , expected_key ) : <EOL> raise InvalidKey </s>
