Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion mega/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,31 @@

def a32_to_str(a):
return struct.pack('>%dI' % len(a), *a)
# > , my guess is that choosing the big-endian and not letting it be native is aiming at making the code independent of the platform, in other words independent of the endianness of the platform: to be checked with @juanriaza https://docs.python.org/3.6/library/struct.html?highlight=struct#byte-order-size-and-alignment
# https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists just to explain the use of '*' in front of 'a'


def aes_cbc_encrypt(data, key):
encryptor = AES.new(key, AES.MODE_CBC, '\0' * 16)
# choice of CBC mode is justified on https://mega.nz/doc 12.10 "A chunk MAC is computed as follows (this is essentially CBC-MAC, which was chosen instead of the more efficient OCB over intellectual property concerns)"
# the last argument, the initiatlisation vector is optional http://pythonhosted.org/pycrypto/Crypto.Cipher.AES-module.html#new
return encryptor.encrypt(data)
# length data must be a multiple of 16 http://pythonhosted.org/pycrypto/Crypto.Cipher.blockalgo.BlockAlgo-class.html#encrypt


def aes_cbc_encrypt_a32(data, key):
return str_to_a32(aes_cbc_encrypt(a32_to_str(data), a32_to_str(key)))


def str_to_a32(b):
if len(b) % 4: # Add padding, we need a string with a length multiple of 4
if len(b) % 4: # Add padding, we need a string with a length multiple of 4 because the size of an unsigned integer as indicated in the call of the unpack method below is 4 bytes https://docs.python.org/3.6/library/struct.html#format-characters
b += '\0' * (4 - len(b) % 4)
return struct.unpack('>%dI' % (len(b) / 4), b)


def mpi2int(s):
return int(binascii.hexlify(s[2:]), 16)
# returns the string s, truncated of its 2 first caracters as an integer https://docs.python.org/3.6/library/functions.html?highlight=int#int


def aes_cbc_decrypt(data, key):
Expand Down