# Implementing 5 modes of operation with a hash function

Is it possible to implement any of the 5 modes of operation (ECB, CBC, OFB, CFB, CTR) with a hash function?

The modes you are referencing are specifically modes of operations for block ciphers, and therefore are not directly applicable to hash functions. Block cipher operations take 2 inputs, the key and a block-sized input value, and output a block-sized keyed permutation of the input. Hash functions take a variable length input, and output a fixed length value.

However, the way 3 of them work can be applied hash functions, by using HMAC or NMAC to turn the hash into a keyed pseudorandom function.

### CTR:

In the block cipher we have:
$$C_i = P_i \oplus Enc_k(Nonce \ || \ Ctr_i)$$

Applying to the hash we have:
$$C_i = P_i \oplus HMAC_k(Nonce \ || \ Ctr_i)$$

### OFB:

In the block cipher we have:
$$O_0 = IV$$
$$O_i = Enc_k(O_{i-1})$$
$$C_i = P_i \oplus O_i$$

Applying to the hash we have:
$$O_0 = IV$$
$$O_i = HMAC_k(O_{i-1})$$
$$C_i = P_i \oplus O_i$$

### CFB:

In the block cipher we have:
$$C_0 = IV$$
$$C_i = P_i \oplus Enc_k(C_{i-1})$$

Applying to the hash we have:
$$C_0 = IV$$
$$C_i = P_i \oplus HMAC_k(C_{i-1})$$

Because of the way these modes work, by not requiring the decryption operation, a keyed one-way function can perform the same function, which is the cryptographic transformation of the input to XOR against the plaintext and generate the ciphertext. They make these schemes stream ciphers.

Because the output size of secure hash functions (SHA256 or SHA512) is generally larger than the block size of a block cipher (AES), using these hash functions may be able to encode a larger amount of plaintext before running into the problems these modes may experience with block ciphers. The additional flexibility of a variable length input also allows the hash functions to have larger nonces/IVs.

However since they are not permutations, the security proofs that apply to block ciphers may not apply to hash functions when used in these modes. Additional security may be provided by truncating the output of the hash function before encrypting the plaintext, but still feeding the full output back in the case of OFB and CFB.

From a performance perspective, most hash functions are slower than most block ciphers, by a wide margin. Using HMAC also requires additional hash operations to generate the secret initial values, however an implementation can do these once per plaintext if the IV and input length of a hash function can changed arbitrarily.

• For completeness' sake: most block cipher mode proofs assume the cipher is PRP and thus PRF up to the birthday bound. Hash functions are not PRP and not required to be PRF either though the ones we use seem to be. – otus Sep 18 '15 at 10:57