class ARC4Cipher: """ARC4 cipher object""" def __init__(self, key, *args, **kwargs): """Initialize an ARC4 cipher object See also `new()` at the module level.""" if len(args) > 0: ndrop = args[0] args = args[1:] else: ndrop = kwargs.pop("drop", 0) expect_byte_string(key) self._state = VoidPointer() result = _raw_arc4_lib.ARC4_stream_init(key, c_size_t(len(key)), self._state.address_of()) if result != 0: raise ValueError("Error %d while creating the ARC4 cipher" % result) self._state = SmartPointer(self._state.get(), _raw_arc4_lib.ARC4_stream_destroy) if ndrop > 0: # This is OK even if the cipher is used for decryption, since encrypt # and decrypt are actually the same thing with ARC4. self.encrypt(b("\x00") * ndrop) self.block_size = 1 self.key_size = len(key) def encrypt(self, plaintext): """Encrypt a piece of data. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any size. :Return: the encrypted data (byte string, as long as the plaintext). """ expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = _raw_arc4_lib.ARC4_stream_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with RC4" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt a piece of data. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any size. :Return: the decrypted data (byte string, as long as the ciphertext). """ try: return self.encrypt(ciphertext) except ValueError, e: raise ValueError(str(e).replace("enc", "dec"))
class Salsa20Cipher: """Salsa20 cipher object""" def __init__(self, key, nonce): """Initialize a Salsa20 cipher object See also `new()` at the module level.""" expect_byte_string(key) expect_byte_string(nonce) self._state = VoidPointer() result = _raw_salsa20_lib.Salsa20_stream_init(key, c_size_t(len(key)), nonce, c_size_t(len(nonce)), self._state.address_of()) if result: raise ValueError("Error %d instantiating a Salsa20 cipher") self._state = SmartPointer(self._state.get(), _raw_salsa20_lib.Salsa20_stream_destroy) self.block_size = 1 self.key_size = len(key) def encrypt(self, plaintext): """Encrypt a piece of data. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any size. :Return: the encrypted data (byte string, as long as the plaintext). """ expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = _raw_salsa20_lib.Salsa20_stream_encrypt( self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with Salsa20" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt a piece of data. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any size. :Return: the decrypted data (byte string, as long as the ciphertext). """ try: return self.encrypt(ciphertext) except ValueError as e: raise ValueError(str(e).replace("enc", "dec"))
class _GHASH(_SmoothMAC): """GHASH function defined in NIST SP 800-38D, Algorithm 2. If X_1, X_2, .. X_m are the blocks of input data, the function computes: X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H in the Galois field GF(2^256) using the reducing polynomial (x^128 + x^7 + x^2 + x + 1). """ def __init__(self, hash_subkey, block_size): _SmoothMAC.__init__(self, block_size, None, 0) self._key = hash_subkey self._exp_key = VoidPointer() expect_byte_string(self._key) result = _raw_galois_lib.ghash_expand(self._key, self._exp_key.address_of()) if result: raise ValueError("Error %d while expanding the GMAC key" % result) self._exp_key = SmartPointer(self._exp_key.get(), _raw_galois_lib.ghash_destroy) self._last_y = create_string_buffer(16) for i in range(16): self._last_y[i] = bchr(0) self._mac = _raw_galois_lib.ghash def copy(self): clone = _GHASH(self._key, self._bs) _SmoothMAC._deep_copy(self, clone) clone._last_y = self._last_y return clone def _update(self, block_data): expect_byte_string(block_data) result = _raw_galois_lib.ghash(self._last_y, block_data, c_size_t(len(block_data)), self._last_y, self._exp_key.get()) if result: raise ValueError("Error %d while updating GMAC" % result) def _digest(self, left_data): return get_raw_buffer(self._last_y)
class _GHASH(_SmoothMAC): """GHASH function defined in NIST SP 800-38D, Algorithm 2. If X_1, X_2, .. X_m are the blocks of input data, the function computes: X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H in the Galois field GF(2^256) using the reducing polynomial (x^128 + x^7 + x^2 + x + 1). """ def __init__(self, hash_subkey, block_size): _SmoothMAC.__init__(self, block_size, None, 0) self._key = hash_subkey self._exp_key = VoidPointer() expect_byte_string(self._key) result = _raw_galois_lib.ghash_expand(self._key, self._exp_key.address_of()) if result: raise ValueError("Error %d while expanding the GMAC key" % result) self._exp_key = SmartPointer(self._exp_key.get(), _raw_galois_lib.ghash_destroy) self._last_y = create_string_buffer(16) for i in xrange(16): self._last_y[i] = bchr(0) self._mac = _raw_galois_lib.ghash def copy(self): clone = _GHASH(self._key, self._bs) _SmoothMAC._deep_copy(self, clone) clone._last_y = self._last_y return clone def _update(self, block_data): expect_byte_string(block_data) result = _raw_galois_lib.ghash(self._last_y, block_data, c_size_t(len(block_data)), self._last_y, self._exp_key.get()) if result: raise ValueError("Error %d while updating GMAC" % result) def _digest(self, left_data): return get_raw_buffer(self._last_y)
class _GHASH(object): """GHASH function defined in NIST SP 800-38D, Algorithm 2. If X_1, X_2, .. X_m are the blocks of input data, the function computes: X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H in the Galois field GF(2^256) using the reducing polynomial (x^128 + x^7 + x^2 + x + 1). """ def __init__(self, subkey): assert len(subkey) == 16 expect_byte_string(subkey) self._exp_key = VoidPointer() result = _raw_galois_lib.ghash_expand(subkey, self._exp_key.address_of()) if result: raise ValueError("Error %d while expanding the GMAC key" % result) self._exp_key = SmartPointer(self._exp_key.get(), _raw_galois_lib.ghash_destroy) self._last_y = create_string_buffer(16) for i in range(16): self._last_y[i] = bchr(0) def update(self, block_data): assert len(block_data) % 16 == 0 expect_byte_string(block_data) result = _raw_galois_lib.ghash(self._last_y, block_data, c_size_t(len(block_data)), self._last_y, self._exp_key.get()) if result: raise ValueError("Error %d while updating GMAC" % result) return self def digest(self): return get_raw_buffer(self._last_y)
class _GHASH(object): """GHASH function defined in NIST SP 800-38D, Algorithm 2. If X_1, X_2, .. X_m are the blocks of input data, the function computes: X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H in the Galois field GF(2^256) using the reducing polynomial (x^128 + x^7 + x^2 + x + 1). """ def __init__(self, subkey): assert len(subkey) == 16 expect_byte_string(subkey) self._exp_key = VoidPointer() result = _raw_galois_lib.ghash_expand(subkey, self._exp_key.address_of()) if result: raise ValueError("Error %d while expanding the GMAC key" % result) self._exp_key = SmartPointer(self._exp_key.get(), _raw_galois_lib.ghash_destroy) # create_string_buffer always returns a string of zeroes self._last_y = create_string_buffer(16) def update(self, block_data): assert len(block_data) % 16 == 0 expect_byte_string(block_data) result = _raw_galois_lib.ghash(self._last_y, block_data, c_size_t(len(block_data)), self._last_y, self._exp_key.get()) if result: raise ValueError("Error %d while updating GMAC" % result) return self def digest(self): return get_raw_buffer(self._last_y)
class _GHASH(object): """GHASH function defined in NIST SP 800-38D, Algorithm 2. If X_1, X_2, .. X_m are the blocks of input data, the function computes: X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H in the Galois field GF(2^256) using the reducing polynomial (x^128 + x^7 + x^2 + x + 1). """ def __init__(self, subkey, ghash_c): assert len(subkey) == 16 self.ghash_c = ghash_c self._exp_key = VoidPointer() result = ghash_c.ghash_expand(c_uint8_ptr(subkey), self._exp_key.address_of()) if result: raise ValueError("Error %d while expanding the GHASH key" % result) self._exp_key = SmartPointer(self._exp_key.get(), ghash_c.ghash_destroy) # create_string_buffer always returns a string of zeroes self._last_y = create_string_buffer(16) def update(self, block_data): assert len(block_data) % 16 == 0 result = self.ghash_c.ghash(self._last_y, c_uint8_ptr(block_data), c_size_t(len(block_data)), self._last_y, self._exp_key.get()) if result: raise ValueError("Error %d while updating GHASH" % result) return self def digest(self): return get_raw_buffer(self._last_y)
class OfbMode(object): """*Output FeedBack (OFB)*. This mode is very similar to CBC, but it transforms the underlying block cipher into a stream cipher. The keystream is the iterated block encryption of the previous ciphertext block. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.4. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf """ def __init__(self, block_cipher, iv): """Create a new block cipher, configured in OFB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : byte string The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be a nonce, to to be reused for any other message**. It shall be a nonce or a random value. Reusing the *IV* for encryptions performed with the same key compromises confidentiality. """ expect_byte_string(iv) self._state = VoidPointer() result = raw_ofb_lib.OFB_start_operation(block_cipher.get(), iv, c_size_t(len(iv)), self._state.address_of()) if result: raise ValueError("Error %d while instatiating the OFB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_ofb_lib.OFB_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() #: The block size of the underlying cipher, in bytes. self.block_size = len(iv) #: The Initialization Vector originally used to create the object. #: The value does not change. self.IV = iv def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = raw_ofb_lib.OFB_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting in OFB mode" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any length. :Return: the decrypted data (byte string). """ expect_byte_string(ciphertext) plaintext = create_string_buffer(len(ciphertext)) result = raw_ofb_lib.OFB_decrypt(self._state.get(), ciphertext, plaintext, c_size_t(len(ciphertext))) if result: raise ValueError("Error %d while decrypting in OFB mode" % result) return get_raw_buffer(plaintext)
class SHA512Hash(object): """A SHA-512 hash object (possibly in its truncated version SHA-512/224 or SHA-512/256. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string :ivar block_size: the size in bytes of the internal message block, input to the compression function :vartype block_size: integer :ivar digest_size: the size in bytes of the resulting hash :vartype digest_size: integer """ # The internal block size of the hash algorithm in bytes. block_size = 128 def __init__(self, data, truncate): self._truncate = truncate if truncate is None: self.oid = "2.16.840.1.101.3.4.2.3" self.digest_size = 64 elif truncate == "224": self.oid = "2.16.840.1.101.3.4.2.5" self.digest_size = 28 elif truncate == "256": self.oid = "2.16.840.1.101.3.4.2.6" self.digest_size = 32 else: raise ValueError( "Incorrect truncation length. It must be '224' or '256'.") state = VoidPointer() result = _raw_sha512_lib.SHA512_init(state.address_of(), c_size_t(self.digest_size)) if result: raise ValueError("Error %d while instantiating SHA-512" % result) self._state = SmartPointer(state.get(), _raw_sha512_lib.SHA512_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string/byte array/memoryview): The next chunk of the message being hashed. """ result = _raw_sha512_lib.SHA512_update(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while hashing data with SHA512" % result) def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Binary form. :rtype: byte string """ bfr = create_string_buffer(self.digest_size) result = _raw_sha512_lib.SHA512_digest(self._state.get(), bfr, c_size_t(self.digest_size)) if result: raise ValueError("Error %d while making SHA512 digest" % result) return get_raw_buffer(bfr) def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Hexadecimal encoded. :rtype: string """ return "".join(["%02x" % bord(x) for x in self.digest()]) def copy(self): """Return a copy ("clone") of the hash object. The copy will have the same internal state as the original hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. :return: A hash object of the same type """ clone = SHA512Hash(None, self._truncate) result = _raw_sha512_lib.SHA512_copy(self._state.get(), clone._state.get()) if result: raise ValueError("Error %d while copying SHA512" % result) return clone def new(self, data=None): """Create a fresh SHA-512 hash object.""" return SHA512Hash(data, self._truncate)
class ChaCha20Cipher: """ChaCha20 cipher object""" block_size = 1 def __init__(self, key, nonce): """Initialize a ChaCha20 cipher object See also `new()` at the module level.""" expect_byte_string(key) expect_byte_string(nonce) self.nonce = nonce self._next = ( self.encrypt, self.decrypt ) self._state = VoidPointer() result = _raw_chacha20_lib.chacha20_init( self._state.address_of(), key, c_size_t(len(key)), nonce, c_size_t(len(nonce))) if result: raise ValueError("Error %d instantiating a ChaCha20 cipher") self._state = SmartPointer(self._state.get(), _raw_chacha20_lib.chacha20_destroy) def encrypt(self, plaintext): """Encrypt a piece of data. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any size. :Return: the encrypted data (byte string, as long as the plaintext). """ if self.encrypt not in self._next: raise TypeError("Cipher object can only be used for decryption") self._next = ( self.encrypt, ) return self._encrypt(plaintext) def _encrypt(self, plaintext): """Encrypt without FSM checks""" expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = _raw_chacha20_lib.chacha20_encrypt( self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with ChaCha20" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt a piece of data. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any size. :Return: the decrypted data (byte string, as long as the ciphertext). """ if self.decrypt not in self._next: raise TypeError("Cipher object can only be used for encryption") self._next = ( self.decrypt, ) try: return self._encrypt(ciphertext) except ValueError as e: raise ValueError(str(e).replace("enc", "dec")) def seek(self, position): """Seek at a certain position in the key stream. :Parameters: position : integer The absolute position within the key stream, in bytes. """ offset = position & 0x3f position >>= 6 block_low = position & 0xFFFFFFFF block_high = position >> 32 result = _raw_chacha20_lib.chacha20_seek( self._state.get(), c_ulong(block_high), c_ulong(block_low), offset ) if result: raise ValueError("Error %d while seeking with ChaCha20" % result)
class SHA256Hash(object): """A SHA-256 hash object. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string :ivar block_size: the size in bytes of the internal message block, input to the compression function :vartype block_size: integer :ivar digest_size: the size in bytes of the resulting hash :vartype digest_size: integer """ # The size of the resulting hash in bytes. digest_size = 32 # The internal block size of the hash algorithm in bytes. block_size = 64 # ASN.1 Object ID oid = "2.16.840.1.101.3.4.2.1" def __init__(self, data=None): state = VoidPointer() result = _raw_sha256_lib.SHA256_init(state.address_of()) if result: raise ValueError("Error %d while instantiating SHA256" % result) self._state = SmartPointer(state.get(), _raw_sha256_lib.SHA256_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string/byte array/memoryview): The next chunk of the message being hashed. """ result = _raw_sha256_lib.SHA256_update(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while hashing data with SHA256" % result) def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Binary form. :rtype: byte string """ bfr = create_string_buffer(self.digest_size) result = _raw_sha256_lib.SHA256_digest(self._state.get(), bfr, c_size_t(self.digest_size)) if result: raise ValueError("Error %d while making SHA256 digest" % result) return get_raw_buffer(bfr) def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Hexadecimal encoded. :rtype: string """ return "".join(["%02x" % bord(x) for x in self.digest()]) def copy(self): """Return a copy ("clone") of the hash object. The copy will have the same internal state as the original hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. :return: A hash object of the same type """ clone = SHA256Hash() result = _raw_sha256_lib.SHA256_copy(self._state.get(), clone._state.get()) if result: raise ValueError("Error %d while copying SHA256" % result) return clone def new(self, data=None): """Create a fresh SHA-256 hash object.""" return SHA256Hash(data)
class SHA3_224_Hash(object): """A SHA3-224 hash object. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string :ivar digest_size: the size in bytes of the resulting hash :vartype digest_size: integer """ # The size of the resulting hash in bytes. digest_size = 28 # ASN.1 Object ID oid = "2.16.840.1.101.3.4.2.7" # Input block size for HMAC block_size = 144 def __init__(self, data, update_after_digest): self._update_after_digest = update_after_digest self._digest_done = False state = VoidPointer() result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(self.digest_size * 2), 0x06) if result: raise ValueError("Error %d while instantiating SHA-3/224" % result) self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string/byte array/memoryview): The next chunk of the message being hashed. """ if self._digest_done and not self._update_after_digest: raise TypeError( "You can only call 'digest' or 'hexdigest' on this object") result = _raw_keccak_lib.keccak_absorb(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while updating SHA-3/224" % result) return self def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Binary form. :rtype: byte string """ self._digest_done = True bfr = create_string_buffer(self.digest_size) result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr, c_size_t(self.digest_size)) if result: raise ValueError("Error %d while instantiating SHA-3/224" % result) self._digest_value = get_raw_buffer(bfr) return self._digest_value def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Hexadecimal encoded. :rtype: string """ return "".join(["%02x" % bord(x) for x in self.digest()]) def copy(self): """Return a copy ("clone") of the hash object. The copy will have the same internal state as the original hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. :return: A hash object of the same type """ clone = self.new() result = _raw_keccak_lib.keccak_copy(self._state.get(), clone._state.get()) if result: raise ValueError("Error %d while copying SHA3-224" % result) return clone def new(self, data=None): """Create a fresh SHA3-224 hash object.""" return type(self)(data, self._update_after_digest)
class Poly1305_MAC(object): digest_size = 16 def __init__(self, r, s, data): if len(r) != 16: raise ValueError("Paramater r is not 16 bytes long") if len(s) != 16: raise ValueError("Parameter s is not 16 bytes long") self._mac_tag = None state = VoidPointer() result = _raw_poly1305.poly1305_init(state.address_of(), c_uint8_ptr(r), c_size_t(len(r)), c_uint8_ptr(s), c_size_t(len(s))) if result: raise ValueError("Error %d while instantiating Poly1305" % result) self._state = SmartPointer(state.get(), _raw_poly1305.poly1305_destroy) if data: self.update(data) def update(self, data): if self._mac_tag: raise TypeError( "You can only call 'digest' or 'hexdigest' on this object") result = _raw_poly1305.poly1305_update(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while hashing Poly1305 data" % result) return self def copy(self): raise NotImplementedError() def digest(self): if self._mac_tag: return self._mac_tag bfr = create_string_buffer(16) result = _raw_poly1305.poly1305_digest(self._state.get(), bfr, c_size_t(len(bfr))) if result: raise ValueError("Error %d while creating Poly1305 digest" % result) self._mac_tag = get_raw_buffer(bfr) return self._mac_tag def hexdigest(self): return "".join(["%02x" % bord(x) for x in tuple(self.digest())]) def verify(self, mac_tag): secret = get_random_bytes(16) mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag) mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest()) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed") def hexverify(self, hex_mac_tag): self.verify(unhexlify(tobytes(hex_mac_tag)))
class Poly1305_MAC(object): """An Poly1305 MAC object. Do not instantiate directly. Use the :func:`new` function. :ivar digest_size: the size in bytes of the resulting MAC tag :vartype digest_size: integer """ digest_size = 16 def __init__(self, r, s, data): if len(r) != 16: raise ValueError("Parameter r is not 16 bytes long") if len(s) != 16: raise ValueError("Parameter s is not 16 bytes long") self._mac_tag = None state = VoidPointer() result = _raw_poly1305.poly1305_init(state.address_of(), c_uint8_ptr(r), c_size_t(len(r)), c_uint8_ptr(s), c_size_t(len(s)) ) if result: raise ValueError("Error %d while instantiating Poly1305" % result) self._state = SmartPointer(state.get(), _raw_poly1305.poly1305_destroy) if data: self.update(data) def update(self, data): """Authenticate the next chunk of message. Args: data (byte string/byte array/memoryview): The next chunk of data """ if self._mac_tag: raise TypeError("You can only call 'digest' or 'hexdigest' on this object") result = _raw_poly1305.poly1305_update(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while hashing Poly1305 data" % result) return self def copy(self): raise NotImplementedError() def digest(self): """Return the **binary** (non-printable) MAC tag of the message authenticated so far. :return: The MAC tag digest, computed over the data processed so far. Binary form. :rtype: byte string """ if self._mac_tag: return self._mac_tag bfr = create_string_buffer(16) result = _raw_poly1305.poly1305_digest(self._state.get(), bfr, c_size_t(len(bfr))) if result: raise ValueError("Error %d while creating Poly1305 digest" % result) self._mac_tag = get_raw_buffer(bfr) return self._mac_tag def hexdigest(self): """Return the **printable** MAC tag of the message authenticated so far. :return: The MAC tag, computed over the data processed so far. Hexadecimal encoded. :rtype: string """ return "".join(["%02x" % bord(x) for x in tuple(self.digest())]) def verify(self, mac_tag): """Verify that a given **binary** MAC (computed by another party) is valid. Args: mac_tag (byte string/byte string/memoryview): the expected MAC of the message. Raises: ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ secret = get_random_bytes(16) mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag) mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest()) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed") def hexverify(self, hex_mac_tag): """Verify that a given **printable** MAC (computed by another party) is valid. Args: hex_mac_tag (string): the expected MAC of the message, as a hexadecimal string. Raises: ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ self.verify(unhexlify(tobytes(hex_mac_tag)))
class CbcMode(object): """*Cipher-Block Chaining (CBC)*. Each of the ciphertext blocks depends on the current and all previous plaintext blocks. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.2 . .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf :undocumented: __init__ """ def __init__(self, block_cipher, iv): """Create a new block cipher, configured in CBC mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : byte string/array The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be unpredictable**. Ideally it is picked randomly. Reusing the *IV* for encryptions performed with the same key compromises confidentiality. """ self._state = VoidPointer() result = raw_cbc_lib.CBC_start_operation(block_cipher.get(), c_uint8_ptr(iv), c_size_t(len(iv)), self._state.address_of()) if result: raise ValueError("Error %d while instatiating the CBC mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_cbc_lib.CBC_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() self.block_size = len(iv) """The block size of the underlying cipher, in bytes.""" self.iv = bstr(iv) """The Initialization Vector originally used to create the object. The value does not change.""" self.IV = self.iv """Alias for `iv`""" self._next = [self.encrypt, self.decrypt] def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) That also means that you cannot reuse an object for encrypting or decrypting other data with the same key. This function does not add any padding to the plaintext. :Parameters: plaintext : byte string/array The piece of data to encrypt. Its lenght must be multiple of the cipher block size. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") self._next = [self.encrypt] ciphertext = create_string_buffer(len(plaintext)) result = raw_cbc_lib.CBC_encrypt(self._state.get(), c_uint8_ptr(plaintext), ciphertext, c_size_t(len(plaintext))) if result: if result == 3: raise ValueError( "Data must be padded to %d byte boundary in CBC mode" % self.block_size) raise ValueError("Error %d while encrypting in CBC mode" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string/array The piece of data to decrypt. Its length must be multiple of the cipher block size. :Return: the decrypted data (byte string). """ if self.decrypt not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") self._next = [self.decrypt] plaintext = create_string_buffer(len(ciphertext)) result = raw_cbc_lib.CBC_decrypt(self._state.get(), c_uint8_ptr(ciphertext), plaintext, c_size_t(len(ciphertext))) if result: if result == 3: raise ValueError( "Data must be padded to %d byte boundary in CBC mode" % self.block_size) raise ValueError("Error %d while decrypting in CBC mode" % result) return get_raw_buffer(plaintext)
class Salsa20Cipher: """Salsa20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string """ def __init__(self, key, nonce): """Initialize a Salsa20 cipher object See also `new()` at the module level.""" if len(key) not in key_size: raise ValueError("Incorrect key length for Salsa20 (%d bytes)" % len(key)) if len(nonce) != 8: raise ValueError("Incorrect nonce length for Salsa20 (%d bytes)" % len(nonce)) self.nonce = _copy_bytes(None, None, nonce) self._state = VoidPointer() result = _raw_salsa20_lib.Salsa20_stream_init( c_uint8_ptr(key), c_size_t(len(key)), c_uint8_ptr(nonce), c_size_t(len(nonce)), self._state.address_of()) if result: raise ValueError("Error %d instantiating a Salsa20 cipher") self._state = SmartPointer(self._state.get(), _raw_salsa20_lib.Salsa20_stream_destroy) self.block_size = 1 self.key_size = len(key) def encrypt(self, plaintext, output=None): """Encrypt a piece of data. Args: plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size. Keyword Args: output(bytes/bytearray/memoryview): The location where the ciphertext is written to. If ``None``, the ciphertext is returned. Returns: If ``output`` is ``None``, the ciphertext is returned as ``bytes``. Otherwise, ``None``. """ if output is None: ciphertext = create_string_buffer(len(plaintext)) else: ciphertext = output if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") if len(plaintext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = _raw_salsa20_lib.Salsa20_stream_encrypt( self._state.get(), c_uint8_ptr(plaintext), c_uint8_ptr(ciphertext), c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with Salsa20" % result) if output is None: return get_raw_buffer(ciphertext) else: return None def decrypt(self, ciphertext, output=None): """Decrypt a piece of data. Args: ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size. Keyword Args: output(bytes/bytearray/memoryview): The location where the plaintext is written to. If ``None``, the plaintext is returned. Returns: If ``output`` is ``None``, the plaintext is returned as ``bytes``. Otherwise, ``None``. """ try: return self.encrypt(ciphertext, output=output) except ValueError as e: raise ValueError(str(e).replace("enc", "dec"))
class BLAKE2b_Hash(object): """Class that implements a BLAKE2b hash """ #: The internal block size of the hash algorithm in bytes. block_size = 64 def __init__(self, data, key, digest_bytes, update_after_digest): """ Initialize a BLAKE2b hash object. """ #: The size of the resulting hash in bytes. self.digest_size = digest_bytes self._update_after_digest = update_after_digest self._digest_done = False # See https://tools.ietf.org/html/draft-saarinen-blake2-02 if digest_bytes in (20, 32, 48, 64) and not key: self.oid = "1.3.6.1.4.1.1722.12.2.1." + str(digest_bytes) expect_byte_string(key) state = VoidPointer() result = _raw_blake2b_lib.blake2b_init(state.address_of(), key, c_size_t(len(key)), c_size_t(digest_bytes) ) if result: raise ValueError("Error %d while instantiating BLAKE2b" % result) self._state = SmartPointer(state.get(), _raw_blake2b_lib.blake2b_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Parameters: data : byte string The next chunk of the message being hashed. """ if self._digest_done and not self._update_after_digest: raise TypeError("You can only call 'digest' or 'hexdigest' on this object") expect_byte_string(data) result = _raw_blake2b_lib.blake2b_update(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while hashing BLAKE2b data" % result) return self def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. You cannot update the hash anymore after the first call to ``digest`` (or ``hexdigest``). :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes. """ bfr = create_string_buffer(64) result = _raw_blake2b_lib.blake2b_digest(self._state.get(), bfr) if result: raise ValueError("Error %d while creating BLAKE2b digest" % result) self._digest_done = True return get_raw_buffer(bfr)[:self.digest_size] def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. This method does not change the state of the hash object. :Return: A string of 2* `digest_size` characters. It contains only hexadecimal ASCII digits. """ return "".join(["%02x" % bord(x) for x in tuple(self.digest())]) def verify(self, mac_tag): """Verify that a given **binary** MAC (computed by another party) is valid. :Parameters: mac_tag : byte string The expected MAC of the message. :Raises ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ secret = get_random_bytes(16) mac1 = new(digest_bits=160, key=secret, data=mac_tag) mac2 = new(digest_bits=160, key=secret, data=self.digest()) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed") def hexverify(self, hex_mac_tag): """Verify that a given **printable** MAC (computed by another party) is valid. :Parameters: hex_mac_tag : string The expected MAC of the message, as a hexadecimal string. :Raises ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ self.verify(unhexlify(tobytes(hex_mac_tag))) def new(self, **kwargs): """Return a new instance of a BLAKE2b hash object.""" if "digest_bytes" not in kwargs and "digest_bits" not in kwargs: kwargs["digest_bytes"] = self.digest_size return new(**kwargs)
class ChaCha20Cipher(object): """ChaCha20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 or 12 :vartype nonce: bytes """ block_size = 1 def __init__(self, key, nonce): """Initialize a ChaCha20 cipher object See also `new()` at the module level.""" self.nonce = _copy_bytes(None, None, nonce) self._next = ( self.encrypt, self.decrypt ) self._state = VoidPointer() result = _raw_chacha20_lib.chacha20_init( self._state.address_of(), c_uint8_ptr(key), c_size_t(len(key)), self.nonce, c_size_t(len(nonce))) if result: raise ValueError("Error %d instantiating a ChaCha20 cipher") self._state = SmartPointer(self._state.get(), _raw_chacha20_lib.chacha20_destroy) def encrypt(self, plaintext, output=None): """Encrypt a piece of data. Args: plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size. Keyword Args: output(bytes/bytearray/memoryview): The location where the ciphertext is written to. If ``None``, the ciphertext is returned. Returns: If ``output`` is ``None``, the ciphertext is returned as ``bytes``. Otherwise, ``None``. """ if self.encrypt not in self._next: raise TypeError("Cipher object can only be used for decryption") self._next = ( self.encrypt, ) return self._encrypt(plaintext, output) def _encrypt(self, plaintext, output): """Encrypt without FSM checks""" if output is None: ciphertext = create_string_buffer(len(plaintext)) else: ciphertext = output if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") if len(plaintext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = _raw_chacha20_lib.chacha20_encrypt( self._state.get(), c_uint8_ptr(plaintext), c_uint8_ptr(ciphertext), c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with ChaCha20" % result) if output is None: return get_raw_buffer(ciphertext) else: return None def decrypt(self, ciphertext, output=None): """Decrypt a piece of data. Args: ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size. Keyword Args: output(bytes/bytearray/memoryview): The location where the plaintext is written to. If ``None``, the plaintext is returned. Returns: If ``output`` is ``None``, the plaintext is returned as ``bytes``. Otherwise, ``None``. """ if self.decrypt not in self._next: raise TypeError("Cipher object can only be used for encryption") self._next = ( self.decrypt, ) try: return self._encrypt(ciphertext, output) except ValueError as e: raise ValueError(str(e).replace("enc", "dec")) def seek(self, position): """Seek to a certain position in the key stream. Args: position (integer): The absolute position within the key stream, in bytes. """ position, offset = divmod(position, 64) block_low = position & 0xFFFFFFFF block_high = position >> 32 result = _raw_chacha20_lib.chacha20_seek( self._state.get(), c_ulong(block_high), c_ulong(block_low), offset ) if result: raise ValueError("Error %d while seeking with ChaCha20" % result)
class Salsa20Cipher: """Salsa20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string """ def __init__(self, key, nonce): """Initialize a Salsa20 cipher object See also `new()` at the module level.""" if len(key) not in key_size: raise ValueError("Incorrect key length for Salsa20 (%d bytes)" % len(key)) if len(nonce) != 8: raise ValueError("Incorrect nonce length for Salsa20 (%d bytes)" % len(nonce)) self.nonce = _copy_bytes(None, None, nonce) self._state = VoidPointer() result = _raw_salsa20_lib.Salsa20_stream_init(c_uint8_ptr(key), c_size_t(len(key)), c_uint8_ptr(nonce), c_size_t(len(nonce)), self._state.address_of()) if result: raise ValueError("Error %d instantiating a Salsa20 cipher") self._state = SmartPointer(self._state.get(), _raw_salsa20_lib.Salsa20_stream_destroy) self.block_size = 1 self.key_size = len(key) def encrypt(self, plaintext, output=None): """Encrypt a piece of data. Args: plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size. Keyword Args: output(bytes/bytearray/memoryview): The location where the ciphertext is written to. If ``None``, the ciphertext is returned. Returns: If ``output`` is ``None``, the ciphertext is returned as ``bytes``. Otherwise, ``None``. """ if output is None: ciphertext = create_string_buffer(len(plaintext)) else: ciphertext = output if not is_writeable_buffer(output): raise TypeError( "output must be a bytearray or a writeable memoryview") if len(plaintext) != len(output): raise ValueError( "output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = _raw_salsa20_lib.Salsa20_stream_encrypt( self._state.get(), c_uint8_ptr(plaintext), c_uint8_ptr(ciphertext), c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with Salsa20" % result) if output is None: return get_raw_buffer(ciphertext) else: return None def decrypt(self, ciphertext, output=None): """Decrypt a piece of data. Args: ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size. Keyword Args: output(bytes/bytearray/memoryview): The location where the plaintext is written to. If ``None``, the plaintext is returned. Returns: If ``output`` is ``None``, the plaintext is returned as ``bytes``. Otherwise, ``None``. """ try: return self.encrypt(ciphertext, output=output) except ValueError as e: raise ValueError(str(e).replace("enc", "dec"))
class CfbMode(object): """*Cipher FeedBack (CFB)*. This mode is similar to CFB, but it transforms the underlying block cipher into a stream cipher. Plaintext and ciphertext are processed in *segments* of **s** bits. The mode is therefore sometimes labelled **s**-bit CFB. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.3. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf :undocumented: __init__ """ def __init__(self, block_cipher, iv, segment_size): """Create a new block cipher, configured in CFB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : byte string The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be unpredictable**. Ideally it is picked randomly. Reusing the *IV* for encryptions performed with the same key compromises confidentiality. segment_size : integer The number of bytes the plaintext and ciphertext are segmented in. """ expect_byte_string(iv) self._state = VoidPointer() result = raw_cfb_lib.CFB_start_operation(block_cipher.get(), iv, c_size_t(len(iv)), c_size_t(segment_size), self._state.address_of()) if result: raise ValueError("Error %d while instatiating the CFB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_cfb_lib.CFB_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() #: The block size of the underlying cipher, in bytes. self.block_size = len(iv) #: The Initialization Vector originally used to create the object. #: The value does not change. self.IV = self.iv = iv self._next = [ self.encrypt, self.decrypt ] def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") self._next = [ self.encrypt ] expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = raw_cfb_lib.CFB_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting in CFB mode" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any length. :Return: the decrypted data (byte string). """ if self.decrypt not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") self._next = [ self.decrypt ] expect_byte_string(ciphertext) plaintext = create_string_buffer(len(ciphertext)) result = raw_cfb_lib.CFB_decrypt(self._state.get(), ciphertext, plaintext, c_size_t(len(ciphertext))) if result: raise ValueError("Error %d while decrypting in CFB mode" % result) return get_raw_buffer(plaintext)
class OcbMode(object): """Offset Codebook (OCB) mode.""" def __init__(self, factory, nonce, mac_len, cipher_params): if factory.block_size != 16: raise ValueError("OCB mode is only available for ciphers" " that operate on 128 bits blocks") #: The block size of the underlying cipher, in bytes. self.block_size = 16 self.nonce = nonce if len(nonce) not in range(1, 16): raise ValueError("Nonce must be at most 15 bytes long") self._mac_len = mac_len if not 8 <= mac_len <= 16: raise ValueError("MAC tag must be between 8 and 16 bytes long") # Cache for MAC tag self._mac_tag = None # Cache for unaligned associated data self._cache_A = b("") # Cache for unaligned ciphertext/plaintext self._cache_P = b("") # Allowed transitions after initialization self._next = [self.update, self.encrypt, self.decrypt, self.digest, self.verify] # Compute Offset_0 params_without_key = dict(cipher_params) key = params_without_key.pop("key") nonce = (bchr(self._mac_len << 4 & 0xFF) + bchr(0) * (14 - len(self.nonce)) + bchr(1) + self.nonce) bottom = bord(nonce[15]) & 0x3F # 6 bits, 0..63 ktop = factory.new(key, factory.MODE_ECB, **params_without_key)\ .encrypt(nonce[:15] + bchr(bord(nonce[15]) & 0xC0)) stretch = ktop + strxor(ktop[:8], ktop[1:9]) # 192 bits offset_0 = long_to_bytes(bytes_to_long(stretch) >> (64 - bottom), 24)[8:] # Create low-level cipher instance raw_cipher = factory._create_base_cipher(cipher_params) if cipher_params: raise TypeError("Unknown keywords: " + str(cipher_params)) self._state = VoidPointer() result = _raw_ocb_lib.OCB_start_operation(raw_cipher.get(), offset_0, c_size_t(len(offset_0)), self._state.address_of()) if result: raise ValueError("Error %d while instantiating the OCB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), _raw_ocb_lib.OCB_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode raw_cipher.release() def _update(self, assoc_data, assoc_data_len): expect_byte_string(assoc_data) result = _raw_ocb_lib.OCB_update(self._state.get(), assoc_data, c_size_t(assoc_data_len)) if result: raise ValueError("Error %d while MAC-ing in OCB mode" % result) def update(self, assoc_data): """Process the associated data. If there is any associated data, the caller has to invoke this method one or more times, before using ``decrypt`` or ``encrypt``. By *associated data* it is meant any data (e.g. packet headers) that will not be encrypted and will be transmitted in the clear. However, the receiver shall still able to detect modifications. If there is no associated data, this method must not be called. The caller may split associated data in segments of any size, and invoke this method multiple times, each time with the next segment. :Parameters: assoc_data : byte string A piece of associated data. """ if self.update not in self._next: raise TypeError("update() can only be called" " immediately after initialization") self._next = [self.encrypt, self.decrypt, self.digest, self.verify, self.update] if len(self._cache_A) > 0: filler = min(16 - len(self._cache_A), len(assoc_data)) self._cache_A += assoc_data[:filler] assoc_data = assoc_data[filler:] if len(self._cache_A) < 16: return self # Clear the cache, and proceeding with any other aligned data self._cache_A, seg = b(""), self._cache_A self.update(seg) update_len = len(assoc_data) // 16 * 16 self._cache_A = assoc_data[update_len:] self._update(assoc_data, update_len) return self def _transcrypt_aligned(self, in_data, in_data_len, trans_func, trans_desc): out_data = create_string_buffer(in_data_len) result = trans_func(self._state.get(), in_data, out_data, c_size_t(in_data_len)) if result: raise ValueError("Error %d while %sing in OCB mode" % (result, trans_desc)) return get_raw_buffer(out_data) def _transcrypt(self, in_data, trans_func, trans_desc): # Last piece to encrypt/decrypt if in_data is None: out_data = self._transcrypt_aligned(self._cache_P, len(self._cache_P), trans_func, trans_desc) self._cache_P = b("") return out_data # Try to fill up the cache, if it already contains something expect_byte_string(in_data) prefix = b("") if len(self._cache_P) > 0: filler = min(16 - len(self._cache_P), len(in_data)) self._cache_P += in_data[:filler] in_data = in_data[filler:] if len(self._cache_P) < 16: # We could not manage to fill the cache, so there is certainly # no output yet. return b("") # Clear the cache, and proceeding with any other aligned data prefix = self._transcrypt_aligned(self._cache_P, len(self._cache_P), trans_func, trans_desc) self._cache_P = b("") # Process data in multiples of the block size trans_len = len(in_data) // 16 * 16 result = self._transcrypt_aligned(in_data, trans_len, trans_func, trans_desc) if prefix: result = prefix + result # Left-over self._cache_P = in_data[trans_len:] return result def encrypt(self, plaintext=None): """Encrypt the next piece of plaintext. After the entire plaintext has been passed (but before `digest`), you **must** call this method one last time with no arguments to collect the final piece of ciphertext. If possible, use the method `encrypt_and_digest` instead. :Parameters: plaintext : byte string The next piece of data to encrypt or ``None`` to signify that encryption has finished and that any remaining ciphertext has to be produced. :Return: the ciphertext, as a byte string. Its length may not match the length of the *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() can only be called after" " initialization or an update()") if plaintext is None: self._next = [self.digest] else: self._next = [self.encrypt] return self._transcrypt(plaintext, _raw_ocb_lib.OCB_encrypt, "encrypt") def decrypt(self, ciphertext=None): """Decrypt the next piece of ciphertext. After the entire ciphertext has been passed (but before `verify`), you **must** call this method one last time with no arguments to collect the remaining piece of plaintext. If possible, use the method `decrypt_and_verify` instead. :Parameters: ciphertext : byte string The next piece of data to decrypt or ``None`` to signify that decryption has finished and that any remaining plaintext has to be produced. :Return: the plaintext, as a byte string. Its length may not match the length of the *ciphertext*. """ if self.decrypt not in self._next: raise TypeError("decrypt() can only be called after" " initialization or an update()") if ciphertext is None: self._next = [self.verify] else: self._next = [self.decrypt] return self._transcrypt(ciphertext, _raw_ocb_lib.OCB_decrypt, "decrypt") def _compute_mac_tag(self): if self._mac_tag is not None: return if self._cache_A: self._update(self._cache_A, len(self._cache_A)) self._cache_A = b("") mac_tag = create_string_buffer(16) result = _raw_ocb_lib.OCB_digest(self._state.get(), mac_tag, c_size_t(len(mac_tag)) ) if result: raise ValueError("Error %d while computing digest in OCB mode" % result) self._mac_tag = get_raw_buffer(mac_tag)[:self._mac_len] def digest(self): """Compute the *binary* MAC tag. Call this method after the final `encrypt` (the one with no arguments) to obtain the MAC tag. The MAC tag is needed by the receiver to determine authenticity of the message. :Return: the MAC, as a byte string. """ if self.digest not in self._next: raise TypeError("digest() cannot be called now for this cipher") assert(len(self._cache_P) == 0) self._next = [self.digest] if self._mac_tag is None: self._compute_mac_tag() return self._mac_tag def hexdigest(self): """Compute the *printable* MAC tag. This method is like `digest`. :Return: the MAC, as a hexadecimal string. """ return "".join(["%02x" % bord(x) for x in self.digest()]) def verify(self, received_mac_tag): """Validate the *binary* MAC tag. Call this method after the final `decrypt` (the one with no arguments) to check if the message is authentic and valid. :Parameters: received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ if self.verify not in self._next: raise TypeError("verify() cannot be called now for this cipher") assert(len(self._cache_P) == 0) self._next = [self.verify] if self._mac_tag is None: self._compute_mac_tag() secret = get_random_bytes(16) mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag) mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed") def hexverify(self, hex_mac_tag): """Validate the *printable* MAC tag. This method is like `verify`. :Parameters: hex_mac_tag : string This is the *printable* MAC, as received from the sender. :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ self.verify(unhexlify(hex_mac_tag)) def encrypt_and_digest(self, plaintext): """Encrypt the message and create the MAC tag in one step. :Parameters: plaintext : byte string The entire message to encrypt. :Return: a tuple with two byte strings: - the encrypted data - the MAC """ return self.encrypt(plaintext) + self.encrypt(), self.digest() def decrypt_and_verify(self, ciphertext, received_mac_tag): """Decrypted the message and verify its authenticity in one step. :Parameters: ciphertext : byte string The entire message to decrypt. received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Return: the decrypted data (byte string). :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ plaintext = self.decrypt(ciphertext) + self.decrypt() self.verify(received_mac_tag) return plaintext
class SHAKE256_XOF(object): """Class that implements a SHAKE256 XOF """ #: ASN.1 Object ID oid = "2.16.840.1.101.3.4.2.12" def __init__(self, data=None): state = VoidPointer() result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(64), 0x1F) if result: raise ValueError("Error %d while instantiating SHAKE256" % result) self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) self._is_squeezing = False if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) You cannot use ``update`` anymore after the first call to ``read``. :Parameters: data : byte string The next chunk of the message being hashed. """ if self._is_squeezing: raise TypeError("You cannot call 'update' after the first 'read'") expect_byte_string(data) result = _raw_keccak_lib.keccak_absorb(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while updating SHAKE256 state" % result) return self def read(self, length): """Return the next ``length`` bytes of **binary** (non-printable) digest for the message. You cannot use ``update`` anymore after the first call to ``read``. :Return: A byte string of `length` bytes. """ self._is_squeezing = True bfr = create_string_buffer(length) result = _raw_keccak_lib.keccak_squeeze(self._state.get(), bfr, c_size_t(length)) if result: raise ValueError("Error %d while extracting from SHAKE256" % result) return get_raw_buffer(bfr) def new(self, data=None): return type(self)(data=data)
class SHA3_512_Hash(object): """Class that implements a SHA-3/512 hash """ #: The size of the resulting hash in bytes. digest_size = 64 #: ASN.1 Object ID oid = "2.16.840.1.101.3.4.2.10" def __init__(self, data, update_after_digest): self._update_after_digest = update_after_digest self._digest_done = False state = VoidPointer() result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(self.digest_size * 2), 0x06) if result: raise ValueError("Error %d while instantiating SHA-3/512" % result) self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Parameters: data : byte string The next chunk of the message being hashed. """ if self._digest_done and not self._update_after_digest: raise TypeError( "You can only call 'digest' or 'hexdigest' on this object") expect_byte_string(data) result = _raw_keccak_lib.keccak_absorb(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while updating SHA-3/512" % result) return self def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. You cannot update the hash anymore after the first call to ``digest`` (or ``hexdigest``). :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes. """ self._digest_done = True bfr = create_string_buffer(self.digest_size) result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr, c_size_t(self.digest_size)) if result: raise ValueError("Error %d while instantiating SHA-3/512" % result) self._digest_value = get_raw_buffer(bfr) return self._digest_value def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. This method does not change the state of the hash object. :Return: A string of 2* `digest_size` characters. It contains only hexadecimal ASCII digits. """ return "".join(["%02x" % bord(x) for x in self.digest()]) def new(self): return type(self)(None, self._update_after_digest)
class Salsa20Cipher: """Salsa20 cipher object""" def __init__(self, key, nonce): """Initialize a Salsa20 cipher object See also `new()` at the module level.""" if len(key) not in key_size: raise ValueError("Incorrect key length for Salsa20 (%d bytes)" % len(key)) if len(nonce) != 8: raise ValueError("Incorrect nonce length for Salsa20 (%d bytes)" % len(nonce)) #: Nonce self.nonce = nonce expect_byte_string(key) expect_byte_string(nonce) self._state = VoidPointer() result = _raw_salsa20_lib.Salsa20_stream_init( key, c_size_t(len(key)), nonce, c_size_t(len(nonce)), self._state.address_of()) if result: raise ValueError("Error %d instantiating a Salsa20 cipher") self._state = SmartPointer(self._state.get(), _raw_salsa20_lib.Salsa20_stream_destroy) self.block_size = 1 self.key_size = len(key) def encrypt(self, plaintext): """Encrypt a piece of data. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any size. :Return: the encrypted data (byte string, as long as the plaintext). """ expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = _raw_salsa20_lib.Salsa20_stream_encrypt( self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with Salsa20" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt a piece of data. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any size. :Return: the decrypted data (byte string, as long as the ciphertext). """ try: return self.encrypt(ciphertext) except ValueError, e: raise ValueError(str(e).replace("enc", "dec"))
class ChaCha20Cipher(object): """ChaCha20 (or XChaCha20) cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8, 12 or 24 bytes :vartype nonce: bytes """ block_size = 1 def __init__(self, key, nonce): """Initialize a ChaCha20/XChaCha20 cipher object See also `new()` at the module level.""" # XChaCha20 requires a key derivation with HChaCha20 # See 2.3 in https://tools.ietf.org/html/draft-arciszewski-xchacha-03 if len(nonce) == 24: key = _HChaCha20(key, nonce[:16]) nonce = b'\x00' * 4 + nonce[16:] self._name = "XChaCha20" else: self._name = "ChaCha20" self.nonce = _copy_bytes(None, None, nonce) self._next = (self.encrypt, self.decrypt) self._state = VoidPointer() result = _raw_chacha20_lib.chacha20_init(self._state.address_of(), c_uint8_ptr(key), c_size_t(len(key)), self.nonce, c_size_t(len(nonce))) if result: raise ValueError("Error %d instantiating a %s cipher" % (result, self._name)) self._state = SmartPointer(self._state.get(), _raw_chacha20_lib.chacha20_destroy) def encrypt(self, plaintext, output=None): """Encrypt a piece of data. Args: plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size. Keyword Args: output(bytes/bytearray/memoryview): The location where the ciphertext is written to. If ``None``, the ciphertext is returned. Returns: If ``output`` is ``None``, the ciphertext is returned as ``bytes``. Otherwise, ``None``. """ if self.encrypt not in self._next: raise TypeError("Cipher object can only be used for decryption") self._next = (self.encrypt, ) return self._encrypt(plaintext, output) def _encrypt(self, plaintext, output): """Encrypt without FSM checks""" if output is None: ciphertext = create_string_buffer(len(plaintext)) else: ciphertext = output if not is_writeable_buffer(output): raise TypeError( "output must be a bytearray or a writeable memoryview") if len(plaintext) != len(output): raise ValueError( "output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = _raw_chacha20_lib.chacha20_encrypt(self._state.get(), c_uint8_ptr(plaintext), c_uint8_ptr(ciphertext), c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with %s" % (result, self._name)) if output is None: return get_raw_buffer(ciphertext) else: return None def decrypt(self, ciphertext, output=None): """Decrypt a piece of data. Args: ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size. Keyword Args: output(bytes/bytearray/memoryview): The location where the plaintext is written to. If ``None``, the plaintext is returned. Returns: If ``output`` is ``None``, the plaintext is returned as ``bytes``. Otherwise, ``None``. """ if self.decrypt not in self._next: raise TypeError("Cipher object can only be used for encryption") self._next = (self.decrypt, ) try: return self._encrypt(ciphertext, output) except ValueError as e: raise ValueError(str(e).replace("enc", "dec")) def seek(self, position): """Seek to a certain position in the key stream. Args: position (integer): The absolute position within the key stream, in bytes. """ position, offset = divmod(position, 64) block_low = position & 0xFFFFFFFF block_high = position >> 32 result = _raw_chacha20_lib.chacha20_seek(self._state.get(), c_ulong(block_high), c_ulong(block_low), offset) if result: raise ValueError("Error %d while seeking with %s" % (result, self._name))
class EcbMode(object): """*Electronic Code Book (ECB)*. This is the simplest encryption mode. Each of the plaintext blocks is directly encrypted into a ciphertext block, independently of any other block. This mode is dangerous because it exposes frequency of symbols in your plaintext. Other modes (e.g. *CBC*) should be used instead. See `NIST SP800-38A`_ , Section 6.1. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf """ def __init__(self, block_cipher): """Create a new block cipher, configured in ECB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. """ self._state = VoidPointer() result = raw_ecb_lib.ECB_start_operation(block_cipher.get(), self._state.address_of()) if result: raise ValueError("Error %d while instatiating the ECB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher # mode self._state = SmartPointer(self._state.get(), raw_ecb_lib.ECB_stop_operation) # Memory allocated for the underlying block cipher is now owned # by the cipher mode block_cipher.release() def encrypt(self, plaintext): """Encrypt data with the key set at initialization. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. The length must be multiple of the cipher block length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = raw_ecb_lib.ECB_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting in ECB mode" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt data with the key set at initialization. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. The length must be multiple of the cipher block length. :Return: the decrypted data (byte string). It is as long as *ciphertext*. """ expect_byte_string(ciphertext) plaintext = create_string_buffer(len(ciphertext)) result = raw_ecb_lib.ECB_decrypt(self._state.get(), ciphertext, plaintext, c_size_t(len(ciphertext))) if result: raise ValueError("Error %d while decrypting in ECB mode" % result) return get_raw_buffer(plaintext)
class ChaCha20Cipher: """ChaCha20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string """ block_size = 1 def __init__(self, key, nonce): """Initialize a ChaCha20 cipher object See also `new()` at the module level.""" expect_byte_string(key) expect_byte_string(nonce) self.nonce = nonce self._next = ( self.encrypt, self.decrypt ) self._state = VoidPointer() result = _raw_chacha20_lib.chacha20_init( self._state.address_of(), key, c_size_t(len(key)), nonce, c_size_t(len(nonce))) if result: raise ValueError("Error %d instantiating a ChaCha20 cipher") self._state = SmartPointer(self._state.get(), _raw_chacha20_lib.chacha20_destroy) def encrypt(self, plaintext): """Encrypt a piece of data. :param plaintext: The data to encrypt, of any size. :type plaintext: byte string :returns: the encrypted byte string, of equal length as the plaintext. """ if self.encrypt not in self._next: raise TypeError("Cipher object can only be used for decryption") self._next = ( self.encrypt, ) return self._encrypt(plaintext) def _encrypt(self, plaintext): """Encrypt without FSM checks""" expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = _raw_chacha20_lib.chacha20_encrypt( self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with ChaCha20" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt a piece of data. :param ciphertext: The data to decrypt, of any size. :type ciphertext: byte string :returns: the decrypted byte string, of equal length as the ciphertext. """ if self.decrypt not in self._next: raise TypeError("Cipher object can only be used for encryption") self._next = ( self.decrypt, ) try: return self._encrypt(ciphertext) except ValueError, e: raise ValueError(str(e).replace("enc", "dec"))
class CtrMode(object): """*CounTeR (CTR)* mode. This mode is very similar to ECB, in that encryption of one block is done independently of all other blocks. Unlike ECB, the block *position* contributes to the encryption and no information leaks about symbol frequency. Each message block is associated to a *counter* which must be unique across all messages that get encrypted with the same key (not just within the same message). The counter is as big as the block size. Counters can be generated in several ways. The most straightword one is to choose an *initial counter block* (which can be made public, similarly to the *IV* for the other modes) and increment its lowest **m** bits by one (modulo *2^m*) for each block. In most cases, **m** is chosen to be half the block size. See `NIST SP800-38A`_, Section 6.5 (for the mode) and Appendix B (for how to manage the *initial counter block*). .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf """ def __init__(self, block_cipher, initial_counter_block, prefix_len, counter_len, little_endian): """Create a new block cipher, configured in CTR mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. initial_counter_block : byte string The initial plaintext to use to generate the key stream. It is as large as the cipher block, and it embeds the initial value of the counter. This value must not be reused. It shall contain a nonce or a random component. Reusing the *initial counter block* for encryptions performed with the same key compromises confidentiality. prefix_len : integer The amount of bytes at the beginning of the counter block that never change. counter_len : integer The length in bytes of the counter embedded in the counter block. little_endian : boolean True if the counter in the counter block is an integer encoded in little endian mode. If False, it is big endian. """ expect_byte_string(initial_counter_block) self._state = VoidPointer() result = raw_ctr_lib.CTR_start_operation(block_cipher.get(), initial_counter_block, c_size_t(len(initial_counter_block)), c_size_t(prefix_len), counter_len, little_endian, self._state.address_of()) if result: raise ValueError("Error %X while instatiating the CTR mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_ctr_lib.CTR_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() #: The block size of the underlying cipher, in bytes. self.block_size = len(initial_counter_block) def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = raw_ctr_lib.CTR_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %X while encrypting in CTR mode" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any length. :Return: the decrypted data (byte string). """ expect_byte_string(ciphertext) plaintext = create_string_buffer(len(ciphertext)) result = raw_ctr_lib.CTR_decrypt(self._state.get(), ciphertext, plaintext, c_size_t(len(ciphertext))) if result: raise ValueError("Error %X while decrypting in CTR mode" % result) return get_raw_buffer(plaintext)
class CbcMode(object): """*Cipher-Block Chaining (CBC)*. Each of the ciphertext blocks depends on the current and all previous plaintext blocks. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.2 . .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf :undocumented: __init__ """ def __init__(self, block_cipher, iv): """Create a new block cipher, configured in CBC mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : bytes/bytearray/memoryview The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be unpredictable**. Ideally it is picked randomly. Reusing the *IV* for encryptions performed with the same key compromises confidentiality. """ self._state = VoidPointer() result = raw_cbc_lib.CBC_start_operation(block_cipher.get(), c_uint8_ptr(iv), c_size_t(len(iv)), self._state.address_of()) if result: raise ValueError("Error %d while instantiating the CBC mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_cbc_lib.CBC_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() self.block_size = len(iv) """The block size of the underlying cipher, in bytes.""" self.iv = _copy_bytes(None, None, iv) """The Initialization Vector originally used to create the object. The value does not change.""" self.IV = self.iv """Alias for `iv`""" self._next = [ self.encrypt, self.decrypt ] def encrypt(self, plaintext, output=None): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) That also means that you cannot reuse an object for encrypting or decrypting other data with the same key. This function does not add any padding to the plaintext. :Parameters: plaintext : bytes/bytearray/memoryview The piece of data to encrypt. Its lenght must be multiple of the cipher block size. :Keywords: output : bytearray/memoryview The location where the ciphertext must be written to. If ``None``, the ciphertext is returned. :Return: If ``output`` is ``None``, the ciphertext is returned as ``bytes``. Otherwise, ``None``. """ if self.encrypt not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") self._next = [ self.encrypt ] if output is None: ciphertext = create_string_buffer(len(plaintext)) else: ciphertext = output if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") if len(plaintext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = raw_cbc_lib.CBC_encrypt(self._state.get(), c_uint8_ptr(plaintext), c_uint8_ptr(ciphertext), c_size_t(len(plaintext))) if result: if result == 3: raise ValueError("Data must be padded to %d byte boundary in CBC mode" % self.block_size) raise ValueError("Error %d while encrypting in CBC mode" % result) if output is None: return get_raw_buffer(ciphertext) else: return None def decrypt(self, ciphertext, output=None): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : bytes/bytearray/memoryview The piece of data to decrypt. Its length must be multiple of the cipher block size. :Keywords: output : bytearray/memoryview The location where the plaintext must be written to. If ``None``, the plaintext is returned. :Return: If ``output`` is ``None``, the plaintext is returned as ``bytes``. Otherwise, ``None``. """ if self.decrypt not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") self._next = [ self.decrypt ] if output is None: plaintext = create_string_buffer(len(ciphertext)) else: plaintext = output if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") if len(ciphertext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = raw_cbc_lib.CBC_decrypt(self._state.get(), c_uint8_ptr(ciphertext), c_uint8_ptr(plaintext), c_size_t(len(ciphertext))) if result: if result == 3: raise ValueError("Data must be padded to %d byte boundary in CBC mode" % self.block_size) raise ValueError("Error %d while decrypting in CBC mode" % result) if output is None: return get_raw_buffer(plaintext) else: return None
class EcbMode(object): """*Electronic Code Book (ECB)*. This is the simplest encryption mode. Each of the plaintext blocks is directly encrypted into a ciphertext block, independently of any other block. This mode is dangerous because it exposes frequency of symbols in your plaintext. Other modes (e.g. *CBC*) should be used instead. See `NIST SP800-38A`_ , Section 6.1. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf :undocumented: __init__ """ def __init__(self, block_cipher): """Create a new block cipher, configured in ECB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. """ self._state = VoidPointer() result = raw_ecb_lib.ECB_start_operation(block_cipher.get(), self._state.address_of()) if result: raise ValueError("Error %d while instantiating the ECB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher # mode self._state = SmartPointer(self._state.get(), raw_ecb_lib.ECB_stop_operation) # Memory allocated for the underlying block cipher is now owned # by the cipher mode block_cipher.release() def encrypt(self, plaintext, output=None): """Encrypt data with the key set at initialization. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : bytes/bytearray/memoryview The piece of data to encrypt. The length must be multiple of the cipher block length. :Keywords: output : bytearray/memoryview The location where the ciphertext must be written to. If ``None``, the ciphertext is returned. :Return: If ``output`` is ``None``, the ciphertext is returned as ``bytes``. Otherwise, ``None``. """ if output is None: ciphertext = create_string_buffer(len(plaintext)) else: ciphertext = output if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") if len(plaintext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = raw_ecb_lib.ECB_encrypt(self._state.get(), c_uint8_ptr(plaintext), c_uint8_ptr(ciphertext), c_size_t(len(plaintext))) if result: if result == 3: raise ValueError("Data must be aligned to block boundary in ECB mode") raise ValueError("Error %d while encrypting in ECB mode" % result) if output is None: return get_raw_buffer(ciphertext) else: return None def decrypt(self, ciphertext, output=None): """Decrypt data with the key set at initialization. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : bytes/bytearray/memoryview The piece of data to decrypt. The length must be multiple of the cipher block length. :Keywords: output : bytearray/memoryview The location where the plaintext must be written to. If ``None``, the plaintext is returned. :Return: If ``output`` is ``None``, the plaintext is returned as ``bytes``. Otherwise, ``None``. """ if output is None: plaintext = create_string_buffer(len(ciphertext)) else: plaintext = output if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") if len(ciphertext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = raw_ecb_lib.ECB_decrypt(self._state.get(), c_uint8_ptr(ciphertext), c_uint8_ptr(plaintext), c_size_t(len(ciphertext))) if result: if result == 3: raise ValueError("Data must be aligned to block boundary in ECB mode") raise ValueError("Error %d while decrypting in ECB mode" % result) if output is None: return get_raw_buffer(plaintext) else: return None
class EccPoint(object): """A class to abstract a point over an Elliptic Curve. :ivar x: The X-coordinate of the ECC point :vartype x: integer :ivar y: The Y-coordinate of the ECC point :vartype y: integer """ def __init__(self, x, y): xb = long_to_bytes(x, 32) yb = long_to_bytes(y, 32) assert (len(xb) == 32) assert (len(yb) == 32) self._point = VoidPointer() result = _ec_lib.ec_ws_new_point(self._point.address_of(), c_uint8_ptr(xb), c_uint8_ptr(yb), c_size_t(len(xb)), _ec_p256_context.get()) if result: if result == 15: raise ValueError("The EC point does not belong to the curve") raise ValueError("Error %d while instantiating an EC point" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the EC point self._point = SmartPointer(self._point.get(), _ec_lib.ec_free_point) def set(self, point): self._point = VoidPointer() result = _ec_lib.ec_ws_clone(self._point.address_of(), point._point.get()) if result: raise ValueError("Error %d while cloning an EC point" % result) self._point = SmartPointer(self._point.get(), _ec_lib.ec_free_point) return self def __eq__(self, point): return 0 == _ec_lib.ec_ws_cmp(self._point.get(), point._point.get()) def __neg__(self): np = self.copy() result = _ec_lib.ec_ws_neg(np._point_get()) if result: raise ValueError("Error %d while negating an EC point" % result) return np def copy(self): x, y = self.xy np = EccPoint(x, y) return np def is_point_at_infinity(self): return self.xy == (0, 0) @staticmethod def point_at_infinity(): return EccPoint(0, 0) @property def x(self): return self.xy[0] @property def y(self): return self.xy[1] @property def xy(self): xb = bytearray(32) yb = bytearray(32) result = _ec_lib.ec_ws_get_xy(c_uint8_ptr(xb), c_uint8_ptr(yb), c_size_t(len(xb)), self._point.get()) if result: raise ValueError("Error %d while encoding an EC point" % result) return [Integer(bytes_to_long(c)) for c in (xb, yb)] def double(self): """Double this point (in-place operation). :Return: :class:`EccPoint` : this same object (to enable chaining) """ result = _ec_lib.ec_ws_double(self._point.get()) if result: raise ValueError("Error %d while doubling an EC point" % result) return self def __iadd__(self, point): """Add a second point to this one""" result = _ec_lib.ec_ws_add(self._point.get(), point._point.get()) if result: if result == 16: raise ValueError( "Trying to add two EC point that are not on the same curve" ) raise ValueError("Error %d while adding two EC points" % result) return self def __add__(self, point): """Return a new point, the addition of this one and another""" np = self.copy() np += point return np def __imul__(self, scalar): """Multiply this point by a scalar""" if scalar < 0: raise ValueError( "Scalar multiplication is only defined for non-negative integers" ) sb = long_to_bytes(scalar) result = _ec_lib.ec_ws_scalar_multiply(self._point.get(), c_uint8_ptr(sb), c_size_t(len(sb))) if result: raise ValueError("Error %d during scalar multiplication" % result) return self def __mul__(self, scalar): """Return a new point, the scalar product of this one""" np = self.copy() np *= scalar return np
class SHAKE128_XOF(object): """A SHAKE128 hash object. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string """ # ASN.1 Object ID oid = "2.16.840.1.101.3.4.2.11" def __init__(self, data=None): state = VoidPointer() result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(32), 0x1F) if result: raise ValueError("Error %d while instantiating SHAKE128" % result) self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) self._is_squeezing = False if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string): The next chunk of the message being hashed. """ if self._is_squeezing: raise TypeError("You cannot call 'update' after the first 'read'") expect_byte_string(data) result = _raw_keccak_lib.keccak_absorb(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while updating SHAKE128 state" % result) return self def read(self, length): """ Compute the next piece of XOF output. .. note:: You cannot use :meth:`update` anymore after the first call to :meth:`read`. Args: length (integer): the amount of bytes this method must return :return: the next piece of XOF output (of the given length) :rtype: byte string """ self._is_squeezing = True bfr = create_string_buffer(length) result = _raw_keccak_lib.keccak_squeeze(self._state.get(), bfr, c_size_t(length)) if result: raise ValueError("Error %d while extracting from SHAKE128" % result) return get_raw_buffer(bfr) def new(self, data=None): return type(self)(data=data)
class Keccak_Hash(object): """A Keccak hash object. Do not instantiate directly. Use the :func:`new` function. :ivar digest_size: the size in bytes of the resulting hash :vartype digest_size: integer """ def __init__(self, data, digest_bytes, update_after_digest): # The size of the resulting hash in bytes. self.digest_size = digest_bytes self._update_after_digest = update_after_digest self._digest_done = False state = VoidPointer() result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(self.digest_size * 2), 0x01) if result: raise ValueError("Error %d while instantiating keccak" % result) self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string/byte array/memoryview): The next chunk of the message being hashed. """ if self._digest_done and not self._update_after_digest: raise TypeError( "You can only call 'digest' or 'hexdigest' on this object") result = _raw_keccak_lib.keccak_absorb(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while updating keccak" % result) return self def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Binary form. :rtype: byte string """ self._digest_done = True bfr = create_string_buffer(self.digest_size) result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr, c_size_t(self.digest_size)) if result: raise ValueError("Error %d while squeezing keccak" % result) return get_raw_buffer(bfr) def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Hexadecimal encoded. :rtype: string """ return "".join(["%02x" % bord(x) for x in self.digest()]) def new(self, **kwargs): """Create a fresh Keccak hash object.""" if "digest_bytes" not in kwargs and "digest_bits" not in kwargs: kwargs["digest_bytes"] = self.digest_size return new(**kwargs)
class CfbMode(object): """*Cipher FeedBack (CFB)*. This mode is similar to CFB, but it transforms the underlying block cipher into a stream cipher. Plaintext and ciphertext are processed in *segments* of **s** bits. The mode is therefore sometimes labelled **s**-bit CFB. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.3. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf :undocumented: __init__ """ def __init__(self, block_cipher, iv, segment_size): """Create a new block cipher, configured in CFB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : bytes/bytearray/memoryview The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be unpredictable**. Ideally it is picked randomly. Reusing the *IV* for encryptions performed with the same key compromises confidentiality. segment_size : integer The number of bytes the plaintext and ciphertext are segmented in. """ self._state = VoidPointer() result = raw_cfb_lib.CFB_start_operation(block_cipher.get(), c_uint8_ptr(iv), c_size_t(len(iv)), c_size_t(segment_size), self._state.address_of()) if result: raise ValueError("Error %d while instatiating the CFB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_cfb_lib.CFB_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() self.block_size = len(iv) """The block size of the underlying cipher, in bytes.""" self.iv = _copy_bytes(None, None, iv) """The Initialization Vector originally used to create the object. The value does not change.""" self.IV = self.iv """Alias for `iv`""" self._next = [self.encrypt, self.decrypt] def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : bytes/bytearray/memoryview The piece of data to encrypt. It can be of any length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") self._next = [self.encrypt] ciphertext = create_string_buffer(len(plaintext)) result = raw_cfb_lib.CFB_encrypt(self._state.get(), c_uint8_ptr(plaintext), ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting in CFB mode" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : bytes/bytearray/memoryview The piece of data to decrypt. It can be of any length. :Return: the decrypted data (byte string). """ if self.decrypt not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") self._next = [self.decrypt] plaintext = create_string_buffer(len(ciphertext)) result = raw_cfb_lib.CFB_decrypt(self._state.get(), c_uint8_ptr(ciphertext), plaintext, c_size_t(len(ciphertext))) if result: raise ValueError("Error %d while decrypting in CFB mode" % result) return get_raw_buffer(plaintext)
class SHA3_224_Hash(object): """Class that implements a SHA-3/224 hash """ #: The size of the resulting hash in bytes. digest_size = 28 #: ASN.1 Object ID oid = "2.16.840.1.101.3.4.2.7" def __init__(self, data, update_after_digest): self._update_after_digest = update_after_digest self._digest_done = False state = VoidPointer() result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(self.digest_size * 2), 0x06) if result: raise ValueError("Error %d while instantiating SHA-3/224" % result) self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Parameters: data : byte string The next chunk of the message being hashed. """ if self._digest_done and not self._update_after_digest: raise TypeError("You can only call 'digest' or 'hexdigest' on this object") expect_byte_string(data) result = _raw_keccak_lib.keccak_absorb(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while updating SHA-3/224" % result) return self def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. You cannot update the hash anymore after the first call to ``digest`` (or ``hexdigest``). :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes. """ self._digest_done = True bfr = create_string_buffer(self.digest_size) result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr, c_size_t(self.digest_size)) if result: raise ValueError("Error %d while instantiating SHA-3/224" % result) self._digest_value = get_raw_buffer(bfr) return self._digest_value def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. This method does not change the state of the hash object. :Return: A string of 2* `digest_size` characters. It contains only hexadecimal ASCII digits. """ return "".join(["%02x" % bord(x) for x in self.digest()]) def new(self): return type(self)(None, self._update_after_digest)
class OcbMode(object): """Offset Codebook (OCB) mode. :undocumented: __init__ """ def __init__(self, factory, nonce, mac_len, cipher_params): if factory.block_size != 16: raise ValueError("OCB mode is only available for ciphers" " that operate on 128 bits blocks") self.block_size = 16 """The block size of the underlying cipher, in bytes.""" self.nonce = _copy_bytes(None, None, nonce) """Nonce used for this session.""" if len(nonce) not in list(range(1, 16)): raise ValueError("Nonce must be at most 15 bytes long") if isinstance(nonce, str): raise TypeError("Nonce must be a byte string") self._mac_len = mac_len if not 8 <= mac_len <= 16: raise ValueError("MAC tag must be between 8 and 16 bytes long") # Cache for MAC tag self._mac_tag = None # Cache for unaligned associated data self._cache_A = b"" # Cache for unaligned ciphertext/plaintext self._cache_P = b"" # Allowed transitions after initialization self._next = [self.update, self.encrypt, self.decrypt, self.digest, self.verify] # Compute Offset_0 params_without_key = dict(cipher_params) key = params_without_key.pop("key") nonce = (struct.pack('B', self._mac_len << 4 & 0xFF) + b'\x00' * (14 - len(nonce)) + b'\x01' + self.nonce) bottom_bits = bord(nonce[15]) & 0x3F # 6 bits, 0..63 top_bits = bord(nonce[15]) & 0xC0 # 2 bits ktop_cipher = factory.new(key, factory.MODE_ECB, **params_without_key) ktop = ktop_cipher.encrypt(struct.pack('15sB', nonce[:15], top_bits)) stretch = ktop + strxor(ktop[:8], ktop[1:9]) # 192 bits offset_0 = long_to_bytes(bytes_to_long(stretch) >> (64 - bottom_bits), 24)[8:] # Create low-level cipher instance raw_cipher = factory._create_base_cipher(cipher_params) if cipher_params: raise TypeError("Unknown keywords: " + str(cipher_params)) self._state = VoidPointer() result = _raw_ocb_lib.OCB_start_operation(raw_cipher.get(), offset_0, c_size_t(len(offset_0)), self._state.address_of()) if result: raise ValueError("Error %d while instantiating the OCB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), _raw_ocb_lib.OCB_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode raw_cipher.release() def _update(self, assoc_data, assoc_data_len): result = _raw_ocb_lib.OCB_update(self._state.get(), c_uint8_ptr(assoc_data), c_size_t(assoc_data_len)) if result: raise ValueError("Error %d while computing MAC in OCB mode" % result) def update(self, assoc_data): """Process the associated data. If there is any associated data, the caller has to invoke this method one or more times, before using ``decrypt`` or ``encrypt``. By *associated data* it is meant any data (e.g. packet headers) that will not be encrypted and will be transmitted in the clear. However, the receiver shall still able to detect modifications. If there is no associated data, this method must not be called. The caller may split associated data in segments of any size, and invoke this method multiple times, each time with the next segment. :Parameters: assoc_data : bytes/bytearray/memoryview A piece of associated data. """ if self.update not in self._next: raise TypeError("update() can only be called" " immediately after initialization") self._next = [self.encrypt, self.decrypt, self.digest, self.verify, self.update] if len(self._cache_A) > 0: filler = min(16 - len(self._cache_A), len(assoc_data)) self._cache_A += _copy_bytes(None, filler, assoc_data) assoc_data = assoc_data[filler:] if len(self._cache_A) < 16: return self # Clear the cache, and proceeding with any other aligned data self._cache_A, seg = b"", self._cache_A self.update(seg) update_len = len(assoc_data) // 16 * 16 self._cache_A = _copy_bytes(update_len, None, assoc_data) self._update(assoc_data, update_len) return self def _transcrypt_aligned(self, in_data, in_data_len, trans_func, trans_desc): out_data = create_string_buffer(in_data_len) result = trans_func(self._state.get(), in_data, out_data, c_size_t(in_data_len)) if result: raise ValueError("Error %d while %sing in OCB mode" % (result, trans_desc)) return get_raw_buffer(out_data) def _transcrypt(self, in_data, trans_func, trans_desc): # Last piece to encrypt/decrypt if in_data is None: out_data = self._transcrypt_aligned(self._cache_P, len(self._cache_P), trans_func, trans_desc) self._cache_P = b"" return out_data # Try to fill up the cache, if it already contains something prefix = b"" if len(self._cache_P) > 0: filler = min(16 - len(self._cache_P), len(in_data)) self._cache_P += _copy_bytes(None, filler, in_data) in_data = in_data[filler:] if len(self._cache_P) < 16: # We could not manage to fill the cache, so there is certainly # no output yet. return b"" # Clear the cache, and proceeding with any other aligned data prefix = self._transcrypt_aligned(self._cache_P, len(self._cache_P), trans_func, trans_desc) self._cache_P = b"" # Process data in multiples of the block size trans_len = len(in_data) // 16 * 16 result = self._transcrypt_aligned(c_uint8_ptr(in_data), trans_len, trans_func, trans_desc) if prefix: result = prefix + result # Left-over self._cache_P = _copy_bytes(trans_len, None, in_data) return result def encrypt(self, plaintext=None): """Encrypt the next piece of plaintext. After the entire plaintext has been passed (but before `digest`), you **must** call this method one last time with no arguments to collect the final piece of ciphertext. If possible, use the method `encrypt_and_digest` instead. :Parameters: plaintext : bytes/bytearray/memoryview The next piece of data to encrypt or ``None`` to signify that encryption has finished and that any remaining ciphertext has to be produced. :Return: the ciphertext, as a byte string. Its length may not match the length of the *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() can only be called after" " initialization or an update()") if plaintext is None: self._next = [self.digest] else: self._next = [self.encrypt] return self._transcrypt(plaintext, _raw_ocb_lib.OCB_encrypt, "encrypt") def decrypt(self, ciphertext=None): """Decrypt the next piece of ciphertext. After the entire ciphertext has been passed (but before `verify`), you **must** call this method one last time with no arguments to collect the remaining piece of plaintext. If possible, use the method `decrypt_and_verify` instead. :Parameters: ciphertext : bytes/bytearray/memoryview The next piece of data to decrypt or ``None`` to signify that decryption has finished and that any remaining plaintext has to be produced. :Return: the plaintext, as a byte string. Its length may not match the length of the *ciphertext*. """ if self.decrypt not in self._next: raise TypeError("decrypt() can only be called after" " initialization or an update()") if ciphertext is None: self._next = [self.verify] else: self._next = [self.decrypt] return self._transcrypt(ciphertext, _raw_ocb_lib.OCB_decrypt, "decrypt") def _compute_mac_tag(self): if self._mac_tag is not None: return if self._cache_A: self._update(self._cache_A, len(self._cache_A)) self._cache_A = b"" mac_tag = create_string_buffer(16) result = _raw_ocb_lib.OCB_digest(self._state.get(), mac_tag, c_size_t(len(mac_tag)) ) if result: raise ValueError("Error %d while computing digest in OCB mode" % result) self._mac_tag = get_raw_buffer(mac_tag)[:self._mac_len] def digest(self): """Compute the *binary* MAC tag. Call this method after the final `encrypt` (the one with no arguments) to obtain the MAC tag. The MAC tag is needed by the receiver to determine authenticity of the message. :Return: the MAC, as a byte string. """ if self.digest not in self._next: raise TypeError("digest() cannot be called now for this cipher") assert(len(self._cache_P) == 0) self._next = [self.digest] if self._mac_tag is None: self._compute_mac_tag() return self._mac_tag def hexdigest(self): """Compute the *printable* MAC tag. This method is like `digest`. :Return: the MAC, as a hexadecimal string. """ return "".join(["%02x" % bord(x) for x in self.digest()]) def verify(self, received_mac_tag): """Validate the *binary* MAC tag. Call this method after the final `decrypt` (the one with no arguments) to check if the message is authentic and valid. :Parameters: received_mac_tag : bytes/bytearray/memoryview This is the *binary* MAC, as received from the sender. :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ if self.verify not in self._next: raise TypeError("verify() cannot be called now for this cipher") assert(len(self._cache_P) == 0) self._next = [self.verify] if self._mac_tag is None: self._compute_mac_tag() secret = get_random_bytes(16) mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag) mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed") def hexverify(self, hex_mac_tag): """Validate the *printable* MAC tag. This method is like `verify`. :Parameters: hex_mac_tag : string This is the *printable* MAC, as received from the sender. :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ self.verify(unhexlify(hex_mac_tag)) def encrypt_and_digest(self, plaintext): """Encrypt the message and create the MAC tag in one step. :Parameters: plaintext : bytes/bytearray/memoryview The entire message to encrypt. :Return: a tuple with two byte strings: - the encrypted data - the MAC """ return self.encrypt(plaintext) + self.encrypt(), self.digest() def decrypt_and_verify(self, ciphertext, received_mac_tag): """Decrypted the message and verify its authenticity in one step. :Parameters: ciphertext : bytes/bytearray/memoryview The entire message to decrypt. received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Return: the decrypted data (byte string). :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ plaintext = self.decrypt(ciphertext) + self.decrypt() self.verify(received_mac_tag) return plaintext
class SHAKE128_XOF(object): """Class that implements a SHAKE128 XOF """ #: ASN.1 Object ID oid = "2.16.840.1.101.3.4.2.11" def __init__(self, data=None): state = VoidPointer() result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(32), 0x1F) if result: raise ValueError("Error %d while instantiating SHAKE128" % result) self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) self._is_squeezing = False if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) You cannot use ``update`` anymore after the first call to ``read``. :Parameters: data : byte string The next chunk of the message being hashed. """ if self._is_squeezing: raise TypeError("You cannot call 'update' after the first 'read'") expect_byte_string(data) result = _raw_keccak_lib.keccak_absorb(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while updating SHAKE128 state" % result) return self def read(self, length): """Return the next ``length`` bytes of **binary** (non-printable) digest for the message. You cannot use ``update`` anymore after the first call to ``read``. :Return: A byte string of `length` bytes. """ self._is_squeezing = True bfr = create_string_buffer(length) result = _raw_keccak_lib.keccak_squeeze(self._state.get(), bfr, c_size_t(length)) if result: raise ValueError("Error %d while extracting from SHAKE128" % result) return get_raw_buffer(bfr) def new(self, data=None): return type(self)(data=data)
class SHAKE128_XOF(object): """A SHAKE128 hash object. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string """ # ASN.1 Object ID oid = "2.16.840.1.101.3.4.2.11" def __init__(self, data=None): state = VoidPointer() result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(32), 0x1F) if result: raise ValueError("Error %d while instantiating SHAKE128" % result) self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) self._is_squeezing = False if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string/array): The next chunk of the message being hashed. """ if self._is_squeezing: raise TypeError("You cannot call 'update' after the first 'read'") result = _raw_keccak_lib.keccak_absorb(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while updating SHAKE128 state" % result) return self def read(self, length): """ Compute the next piece of XOF output. .. note:: You cannot use :meth:`update` anymore after the first call to :meth:`read`. Args: length (integer): the amount of bytes this method must return :return: the next piece of XOF output (of the given length) :rtype: byte string """ self._is_squeezing = True bfr = create_string_buffer(length) result = _raw_keccak_lib.keccak_squeeze(self._state.get(), bfr, c_size_t(length)) if result: raise ValueError("Error %d while extracting from SHAKE128" % result) return get_raw_buffer(bfr) def new(self, data=None): return type(self)(data=data)
class EcbMode(object): """*Electronic Code Book (ECB)*. This is the simplest encryption mode. Each of the plaintext blocks is directly encrypted into a ciphertext block, independently of any other block. This mode is dangerous because it exposes frequency of symbols in your plaintext. Other modes (e.g. *CBC*) should be used instead. See `NIST SP800-38A`_ , Section 6.1. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf :undocumented: __init__ """ def __init__(self, block_cipher): """Create a new block cipher, configured in ECB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. """ self.block_size = block_cipher.block_size self._state = VoidPointer() result = raw_ecb_lib.ECB_start_operation(block_cipher.get(), self._state.address_of()) if result: raise ValueError("Error %d while instantiating the ECB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher # mode self._state = SmartPointer(self._state.get(), raw_ecb_lib.ECB_stop_operation) # Memory allocated for the underlying block cipher is now owned # by the cipher mode block_cipher.release() def encrypt(self, plaintext, output=None): """Encrypt data with the key set at initialization. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : bytes/bytearray/memoryview The piece of data to encrypt. The length must be multiple of the cipher block length. :Keywords: output : bytearray/memoryview The location where the ciphertext must be written to. If ``None``, the ciphertext is returned. :Return: If ``output`` is ``None``, the ciphertext is returned as ``bytes``. Otherwise, ``None``. """ if output is None: ciphertext = create_string_buffer(len(plaintext)) else: ciphertext = output if not is_writeable_buffer(output): raise TypeError( "output must be a bytearray or a writeable memoryview") if len(plaintext) != len(output): raise ValueError( "output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = raw_ecb_lib.ECB_encrypt(self._state.get(), c_uint8_ptr(plaintext), c_uint8_ptr(ciphertext), c_size_t(len(plaintext))) if result: if result == 3: raise ValueError( "Data must be aligned to block boundary in ECB mode") raise ValueError("Error %d while encrypting in ECB mode" % result) if output is None: return get_raw_buffer(ciphertext) else: return None def decrypt(self, ciphertext, output=None): """Decrypt data with the key set at initialization. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : bytes/bytearray/memoryview The piece of data to decrypt. The length must be multiple of the cipher block length. :Keywords: output : bytearray/memoryview The location where the plaintext must be written to. If ``None``, the plaintext is returned. :Return: If ``output`` is ``None``, the plaintext is returned as ``bytes``. Otherwise, ``None``. """ if output is None: plaintext = create_string_buffer(len(ciphertext)) else: plaintext = output if not is_writeable_buffer(output): raise TypeError( "output must be a bytearray or a writeable memoryview") if len(ciphertext) != len(output): raise ValueError( "output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = raw_ecb_lib.ECB_decrypt(self._state.get(), c_uint8_ptr(ciphertext), c_uint8_ptr(plaintext), c_size_t(len(ciphertext))) if result: if result == 3: raise ValueError( "Data must be aligned to block boundary in ECB mode") raise ValueError("Error %d while decrypting in ECB mode" % result) if output is None: return get_raw_buffer(plaintext) else: return None
class BLAKE2b_Hash(object): """A BLAKE2b hash object. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string :ivar block_size: the size in bytes of the internal message block, input to the compression function :vartype block_size: integer :ivar digest_size: the size in bytes of the resulting hash :vartype digest_size: integer """ # The internal block size of the hash algorithm in bytes. block_size = 64 def __init__(self, data, key, digest_bytes, update_after_digest): # The size of the resulting hash in bytes. self.digest_size = digest_bytes self._update_after_digest = update_after_digest self._digest_done = False # See https://tools.ietf.org/html/rfc7693 if digest_bytes in (20, 32, 48, 64) and not key: self.oid = "1.3.6.1.4.1.1722.12.2.1." + str(digest_bytes) expect_byte_string(key) state = VoidPointer() result = _raw_blake2b_lib.blake2b_init(state.address_of(), key, c_size_t(len(key)), c_size_t(digest_bytes) ) if result: raise ValueError("Error %d while instantiating BLAKE2b" % result) self._state = SmartPointer(state.get(), _raw_blake2b_lib.blake2b_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string): The next chunk of the message being hashed. """ if self._digest_done and not self._update_after_digest: raise TypeError("You can only call 'digest' or 'hexdigest' on this object") expect_byte_string(data) result = _raw_blake2b_lib.blake2b_update(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while hashing BLAKE2b data" % result) return self def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Binary form. :rtype: byte string """ bfr = create_string_buffer(64) result = _raw_blake2b_lib.blake2b_digest(self._state.get(), bfr) if result: raise ValueError("Error %d while creating BLAKE2b digest" % result) self._digest_done = True return get_raw_buffer(bfr)[:self.digest_size] def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Hexadecimal encoded. :rtype: string """ return "".join(["%02x" % bord(x) for x in tuple(self.digest())]) def verify(self, mac_tag): """Verify that a given **binary** MAC (computed by another party) is valid. Args: mac_tag (byte string): the expected MAC of the message. Raises: ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ secret = get_random_bytes(16) mac1 = new(digest_bits=160, key=secret, data=mac_tag) mac2 = new(digest_bits=160, key=secret, data=self.digest()) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed") def hexverify(self, hex_mac_tag): """Verify that a given **printable** MAC (computed by another party) is valid. Args: hex_mac_tag (string): the expected MAC of the message, as a hexadecimal string. Raises: ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ self.verify(unhexlify(tobytes(hex_mac_tag))) def new(self, **kwargs): """Return a new instance of a BLAKE2b hash object. See :func:`new`. """ if "digest_bytes" not in kwargs and "digest_bits" not in kwargs: kwargs["digest_bytes"] = self.digest_size return new(**kwargs)
class OfbMode(object): """*Output FeedBack (OFB)*. This mode is very similar to CBC, but it transforms the underlying block cipher into a stream cipher. The keystream is the iterated block encryption of the previous ciphertext block. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.4. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf :undocumented: __init__ """ def __init__(self, block_cipher, iv): """Create a new block cipher, configured in OFB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : bytes/bytearray/memoryview The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be a nonce, to to be reused for any other message**. It shall be a nonce or a random value. Reusing the *IV* for encryptions performed with the same key compromises confidentiality. """ self._state = VoidPointer() result = raw_ofb_lib.OFB_start_operation(block_cipher.get(), c_uint8_ptr(iv), c_size_t(len(iv)), self._state.address_of()) if result: raise ValueError("Error %d while instatiating the OFB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_ofb_lib.OFB_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() self.block_size = len(iv) """The block size of the underlying cipher, in bytes.""" self.iv = _copy_bytes(None, None, iv) """The Initialization Vector originally used to create the object. The value does not change.""" self.IV = self.iv """Alias for `iv`""" self._next = [ self.encrypt, self.decrypt ] def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : bytes/bytearray/memoryview The piece of data to encrypt. It can be of any length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") self._next = [ self.encrypt ] ciphertext = create_string_buffer(len(plaintext)) result = raw_ofb_lib.OFB_encrypt(self._state.get(), c_uint8_ptr(plaintext), ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting in OFB mode" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : bytes/bytearray/memoryview The piece of data to decrypt. It can be of any length. :Return: the decrypted data (byte string). """ if self.decrypt not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") self._next = [ self.decrypt ] plaintext = create_string_buffer(len(ciphertext)) result = raw_ofb_lib.OFB_decrypt(self._state.get(), c_uint8_ptr(ciphertext), plaintext, c_size_t(len(ciphertext))) if result: raise ValueError("Error %d while decrypting in OFB mode" % result) return get_raw_buffer(plaintext)
class SHA3_384_Hash(object): """A SHA3-384 hash object. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string :ivar digest_size: the size in bytes of the resulting hash :vartype digest_size: integer """ # The size of the resulting hash in bytes. digest_size = 48 # ASN.1 Object ID oid = "2.16.840.1.101.3.4.2.9" def __init__(self, data, update_after_digest): self._update_after_digest = update_after_digest self._digest_done = False state = VoidPointer() result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(self.digest_size * 2), 0x06) if result: raise ValueError("Error %d while instantiating SHA-3/384" % result) self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string/array): The next chunk of the message being hashed. """ if self._digest_done and not self._update_after_digest: raise TypeError( "You can only call 'digest' or 'hexdigest' on this object") result = _raw_keccak_lib.keccak_absorb(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while updating SHA-3/384" % result) return self def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Binary form. :rtype: byte string """ self._digest_done = True bfr = create_string_buffer(self.digest_size) result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr, c_size_t(self.digest_size)) if result: raise ValueError("Error %d while instantiating SHA-3/384" % result) self._digest_value = get_raw_buffer(bfr) return self._digest_value def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Hexadecimal encoded. :rtype: string """ return "".join(["%02x" % bord(x) for x in self.digest()]) def new(self): """Create a fresh SHA3-384 hash object.""" return type(self)(None, self._update_after_digest)
class SHA3_384_Hash(object): """Class that implements a SHA-3/384 hash """ #: The size of the resulting hash in bytes. digest_size = 48 name = "SHA3_384" def __init__(self, data=None): state = VoidPointer() result = _raw_sha3_384_lib.SHA3_384_init(state.address_of()) if result: raise ValueError("Error %d while instantiating SHA-3/384" % result) self._state = SmartPointer(state.get(), _raw_sha3_384_lib.SHA3_384_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Parameters: data : byte string The next chunk of the message being hashed. """ expect_byte_string(data) result = _raw_sha3_384_lib.SHA3_384_update(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while instantiating SHA-3/384" % result) def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. This method does not change the state of the hash object. You can continue updating the object after calling this function. :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes. """ bfr = create_string_buffer(self.digest_size) result = _raw_sha3_384_lib.SHA3_384_digest(self._state.get(), bfr) if result: raise ValueError("Error %d while instantiating SHA-3/384" % result) return get_raw_buffer(bfr) def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. This method does not change the state of the hash object. :Return: A string of 2* `digest_size` characters. It contains only hexadecimal ASCII digits. """ return "".join(["%02x" % bord(x) for x in self.digest()]) def copy(self): """Return a copy ("clone") of the hash object. The copy will have the same internal state as the original hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. :Return: A hash object of the same type """ clone = SHA3_384_Hash() result = _raw_sha3_384_lib.SHA3_384_copy(self._state.get(), clone._state.get()) if result: raise ValueError("Error %d while copying SHA-3/384" % result) return clone def new(self, data=None): return SHA3_384_Hash(data)
class MD5Hash(object): """A MD5 hash object. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string :ivar block_size: the size in bytes of the internal message block, input to the compression function :vartype block_size: integer :ivar digest_size: the size in bytes of the resulting hash :vartype digest_size: integer """ # The size of the resulting hash in bytes. digest_size = 16 # The internal block size of the hash algorithm in bytes. block_size = 64 # ASN.1 Object ID oid = "1.2.840.113549.2.5" def __init__(self, data=None): state = VoidPointer() result = _raw_md5_lib.MD5_init(state.address_of()) if result: raise ValueError("Error %d while instantiating MD5" % result) self._state = SmartPointer(state.get(), _raw_md5_lib.MD5_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string/byte array/memoryview): The next chunk of the message being hashed. """ result = _raw_md5_lib.MD5_update(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while instantiating MD5" % result) def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Binary form. :rtype: byte string """ bfr = create_string_buffer(self.digest_size) result = _raw_md5_lib.MD5_digest(self._state.get(), bfr) if result: raise ValueError("Error %d while instantiating MD5" % result) return get_raw_buffer(bfr) def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Hexadecimal encoded. :rtype: string """ return "".join(["%02x" % bord(x) for x in self.digest()]) def copy(self): """Return a copy ("clone") of the hash object. The copy will have the same internal state as the original hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. :return: A hash object of the same type """ clone = MD5Hash() result = _raw_md5_lib.MD5_copy(self._state.get(), clone._state.get()) if result: raise ValueError("Error %d while copying MD5" % result) return clone def new(self, data=None): """Create a fresh SHA-1 hash object.""" return MD5Hash(data)
class CtrMode(object): """*CounTeR (CTR)* mode. This mode is very similar to ECB, in that encryption of one block is done independently of all other blocks. Unlike ECB, the block *position* contributes to the encryption and no information leaks about symbol frequency. Each message block is associated to a *counter* which must be unique across all messages that get encrypted with the same key (not just within the same message). The counter is as big as the block size. Counters can be generated in several ways. The most straightword one is to choose an *initial counter block* (which can be made public, similarly to the *IV* for the other modes) and increment its lowest **m** bits by one (modulo *2^m*) for each block. In most cases, **m** is chosen to be half the block size. See `NIST SP800-38A`_, Section 6.5 (for the mode) and Appendix B (for how to manage the *initial counter block*). .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf :undocumented: __init__ """ def __init__(self, block_cipher, initial_counter_block, prefix_len, counter_len, little_endian): """Create a new block cipher, configured in CTR mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. initial_counter_block : bytes/bytearray/memoryview The initial plaintext to use to generate the key stream. It is as large as the cipher block, and it embeds the initial value of the counter. This value must not be reused. It shall contain a nonce or a random component. Reusing the *initial counter block* for encryptions performed with the same key compromises confidentiality. prefix_len : integer The amount of bytes at the beginning of the counter block that never change. counter_len : integer The length in bytes of the counter embedded in the counter block. little_endian : boolean True if the counter in the counter block is an integer encoded in little endian mode. If False, it is big endian. """ if len(initial_counter_block) == prefix_len + counter_len: self.nonce = _copy_bytes(None, prefix_len, initial_counter_block) """Nonce; not available if there is a fixed suffix""" self._state = VoidPointer() result = raw_ctr_lib.CTR_start_operation(block_cipher.get(), c_uint8_ptr(initial_counter_block), c_size_t(len(initial_counter_block)), c_size_t(prefix_len), counter_len, little_endian, self._state.address_of()) if result: raise ValueError("Error %X while instatiating the CTR mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_ctr_lib.CTR_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() self.block_size = len(initial_counter_block) """The block size of the underlying cipher, in bytes.""" self._next = [self.encrypt, self.decrypt] def encrypt(self, plaintext, output=None): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : bytes/bytearray/memoryview The piece of data to encrypt. It can be of any length. :Keywords: output : bytearray/memoryview The location where the ciphertext must be written to. If ``None``, the ciphertext is returned. :Return: If ``output`` is ``None``, the ciphertext is returned as ``bytes``. Otherwise, ``None``. """ if self.encrypt not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") self._next = [self.encrypt] if output is None: ciphertext = create_string_buffer(len(plaintext)) else: ciphertext = output if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") if len(plaintext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = raw_ctr_lib.CTR_encrypt(self._state.get(), c_uint8_ptr(plaintext), c_uint8_ptr(ciphertext), c_size_t(len(plaintext))) if result: if result == 0x60002: raise OverflowError("The counter has wrapped around in" " CTR mode") raise ValueError("Error %X while encrypting in CTR mode" % result) if output is None: return get_raw_buffer(ciphertext) else: return None def decrypt(self, ciphertext, output=None): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : bytes/bytearray/memoryview The piece of data to decrypt. It can be of any length. :Keywords: output : bytearray/memoryview The location where the plaintext must be written to. If ``None``, the plaintext is returned. :Return: If ``output`` is ``None``, the plaintext is returned as ``bytes``. Otherwise, ``None``. """ if self.decrypt not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") self._next = [self.decrypt] if output is None: plaintext = create_string_buffer(len(ciphertext)) else: plaintext = output if not is_writeable_buffer(output): raise TypeError("output must be a bytearray or a writeable memoryview") if len(ciphertext) != len(output): raise ValueError("output must have the same length as the input" " (%d bytes)" % len(plaintext)) result = raw_ctr_lib.CTR_decrypt(self._state.get(), c_uint8_ptr(ciphertext), c_uint8_ptr(plaintext), c_size_t(len(ciphertext))) if result: if result == 0x60002: raise OverflowError("The counter has wrapped around in" " CTR mode") raise ValueError("Error %X while decrypting in CTR mode" % result) if output is None: return get_raw_buffer(plaintext) else: return None
class EccPoint(object): """A class to abstract a point over an Elliptic Curve. The class support special methods for: * Adding two points: ``R = S + T`` * In-place addition: ``S += T`` * Negating a point: ``R = -T`` * Comparing two points: ``if S == T: ...`` * Multiplying a point by a scalar: ``R = S*k`` * In-place multiplication by a scalar: ``T *= k`` :ivar x: The affine X-coordinate of the ECC point :vartype x: integer :ivar y: The affine Y-coordinate of the ECC point :vartype y: integer :ivar xy: The tuple with X- and Y- coordinates """ def __init__(self, x, y, curve="p256"): try: self._curve = _curves[curve] except KeyError: raise ValueError("Unknown curve name %s" % str(curve)) self._curve_name = curve modulus_bytes = self.size_in_bytes() context = self._curve.context xb = long_to_bytes(x, modulus_bytes) yb = long_to_bytes(y, modulus_bytes) if len(xb) != modulus_bytes or len(yb) != modulus_bytes: raise ValueError("Incorrect coordinate length") self._point = VoidPointer() result = _ec_lib.ec_ws_new_point(self._point.address_of(), c_uint8_ptr(xb), c_uint8_ptr(yb), c_size_t(modulus_bytes), context.get()) if result: if result == 15: raise ValueError("The EC point does not belong to the curve") raise ValueError("Error %d while instantiating an EC point" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the EC point self._point = SmartPointer(self._point.get(), _ec_lib.ec_free_point) def set(self, point): self._point = VoidPointer() result = _ec_lib.ec_ws_clone(self._point.address_of(), point._point.get()) if result: raise ValueError("Error %d while cloning an EC point" % result) self._point = SmartPointer(self._point.get(), _ec_lib.ec_free_point) return self def __eq__(self, point): return 0 == _ec_lib.ec_ws_cmp(self._point.get(), point._point.get()) def __neg__(self): np = self.copy() result = _ec_lib.ec_ws_neg(np._point_get()) if result: raise ValueError("Error %d while negating an EC point" % result) return np def copy(self): """Return a copy of this point.""" x, y = self.xy np = EccPoint(x, y, self._curve_name) return np def is_point_at_infinity(self): """``True`` if this is the point-at-infinity.""" return self.xy == (0, 0) def point_at_infinity(self): """Return the point-at-infinity for the curve this point is on.""" return EccPoint(0, 0, self._curve_name) @property def x(self): return self.xy[0] @property def y(self): return self.xy[1] @property def xy(self): modulus_bytes = self.size_in_bytes() xb = bytearray(modulus_bytes) yb = bytearray(modulus_bytes) result = _ec_lib.ec_ws_get_xy(c_uint8_ptr(xb), c_uint8_ptr(yb), c_size_t(modulus_bytes), self._point.get()) if result: raise ValueError("Error %d while encoding an EC point" % result) return (Integer(bytes_to_long(xb)), Integer(bytes_to_long(yb))) def size_in_bytes(self): """Size of each coordinate, in bytes.""" return (self.size_in_bits() + 7) // 8 def size_in_bits(self): """Size of each coordinate, in bits.""" return self._curve.modulus_bits def double(self): """Double this point (in-place operation). :Return: :class:`EccPoint` : this same object (to enable chaining) """ result = _ec_lib.ec_ws_double(self._point.get()) if result: raise ValueError("Error %d while doubling an EC point" % result) return self def __iadd__(self, point): """Add a second point to this one""" result = _ec_lib.ec_ws_add(self._point.get(), point._point.get()) if result: if result == 16: raise ValueError("EC points are not on the same curve") raise ValueError("Error %d while adding two EC points" % result) return self def __add__(self, point): """Return a new point, the addition of this one and another""" np = self.copy() np += point return np def __imul__(self, scalar): """Multiply this point by a scalar""" if scalar < 0: raise ValueError("Scalar multiplication is only defined for non-negative integers") sb = long_to_bytes(scalar) result = _ec_lib.ec_ws_scalar(self._point.get(), c_uint8_ptr(sb), c_size_t(len(sb)), c_ulonglong(getrandbits(64))) if result: raise ValueError("Error %d during scalar multiplication" % result) return self def __mul__(self, scalar): """Return a new point, the scalar product of this one""" np = self.copy() np *= scalar return np
class ARC4Cipher: """ARC4 cipher object. Do not create it directly. Use :func:`Crypto.Cipher.ARC4.new` instead. """ def __init__(self, key, *args, **kwargs): """Initialize an ARC4 cipher object See also `new()` at the module level.""" if len(args) > 0: ndrop = args[0] args = args[1:] else: ndrop = kwargs.pop('drop', 0) if len(key) not in key_size: raise ValueError("Incorrect ARC4 key length (%d bytes)" % len(key)) self._state = VoidPointer() result = _raw_arc4_lib.ARC4_stream_init(c_uint8_ptr(key), c_size_t(len(key)), self._state.address_of()) if result != 0: raise ValueError("Error %d while creating the ARC4 cipher" % result) self._state = SmartPointer(self._state.get(), _raw_arc4_lib.ARC4_stream_destroy) if ndrop > 0: # This is OK even if the cipher is used for decryption, # since encrypt and decrypt are actually the same thing # with ARC4. self.encrypt(b('\x00') * ndrop) self.block_size = 1 self.key_size = len(key) def encrypt(self, plaintext): """Encrypt a piece of data. :param plaintext: The data to encrypt, of any size. :type plaintext: byte string :returns: the encrypted byte string, of equal length as the plaintext. """ ciphertext = create_string_buffer(len(plaintext)) result = _raw_arc4_lib.ARC4_stream_encrypt(self._state.get(), c_uint8_ptr(plaintext), ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with RC4" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt a piece of data. :param ciphertext: The data to decrypt, of any size. :type ciphertext: byte string :returns: the decrypted byte string, of equal length as the ciphertext. """ try: return self.encrypt(ciphertext) except ValueError, e: raise ValueError(str(e).replace("enc", "dec"))
class ChaCha20Cipher: """ChaCha20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 or 12 :vartype nonce: byte string """ block_size = 1 def __init__(self, key, nonce): """Initialize a ChaCha20 cipher object See also `new()` at the module level.""" self.nonce = _copy_bytes(None, None, nonce) self._next = ( self.encrypt, self.decrypt ) self._state = VoidPointer() result = _raw_chacha20_lib.chacha20_init( self._state.address_of(), c_uint8_ptr(key), c_size_t(len(key)), self.nonce, c_size_t(len(nonce))) if result: raise ValueError("Error %d instantiating a ChaCha20 cipher") self._state = SmartPointer(self._state.get(), _raw_chacha20_lib.chacha20_destroy) def encrypt(self, plaintext): """Encrypt a piece of data. :param plaintext: The data to encrypt, of any size. :type plaintext: bytes, bytearray, memoryview :returns: the encrypted byte string, of equal length as the plaintext. """ if self.encrypt not in self._next: raise TypeError("Cipher object can only be used for decryption") self._next = ( self.encrypt, ) return self._encrypt(plaintext) def _encrypt(self, plaintext): """Encrypt without FSM checks""" ciphertext = create_string_buffer(len(plaintext)) result = _raw_chacha20_lib.chacha20_encrypt( self._state.get(), c_uint8_ptr(plaintext), ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with ChaCha20" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt a piece of data. :param ciphertext: The data to decrypt, of any size. :type ciphertext: bytes, bytearray, memoryview :returns: the decrypted byte string, of equal length as the ciphertext. """ if self.decrypt not in self._next: raise TypeError("Cipher object can only be used for encryption") self._next = ( self.decrypt, ) try: return self._encrypt(ciphertext) except ValueError as e: raise ValueError(str(e).replace("enc", "dec")) def seek(self, position): """Seek to a certain position in the key stream. :param integer position: The absolute position within the key stream, in bytes. """ position, offset = divmod(position, 64) block_low = position & 0xFFFFFFFF block_high = position >> 32 result = _raw_chacha20_lib.chacha20_seek( self._state.get(), c_ulong(block_high), c_ulong(block_low), offset ) if result: raise ValueError("Error %d while seeking with ChaCha20" % result)
class BLAKE2s_Hash(object): """A BLAKE2s hash object. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string :ivar block_size: the size in bytes of the internal message block, input to the compression function :vartype block_size: integer :ivar digest_size: the size in bytes of the resulting hash :vartype digest_size: integer """ # The internal block size of the hash algorithm in bytes. block_size = 32 def __init__(self, data, key, digest_bytes, update_after_digest): # The size of the resulting hash in bytes. self.digest_size = digest_bytes self._update_after_digest = update_after_digest self._digest_done = False # See https://tools.ietf.org/html/rfc7693 if digest_bytes in (16, 20, 28, 32) and not key: self.oid = "1.3.6.1.4.1.1722.12.2.2." + str(digest_bytes) state = VoidPointer() result = _raw_blake2s_lib.blake2s_init(state.address_of(), c_uint8_ptr(key), c_size_t(len(key)), c_size_t(digest_bytes)) if result: raise ValueError("Error %d while instantiating BLAKE2s" % result) self._state = SmartPointer(state.get(), _raw_blake2s_lib.blake2s_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string/byte array/memoryview): The next chunk of the message being hashed. """ if self._digest_done and not self._update_after_digest: raise TypeError( "You can only call 'digest' or 'hexdigest' on this object") result = _raw_blake2s_lib.blake2s_update(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while hashing BLAKE2s data" % result) return self def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Binary form. :rtype: byte string """ bfr = create_string_buffer(32) result = _raw_blake2s_lib.blake2s_digest(self._state.get(), bfr) if result: raise ValueError("Error %d while creating BLAKE2s digest" % result) self._digest_done = True return get_raw_buffer(bfr)[:self.digest_size] def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Hexadecimal encoded. :rtype: string """ return "".join(["%02x" % bord(x) for x in tuple(self.digest())]) def verify(self, mac_tag): """Verify that a given **binary** MAC (computed by another party) is valid. Args: mac_tag (byte string/byte array/memoryview): the expected MAC of the message. Raises: ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ secret = get_random_bytes(16) mac1 = new(digest_bits=160, key=secret, data=mac_tag) mac2 = new(digest_bits=160, key=secret, data=self.digest()) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed") def hexverify(self, hex_mac_tag): """Verify that a given **printable** MAC (computed by another party) is valid. Args: hex_mac_tag (string): the expected MAC of the message, as a hexadecimal string. Raises: ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ self.verify(unhexlify(tobytes(hex_mac_tag))) def new(self, **kwargs): """Return a new instance of a BLAKE2s hash object. See :func:`new`. """ if "digest_bytes" not in kwargs and "digest_bits" not in kwargs: kwargs["digest_bytes"] = self.digest_size return new(**kwargs)
class Salsa20Cipher: """Salsa20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string """ def __init__(self, key, nonce): """Initialize a Salsa20 cipher object See also `new()` at the module level.""" if len(key) not in key_size: raise ValueError("Incorrect key length for Salsa20 (%d bytes)" % len(key)) if len(nonce) != 8: raise ValueError("Incorrect nonce length for Salsa20 (%d bytes)" % len(nonce)) self.nonce = nonce expect_byte_string(key) expect_byte_string(nonce) self._state = VoidPointer() result = _raw_salsa20_lib.Salsa20_stream_init( key, c_size_t(len(key)), nonce, c_size_t(len(nonce)), self._state.address_of()) if result: raise ValueError("Error %d instantiating a Salsa20 cipher") self._state = SmartPointer(self._state.get(), _raw_salsa20_lib.Salsa20_stream_destroy) self.block_size = 1 self.key_size = len(key) def encrypt(self, plaintext): """Encrypt a piece of data. :param plaintext: The data to encrypt, of any size. :type plaintext: byte string :returns: the encrypted byte string, of equal length as the plaintext. """ expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = _raw_salsa20_lib.Salsa20_stream_encrypt( self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with Salsa20" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt a piece of data. :param ciphertext: The data to decrypt, of any size. :type ciphertext: byte string :returns: the decrypted byte string, of equal length as the ciphertext. """ try: return self.encrypt(ciphertext) except ValueError, e: raise ValueError(str(e).replace("enc", "dec"))
class SHA3_384_Hash(object): """A SHA3-384 hash object. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string :ivar digest_size: the size in bytes of the resulting hash :vartype digest_size: integer """ # The size of the resulting hash in bytes. digest_size = 48 # ASN.1 Object ID oid = "2.16.840.1.101.3.4.2.9" def __init__(self, data, update_after_digest): self._update_after_digest = update_after_digest self._digest_done = False state = VoidPointer() result = _raw_keccak_lib.keccak_init(state.address_of(), c_size_t(self.digest_size * 2), 0x06) if result: raise ValueError("Error %d while instantiating SHA-3/384" % result) self._state = SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string): The next chunk of the message being hashed. """ if self._digest_done and not self._update_after_digest: raise TypeError("You can only call 'digest' or 'hexdigest' on this object") expect_byte_string(data) result = _raw_keccak_lib.keccak_absorb(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while updating SHA-3/384" % result) return self def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Binary form. :rtype: byte string """ self._digest_done = True bfr = create_string_buffer(self.digest_size) result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr, c_size_t(self.digest_size)) if result: raise ValueError("Error %d while instantiating SHA-3/384" % result) self._digest_value = get_raw_buffer(bfr) return self._digest_value def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Hexadecimal encoded. :rtype: string """ return "".join(["%02x" % bord(x) for x in self.digest()]) def new(self): """Create a fresh SHA3-384 hash object.""" return type(self)(None, self._update_after_digest)
class ARC4Cipher: """ARC4 cipher object. Do not create it directly. Use :func:`Crypto.Cipher.ARC4.new` instead. """ def __init__(self, key, *args, **kwargs): """Initialize an ARC4 cipher object See also `new()` at the module level.""" if len(args) > 0: ndrop = args[0] args = args[1:] else: ndrop = kwargs.pop('drop', 0) if len(key) not in key_size: raise ValueError("Incorrect ARC4 key length (%d bytes)" % len(key)) expect_byte_string(key) self._state = VoidPointer() result = _raw_arc4_lib.ARC4_stream_init(key, c_size_t(len(key)), self._state.address_of()) if result != 0: raise ValueError("Error %d while creating the ARC4 cipher" % result) self._state = SmartPointer(self._state.get(), _raw_arc4_lib.ARC4_stream_destroy) if ndrop > 0: # This is OK even if the cipher is used for decryption, # since encrypt and decrypt are actually the same thing # with ARC4. self.encrypt(b('\x00') * ndrop) self.block_size = 1 self.key_size = len(key) def encrypt(self, plaintext): """Encrypt a piece of data. :param plaintext: The data to encrypt, of any size. :type plaintext: byte string :returns: the encrypted byte string, of equal length as the plaintext. """ expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = _raw_arc4_lib.ARC4_stream_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with RC4" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt a piece of data. :param ciphertext: The data to decrypt, of any size. :type ciphertext: byte string :returns: the decrypted byte string, of equal length as the ciphertext. """ try: return self.encrypt(ciphertext) except ValueError, e: raise ValueError(str(e).replace("enc", "dec"))
class EccPoint(object): """A class to abstract a point over an Elliptic Curve. The class support special methods for: * Adding two points: ``R = S + T`` * In-place addition: ``S += T`` * Negating a point: ``R = -T`` * Comparing two points: ``if S == T: ...`` * Multiplying a point by a scalar: ``R = S*k`` * In-place multiplication by a scalar: ``T *= k`` :ivar x: The affine X-coordinate of the ECC point :vartype x: integer :ivar y: The affine Y-coordinate of the ECC point :vartype y: integer :ivar xy: The tuple with X- and Y- coordinates """ def __init__(self, x, y, curve="p256"): try: self._curve = _curves[curve] except KeyError: raise ValueError("Unknown curve name %s" % str(curve)) self._curve_name = curve modulus_bytes = self.size_in_bytes() context = self._curve.context xb = long_to_bytes(x, modulus_bytes) yb = long_to_bytes(y, modulus_bytes) if len(xb) != modulus_bytes or len(yb) != modulus_bytes: raise ValueError("Incorrect coordinate length") self._point = VoidPointer() result = _ec_lib.ec_ws_new_point(self._point.address_of(), c_uint8_ptr(xb), c_uint8_ptr(yb), c_size_t(modulus_bytes), context.get()) if result: if result == 15: raise ValueError("The EC point does not belong to the curve") raise ValueError("Error %d while instantiating an EC point" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the EC point self._point = SmartPointer(self._point.get(), _ec_lib.ec_free_point) def set(self, point): self._point = VoidPointer() result = _ec_lib.ec_ws_clone(self._point.address_of(), point._point.get()) if result: raise ValueError("Error %d while cloning an EC point" % result) self._point = SmartPointer(self._point.get(), _ec_lib.ec_free_point) return self def __eq__(self, point): return 0 == _ec_lib.ec_ws_cmp(self._point.get(), point._point.get()) def __neg__(self): np = self.copy() result = _ec_lib.ec_ws_neg(np._point.get()) if result: raise ValueError("Error %d while inverting an EC point" % result) return np def copy(self): """Return a copy of this point.""" x, y = self.xy np = EccPoint(x, y, self._curve_name) return np def is_point_at_infinity(self): """``True`` if this is the point-at-infinity.""" return self.xy == (0, 0) def point_at_infinity(self): """Return the point-at-infinity for the curve this point is on.""" return EccPoint(0, 0, self._curve_name) @property def x(self): return self.xy[0] @property def y(self): return self.xy[1] @property def xy(self): modulus_bytes = self.size_in_bytes() xb = bytearray(modulus_bytes) yb = bytearray(modulus_bytes) result = _ec_lib.ec_ws_get_xy(c_uint8_ptr(xb), c_uint8_ptr(yb), c_size_t(modulus_bytes), self._point.get()) if result: raise ValueError("Error %d while encoding an EC point" % result) return (Integer(bytes_to_long(xb)), Integer(bytes_to_long(yb))) def size_in_bytes(self): """Size of each coordinate, in bytes.""" return (self.size_in_bits() + 7) // 8 def size_in_bits(self): """Size of each coordinate, in bits.""" return self._curve.modulus_bits def double(self): """Double this point (in-place operation). :Return: :class:`EccPoint` : this same object (to enable chaining) """ result = _ec_lib.ec_ws_double(self._point.get()) if result: raise ValueError("Error %d while doubling an EC point" % result) return self def __iadd__(self, point): """Add a second point to this one""" result = _ec_lib.ec_ws_add(self._point.get(), point._point.get()) if result: if result == 16: raise ValueError("EC points are not on the same curve") raise ValueError("Error %d while adding two EC points" % result) return self def __add__(self, point): """Return a new point, the addition of this one and another""" np = self.copy() np += point return np def __imul__(self, scalar): """Multiply this point by a scalar""" if scalar < 0: raise ValueError( "Scalar multiplication is only defined for non-negative integers" ) sb = long_to_bytes(scalar) result = _ec_lib.ec_ws_scalar(self._point.get(), c_uint8_ptr(sb), c_size_t(len(sb)), c_ulonglong(getrandbits(64))) if result: raise ValueError("Error %d during scalar multiplication" % result) return self def __mul__(self, scalar): """Return a new point, the scalar product of this one""" np = self.copy() np *= scalar return np def __rmul__(self, left_hand): return self.__mul__(left_hand)
class CbcMode(object): """*Cipher-Block Chaining (CBC)*. Each of the ciphertext blocks depends on the current and all previous plaintext blocks. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.2 . .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf """ def __init__(self, block_cipher, iv): """Create a new block cipher, configured in CBC mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : byte string The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be unpredictable**. Ideally it is picked randomly. Reusing the *IV* for encryptions performed with the same key compromises confidentiality. """ expect_byte_string(iv) self._state = VoidPointer() result = raw_cbc_lib.CBC_start_operation(block_cipher.get(), iv, c_size_t(len(iv)), self._state.address_of()) if result: raise ValueError("Error %d while instatiating the CBC mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_cbc_lib.CBC_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() #: The block size of the underlying cipher, in bytes. self.block_size = len(iv) #: The Initialization Vector originally used to create the object. #: The value does not change. self.IV = iv def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) That also means that you cannot reuse an object for encrypting or decrypting other data with the same key. This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. Its lenght must be multiple of the cipher block size. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = raw_cbc_lib.CBC_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting in CBC mode" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. Its length must be multiple of the cipher block size. :Return: the decrypted data (byte string). """ expect_byte_string(ciphertext) plaintext = create_string_buffer(len(ciphertext)) result = raw_cbc_lib.CBC_decrypt(self._state.get(), ciphertext, plaintext, c_size_t(len(ciphertext))) if result: raise ValueError("Error %d while decrypting in CBC mode" % result) return get_raw_buffer(plaintext)
class ChaCha20Cipher: """ChaCha20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string """ block_size = 1 def __init__(self, key, nonce): """Initialize a ChaCha20 cipher object See also `new()` at the module level.""" self.nonce = _copy_bytes(None, None, nonce) self._next = (self.encrypt, self.decrypt) self._state = VoidPointer() result = _raw_chacha20_lib.chacha20_init(self._state.address_of(), c_uint8_ptr(key), c_size_t(len(key)), self.nonce, c_size_t(len(nonce))) if result: raise ValueError("Error %d instantiating a ChaCha20 cipher") self._state = SmartPointer(self._state.get(), _raw_chacha20_lib.chacha20_destroy) def encrypt(self, plaintext): """Encrypt a piece of data. :param plaintext: The data to encrypt, of any size. :type plaintext: bytes, bytearray, memoryview :returns: the encrypted byte string, of equal length as the plaintext. """ if self.encrypt not in self._next: raise TypeError("Cipher object can only be used for decryption") self._next = (self.encrypt, ) return self._encrypt(plaintext) def _encrypt(self, plaintext): """Encrypt without FSM checks""" ciphertext = create_string_buffer(len(plaintext)) result = _raw_chacha20_lib.chacha20_encrypt(self._state.get(), c_uint8_ptr(plaintext), ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with ChaCha20" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt a piece of data. :param ciphertext: The data to decrypt, of any size. :type ciphertext: bytes, bytearray, memoryview :returns: the decrypted byte string, of equal length as the ciphertext. """ if self.decrypt not in self._next: raise TypeError("Cipher object can only be used for encryption") self._next = (self.decrypt, ) try: return self._encrypt(ciphertext) except ValueError, e: raise ValueError(str(e).replace("enc", "dec"))
class Salsa20Cipher: """Salsa20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string """ def __init__(self, key, nonce): """Initialize a Salsa20 cipher object See also `new()` at the module level.""" if len(key) not in key_size: raise ValueError("Incorrect key length for Salsa20 (%d bytes)" % len(key)) if len(nonce) != 8: raise ValueError("Incorrect nonce length for Salsa20 (%d bytes)" % len(nonce)) self.nonce = _copy_bytes(None, None, nonce) self._state = VoidPointer() result = _raw_salsa20_lib.Salsa20_stream_init( c_uint8_ptr(key), c_size_t(len(key)), c_uint8_ptr(nonce), c_size_t(len(nonce)), self._state.address_of()) if result: raise ValueError("Error %d instantiating a Salsa20 cipher") self._state = SmartPointer(self._state.get(), _raw_salsa20_lib.Salsa20_stream_destroy) self.block_size = 1 self.key_size = len(key) def encrypt(self, plaintext): """Encrypt a piece of data. :param plaintext: The data to encrypt, of any size. :type plaintext: bytes/bytearray/memoryview :returns: the encrypted byte string, of equal length as the plaintext. """ ciphertext = create_string_buffer(len(plaintext)) result = _raw_salsa20_lib.Salsa20_stream_encrypt( self._state.get(), c_uint8_ptr(plaintext), ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with Salsa20" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt a piece of data. :param ciphertext: The data to decrypt, of any size. :type ciphertext: bytes/bytearray/memoryview :returns: the decrypted byte string, of equal length as the ciphertext. """ try: return self.encrypt(ciphertext) except ValueError, e: raise ValueError(str(e).replace("enc", "dec"))
class CtrMode(object): """*CounTeR (CTR)* mode. This mode is very similar to ECB, in that encryption of one block is done independently of all other blocks. Unlike ECB, the block *position* contributes to the encryption and no information leaks about symbol frequency. Each message block is associated to a *counter* which must be unique across all messages that get encrypted with the same key (not just within the same message). The counter is as big as the block size. Counters can be generated in several ways. The most straightword one is to choose an *initial counter block* (which can be made public, similarly to the *IV* for the other modes) and increment its lowest **m** bits by one (modulo *2^m*) for each block. In most cases, **m** is chosen to be half the block size. See `NIST SP800-38A`_, Section 6.5 (for the mode) and Appendix B (for how to manage the *initial counter block*). .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf """ def __init__(self, block_cipher, initial_counter_block, prefix_len, counter_len, little_endian): """Create a new block cipher, configured in CTR mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. initial_counter_block : byte string The initial plaintext to use to generate the key stream. It is as large as the cipher block, and it embeds the initial value of the counter. This value must not be reused. It shall contain a nonce or a random component. Reusing the *initial counter block* for encryptions performed with the same key compromises confidentiality. prefix_len : integer The amount of bytes at the beginning of the counter block that never change. counter_len : integer The length in bytes of the counter embedded in the counter block. little_endian : boolean True if the counter in the counter block is an integer encoded in little endian mode. If False, it is big endian. """ if len(initial_counter_block) == prefix_len + counter_len: #: Nonce; not available if there is a fixed suffix self.nonce = initial_counter_block[:prefix_len] expect_byte_string(initial_counter_block) self._state = VoidPointer() result = raw_ctr_lib.CTR_start_operation(block_cipher.get(), initial_counter_block, c_size_t(len(initial_counter_block)), c_size_t(prefix_len), counter_len, little_endian, self._state.address_of()) if result: raise ValueError("Error %X while instatiating the CTR mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_ctr_lib.CTR_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() #: The block size of the underlying cipher, in bytes. self.block_size = len(initial_counter_block) self._next = [self.encrypt, self.decrypt] def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") self._next = [self.encrypt] expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = raw_ctr_lib.CTR_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: if result == 0x60002: raise OverflowError("The counter has wrapped around in" " CTR mode") raise ValueError("Error %X while encrypting in CTR mode" % result) return get_raw_buffer(ciphertext) def decrypt(self, ciphertext): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any length. :Return: the decrypted data (byte string). """ if self.decrypt not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") self._next = [self.decrypt] expect_byte_string(ciphertext) plaintext = create_string_buffer(len(ciphertext)) result = raw_ctr_lib.CTR_decrypt(self._state.get(), ciphertext, plaintext, c_size_t(len(ciphertext))) if result: if result == 0x60002: raise OverflowError("The counter has wrapped around in" " CTR mode") raise ValueError("Error %X while decrypting in CTR mode" % result) return get_raw_buffer(plaintext)
class BLAKE2s_Hash(object): """Class that implements a BLAKE2s hash """ #: The internal block size of the hash algorithm in bytes. block_size = 32 def __init__(self, data, key, digest_bytes): """ Initialize a BLAKE2s hash object. """ #: The size of the resulting hash in bytes. self.digest_size = digest_bytes # See https://tools.ietf.org/html/draft-saarinen-blake2-02 if digest_bytes in (16, 20, 28, 32) and not key: self.oid = "1.3.6.1.4.1.1722.12.2.2." + str(digest_bytes) expect_byte_string(key) state = VoidPointer() result = _raw_blake2s_lib.blake2s_init(state.address_of(), key, c_size_t(len(key)), c_size_t(digest_bytes) ) if result: raise ValueError("Error %d while instantiating BLAKE2s" % result) self._state = SmartPointer(state.get(), _raw_blake2s_lib.blake2s_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Parameters: data : byte string The next chunk of the message being hashed. """ expect_byte_string(data) result = _raw_blake2s_lib.blake2s_update(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while hashing BLAKE2s data" % result) return self def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. This method does not change the state of the hash object. You can continue updating the object after calling this function. :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes. """ bfr = create_string_buffer(32) result = _raw_blake2s_lib.blake2s_digest(self._state.get(), bfr) if result: raise ValueError("Error %d while creating BLAKE2s digest" % result) return get_raw_buffer(bfr)[:self.digest_size] def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. This method does not change the state of the hash object. :Return: A string of 2* `digest_size` characters. It contains only hexadecimal ASCII digits. """ return "".join(["%02x" % bord(x) for x in tuple(self.digest())]) def copy(self): """Return a copy ("clone") of the hash object. The copy will have the same internal state as the original hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. :Return: A hash object of the same type """ clone = BLAKE2s_Hash(None, b(""), self.digest_size) result = _raw_blake2s_lib.blake2s_copy(self._state.get(), clone._state.get()) if result: raise ValueError("Error %d while copying BLAKE2s" % result) return clone def verify(self, mac_tag): """Verify that a given **binary** MAC (computed by another party) is valid. :Parameters: mac_tag : byte string The expected MAC of the message. :Raises ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ secret = get_random_bytes(16) mac1 = new(digest_bits=160, key=secret, data=mac_tag) mac2 = new(digest_bits=160, key=secret, data=self.digest()) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed") def hexverify(self, hex_mac_tag): """Verify that a given **printable** MAC (computed by another party) is valid. :Parameters: hex_mac_tag : string The expected MAC of the message, as a hexadecimal string. :Raises ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ self.verify(unhexlify(tobytes(hex_mac_tag))) def new(self, **kwargs): """Return a new instance of a BLAKE2s hash object.""" if "digest_bytes" not in kwargs and "digest_bits" not in kwargs: kwargs["digest_bytes"] = self.digest_size return new(**kwargs)