pyca / cryptography

cryptography is a package designed to expose cryptographic primitives and recipes to Python developers.
https://cryptography.io
Other
6.56k stars 1.51k forks source link

AES XTS Mode questions (key division & tweak encryption / galois multiplication) #9754

Closed mewmix closed 11 months ago

mewmix commented 11 months ago

Hi all,

Thank you for an outstanding library.

I've been examining the XTS mode implementation for AES and I have some questions and clarifications regarding the key division and the tweak value.

When I deal with XTS mode, I typically divide the AES key into two halves. The first half is used for data encryption and the second half for the tweak value. Here's a simplified version of what I typically do:

# Convert the hex string to bytes
aes_key = bytes.fromhex(hex_value)
half_length = len(aes_key) // 2
first_half = aes_key[:half_length]
last_half = aes_key[half_length:]

For the tweak encryption, I then use the second half of the AES key in ECB mode:

tweak_cipher = Cipher(algorithms.AES(last_half), modes.ECB())
tweak_encryptor = tweak_cipher.encryptor()

My questions are:

  1. Does the cryptography library's XTS mode implementation also divide the AES key in half as demonstrated above?

  2. For the tweak value, is it multiplied by the Galois multiplication field, GF(2^128), as described in the XTS specification? Specifically, is the operation similar to the one demonstrated below?

def galois_mul_x(tweak):
    """Performs Galois multiplication of the tweak value by x in GF(2^128)"""
    high_bit_set = tweak[15] & 0x80  # Check the highest bit for little-endian
    tweak = int.from_bytes(tweak, byteorder='little')
    tweak = (tweak << 1)  # Left shift to multiply by x
    if high_bit_set:
        # If the highest bit was set, XOR with 0x87, adjusted for little-endian format
        tweak ^= 0x87
    return tweak.to_bytes(16, byteorder='little')

If the library does things differently, could you please clarify how the AES key is used in XTS mode and how the tweak multiplication is performed?

Thank you!

reaperhulk commented 11 months ago

We obtain our implementation from OpenSSL so you can see exactly how it is implemented in their source code. We also run the NIST CAVP XTS vectors in our test suite (see test_aes.py).

mewmix commented 11 months ago

Thank you!