How use python download file from mega

0

How can I download file from mega, i had tried to fix mega.py (because its for python2, 3 is not work), but it still not work, can someone tell me how to fix it or is there other way to download it?

Following codes all are feom mega.py's repo, and i fix its error, but still can't work, it will report

Traceback (most recent call last):
  File "mega.py", line 90, in <module>
    Mega().from_ephemeral()
  File "mega.py", line 18, in from_ephemeral
    inst.login_ephemeral()
  File "mega.py", line 51, in login_ephemeral
    self._login_common(res, random_password_key)
  File "mega.py", line 55, in _login_common
    raise MegaIncorrectPasswordExcetion("Incorrect e-mail and/or password.")
exceptions.MegaIncorrectPasswordExcetion: Incorrect e-mail and/or password.

mega.py

import json
import random
import base64
import requests

from crypto import encrypt_key
from utitls import a32_to_str, a32_to_base64, base64urlencode, base64_to_a32
from exceptions import MegaRequestException, MegaIncorrectPasswordExcetion

class Mega:
    def __init__(self):
        self.seqno = random.randint(0, 0xFFFFFFFF)
        self.sid = None

    @classmethod
    def from_ephemeral(cls):
        inst = cls()
        inst.login_ephemeral()
        return inst

    def api_req(self, data):
        print(data)
        params = {'id': self.seqno}
        self.seqno += 1
        if self.sid:
            params.update({'sid': self.sid})
        data = json.dumps([data])
        req = requests.post(
            'https://g.api.mega.co.nz/cs', params=params, data=data)
        json_data = req.json()
        if isinstance(json_data, int):
            raise MegaRequestException(json_data)
        return json_data[0]

    def login_ephemeral(self):
        random_master_key = [random.randint(0, 0xFFFFFFFF)] * 4
        random_password_key = [random.randint(0, 0xFFFFFFFF)] * 4
        random_session_self_challenge = [random.randint(0, 0xFFFFFFFF)] * 4
        user_handle = self.api_req({
            'a':
            'up',
            'k':
            base64.encodebytes(a32_to_base64(encrypt_key(random_master_key, random_password_key))).decode('ascii').replace('\n', ''),
            'ts':
            base64.encodebytes(base64urlencode(
                a32_to_str(random_session_self_challenge) + a32_to_str(
                    encrypt_key(random_session_self_challenge,
                                random_master_key)))).decode('ascii').replace('\n', '')
        })
        res = self.api_req({'a': 'us', 'user': user_handle})
        self._login_common(res, random_password_key)

    def _login_common(self, res, password):
        if res in (-2, -9):
            raise MegaIncorrectPasswordExcetion("Incorrect e-mail and/or password.")

        enc_master_key = base64_to_a32(res['k'])
        self.master_key = decrypt_key(enc_master_key, password)
        if 'tsid' in res:
            tsid = base64urldecode(res['tsid'])
            key_encrypted = a32_to_str(
                encrypt_key(str_to_a32(tsid[:16]), self.master_key))
            if key_encrypted == tsid[-16:]:
                self.sid = res['tsid']
        elif 'csid' in res:
            enc_rsa_priv_key = base64_to_a32(res['privk'])
            rsa_priv_key = decrypt_key(enc_rsa_priv_key, self.master_key)

            privk = a32_to_str(rsa_priv_key)
            self.rsa_priv_key = [0, 0, 0, 0]

            for i in xrange(4):
                l = ((ord(privk[0]) * 256 + ord(privk[1]) + 7) / 8) + 2
                self.rsa_priv_key[i] = mpi2int(privk[:l])
                privk = privk[l:]

            enc_sid = mpi2int(base64urldecode(res['csid']))
            decrypter = RSA.construct(
                (self.rsa_priv_key[0] * self.rsa_priv_key[1],
                 0,
                 self.rsa_priv_key[2],
                 self.rsa_priv_key[0],
                 self.rsa_priv_key[1]))
            sid = '%x' % decrypter.key._decrypt(enc_sid)
            sid = binascii.unhexlify('0' + sid if len(sid) % 2 else sid)
            self.sid = base64urlencode(sid[:43])


if __name__ == '__main__':
    Mega().from_ephemeral()

crypto.py

import struct
from Crypto.Cipher import AES

def a32_to_str(a):
    return struct.pack('>%dI' % len(a), *a)

def encrypt_key(a, key):
    return sum(
        (aes_cbc_encrypt_a32(a[i:i+4], key)
            for i in range(0, len(a), 4)), ())

def aes_cbc_encrypt(data, key):
    encryptor = AES.new(key, AES.MODE_CBC, b'\0' * 16)
    return encryptor.encrypt(data)

def str_to_a32(b):
    if len(b) % 4:  # Add padding, we need a string with a length multiple of 4
        b += '\0' * (4 - len(b) % 4)
    return struct.unpack('>%dI' % (len(b) / 4), b)

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

utitles.py

import base64
import struct

def base64urlencode(data):
    data = base64.b64encode(data)
    for search, replace in (('+', '-'), ('/', '_'), ('=', '')):
        data = data.replace(search, replace)
    return data

def a32_to_str(a):
    return struct.pack('>%dI' % len(a), *a)

def base64urlencode(data):
    data = base64.b64encode(data)
    for search, replace in (('+', '-'), ('/', '_'), ('=', '')):
        data = data.replace(bytes(search, encoding='utf8'), bytes(replace, encoding='utf8'))
    return data

def a32_to_base64(a):
    return base64urlencode(a32_to_str(a))


def base64_to_a32(s):
    return str_to_a32(base64urldecode(s))

exceptions.py

# -*- coding: utf-8 -*-


class MegaException(Exception):
    pass

class MegaIncorrectPasswordExcetion(MegaException):
    """
    A incorrect password or email was given.
    """

class MegaRequestException(MegaException):
    """
    There was an error in the request.
    """
    pass
python
download
asked on Stack Overflow Oct 30, 2019 by arasHi_

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0