Beispiel #1
0
def aes_encrypt_with_iv(key, iv, data):
    aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv)
    aes = pyaes.Encrypter(aes_cbc)
    e = aes.feed(data) + aes.feed()  # empty aes.feed() appends pkcs padding
    return e
Beispiel #2
0
def aes_decrypt_with_iv(key, iv, data):
    aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv)
    aes = pyaes.Decrypter(aes_cbc)
    s = aes.feed(data) + aes.feed()  # empty aes.feed() strips pkcs padding
    return s
Beispiel #3
0
def aes_encrypt_with_iv(key: bytes, iv: bytes, data: bytes) -> bytes:
    aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv)
    aes = pyaes.Encrypter(aes_cbc)
    e = aes.feed(data) + aes.feed()  # empty aes.feed() appends pkcs padding
    assert isinstance(e, bytes)
    return e
Beispiel #4
0
def aes_decrypt_with_iv(key: bytes, iv: bytes, data: bytes) -> bytes:
    aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv)
    aes = pyaes.Decrypter(aes_cbc)
    s = aes.feed(data) + aes.feed()  # empty aes.feed() strips pkcs padding
    assert isinstance(s, bytes)
    return s
Beispiel #5
0
def get_access_attrs(content, url, check=True):
    values = {}
    attrs = {}

    mw_pid = re.compile(r"partner_id:\s*(\w*),").findall(content)[0]
    p_domain_id = re.compile(r"domain_id:\s*(\w*),").findall(content)[0]

    _mw_adb = False

    video_token = re.compile(r"video_token:\s*\S?\'([0-9a-f]*)\S?\'").findall(
        content)[0]
    ref = re.compile('ref: \'(.+?)\'').findall(content)[0]

    js_path = re.compile(r'script src=\"(.*)\"').findall(content)[0]

    headers = {
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
    }
    if "://" in js_path:
        request = urllib2.Request(js_path, "", headers)
    else:
        request = urllib2.Request("http://" + url.split('/')[2] + js_path, "",
                                  headers)
    request.get_method = lambda: 'GET'
    js_page = urllib2.urlopen(request).read()

    t = EncryptedData()
    t.a = mw_pid
    t.b = p_domain_id
    t.c = _mw_adb
    #t.d = window_value
    t.e = video_token
    t.f = USER_AGENT

    json_string = t.to_json()

    e_value = addon.getSetting('value1')
    n_value = addon.getSetting('value2')
    encrypted = ''

    try:
        encrypt_mode = pyaes.AESModeOfOperationCBC(binascii.a2b_hex(e_value),
                                                   binascii.a2b_hex(n_value))
        encrypter = pyaes.Encrypter(encrypt_mode)
        encrypted += encrypter.feed(json_string)
        encrypted += encrypter.feed()
    except:
        pass

    host = re.compile(r"host: \'(.+?)\'").findall(content)[0]
    attrs['purl'] = "http://" + host + "/vs"
    values["q"] = base64.standard_b64encode(encrypted)
    values["ref"] = ref

    #check
    if (check == True) and vurl:
        response = ''
        try:
            opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
            opener.addheaders = [("User-Agent", USER_AGENT)]
            request = urllib2.Request(attrs["purl"], urllib.urlencode(values),
                                      {})
            connection = opener.open(request)
            response = connection.read()
        except:
            values, attrs = reload_values2(content, url)
        if response and (not ("mp4" in response)):
            values, attrs = reload_values2(content, url)

    xbmc.log("param=" + repr(values) + " " + repr(attrs))
    return values, attrs
 def decrypt_pyaes(self, payload):
     aes = pyaes.AESModeOfOperationCBC(self.key, iv=bytes(self.iv))
     return b"".join([aes.decrypt(bytes(payload[i:i + 16])) for i in range(0, len(payload), 16)])
Beispiel #7
0
# Encrypt the 1KB text file stored in the variable plaintext with the given key produced in first step:

#create a initial vector iv of 16bytes ,ALso remember CBC takes in one block size
iv = os.urandom(16)

#read the text file
with open('1kb.txt','rb') as f :
  plaintext = f.read()  
  statinfo = os.stat('1kb.txt')
  f_Size= statinfo.st_size


#perform the AES-256-CTR-Encryption using the text, key and iv. Also the text file must be 16bytes
ency_start = time.time()
encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(key, iv))

ciphertext = []
for line in open('1kb.txt'):
  ciphertext += encrypter.feed(line)
  #Make a final call to flush any remaining bytes and add padding
ciphertext +=encrypter.feed()
ency_stop = time.time()

#to check total time for encryption
encr_time = (ency_stop - ency_start)*1000000

#write the cipher text into a file
file = open('cipher.txt','w')
file.write(str(ciphertext))
Beispiel #8
0
    def prepare(self, document, overrideID=None):
        # get ready to do encryption
        if DEBUG:
            print('StandardEncryption.prepare(...) - revision %d' %
                  self.revision)
        if self.prepared:
            raise ValueError("encryption already prepared!")
        # get the unescaped string value of the document id (first array element).
        # we allow one to be passed in instead to permit reproducible tests
        # of our algorithm, but in real life overrideID will always be None
        if overrideID:
            internalID = overrideID
        else:
            externalID = document.ID()  # initialize it...
            internalID = document.signature.digest()
            #AR debugging
            if CLOBBERID:
                internalID = "xxxxxxxxxxxxxxxx"

        if DEBUG:
            print('userPassword    = %r' % self.userPassword)
            print('ownerPassword   = %r' % self.ownerPassword)
            print('internalID      = %r' % internalID)
        self.P = int(self.permissionBits() - 2**31)
        if CLOBBERPERMISSIONS: self.P = -44  # AR hack
        if DEBUG:
            print("self.P          = %s" % repr(self.P))
        if self.revision == 5:

            # Init vectro for AES cipher (should be 16 bytes null array)
            iv = b'\x00' * 16

            # Random User salts
            uvs = os_urandom(8)
            uks = os_urandom(8)

            # the main encryption key
            self.key = asBytes(os_urandom(32))

            if DEBUG:
                print("uvs      (hex)  = %s" % hexText(uvs))
                print("uks      (hex)  = %s" % hexText(uks))
                print("self.key (hex)  = %s" % hexText(self.key))

            # Calculate the sha-256 hash of the User password (U)
            md = sha256(asBytes(self.userPassword[:127]) + uvs)
            self.U = md.digest() + uvs + uks

            if DEBUG:
                print("self.U (hex)  = %s" % hexText(self.U))

            # Calculate the User encryption key (UE)
            md = sha256(asBytes(self.userPassword[:127]) + uks)

            encrypter = pyaes.Encrypter(
                pyaes.AESModeOfOperationCBC(md.digest(), iv=iv))
            self.UE = encrypter.feed(self.key)
            self.UE += encrypter.feed()

            if DEBUG:
                print("self.UE (hex)  = %s" % hexText(self.UE))

            # Random Owner salts
            ovs = os_urandom(8)
            oks = os_urandom(8)

            # Calculate the hash of the Owner password (U)
            md = sha256(asBytes(self.ownerPassword[:127]) + ovs + self.U)
            self.O = md.digest() + ovs + oks

            if DEBUG:
                print("self.O (hex)  = %s" % hexText(self.O))

            # Calculate the User encryption key (OE)
            md = sha256(asBytes(self.ownerPassword[:127]) + oks + self.U)

            encrypter = pyaes.Encrypter(
                pyaes.AESModeOfOperationCBC(md.digest(), iv=iv))
            self.OE = encrypter.feed(self.key)
            self.OE += encrypter.feed()

            if DEBUG:
                print("self.OE (hex)  = %s" % hexText(self.OE))

            # Compute permissions array
            permsarr = [
                self.P
                & 0xFF,  # store the permission value in the first 32-bits
                self.P >> 8 & 0xFF,
                self.P >> 16 & 0xFF,
                self.P >> 24 & 0xFF,
                0xFF,
                0xFF,
                0xFF,
                0xFF,
                ord(
                    'T'
                ),  # 'T' if EncryptMetaData is True (default), 'F' otherwise
                ord('a'),  # a, d, b are magic values 
                ord('d'),
                ord('b'),
                0x01,  # trailing zeros will be ignored
                0x01,
                0x01,
                0x01
            ]

            # the permission array should be enrypted in the Perms field
            encrypter = pyaes.Encrypter(
                pyaes.AESModeOfOperationCBC(self.key, iv=iv))
            self.Perms = encrypter.feed(bytes3(permsarr))
            self.Perms += encrypter.feed()

            if DEBUG:
                print("self.Perms (hex)  = %s" % hexText(self.Perms))

        elif self.revision in (2, 3):
            self.O = computeO(self.userPassword, self.ownerPassword,
                              self.revision)

            if DEBUG:
                print("self.O (as hex) = %s" % hexText(self.O))

            #print "\nself.O", self.O, repr(self.O)
            self.key = encryptionkey(self.userPassword,
                                     self.O,
                                     self.P,
                                     internalID,
                                     revision=self.revision)
            if DEBUG:
                print("self.key (hex)  = %s" % hexText(self.key))
            self.U = computeU(self.key,
                              revision=self.revision,
                              documentId=internalID)
            if DEBUG:
                print("self.U (as hex) = %s" % hexText(self.U))

        self.objnum = self.version = None
        self.prepared = 1
Beispiel #9
0
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    print('[+] Connected by ', addr)
    g = 17959
    p = 6
    b = 673
    A = int(s.recv(100).decode())
    B = (g ** b) % p
    s.send(str(B).encode())

    AESkey = (A ** b) % p

    hashed = hashlib.sha256(AESkey).digest()
    aes = pyaes.AESModeOfOperationCBC(hashed)




else:
    print("[+] Server Running ")
    print("[+] Waiting For Connection...")

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    print('[+] Connected by ', addr)

def verify_and_display(recv_dict):
def aes_encrypt(key, data, iv):
    encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(key, iv=iv))
    enc_data = encrypter.feed(data)
    enc_data += encrypter.feed()

    return enc_data
Beispiel #11
0
    def login(self, username=None, password=None):
        # Modified from:
        # https://github.com/retrospect-addon/plugin.video.retrospect/blob/master/channels/channel.se/sbs/chn_sbs.py

        # Local import to not slow down any other stuff
        import binascii
        try:
            # If running on Leia
            import pyaes
        except:
            # If running on Pre-Leia
            from resources.lib import pyaes
        import random

        now = int(time.time())
        b64_now = binascii.b2a_base64(str(now).encode()).decode().strip()

        user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " \
                     "(KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36"
        window_id = "{}|{}".format(
            binascii.hexlify(os.urandom(16)).decode(),
            binascii.hexlify(os.urandom(16)).decode())

        fe = [
            "DNT:unknown", "L:en-US", "D:24", "PR:1", "S:1920,975",
            "AS:1920,935", "TO:-120", "SS:true", "LS:true", "IDB:true",
            "B:false", "ODB:true", "CPUC:unknown", "PK:Win32", "CFP:990181251",
            "FR:false", "FOS:false", "FB:false", "JSF:Arial",
            "P:Chrome PDF Plugin", "T:0,false,false", "H:4", "SWF:false"
        ]
        fs_murmur_hash = '48bf49e1796939175b0406859d00baec'

        data = [
            {
                "key": "api_type",
                "value": "js"
            },
            {
                "key": "p",
                "value": 1
            },  # constant
            {
                "key": "f",
                "value": self.device_id
            },  # browser instance ID
            {
                "key": "n",
                "value": b64_now
            },  # base64 encoding of time.now()
            {
                "key": "wh",
                "value": window_id
            },  # WindowHandle ID
            {
                "key": "fe",
                "value": fe
            },  # browser properties
            {
                "key": "ife_hash",
                "value": fs_murmur_hash
            },  # hash of browser properties
            {
                "key": "cs",
                "value": 1
            },  # canvas supported 0/1
            {
                "key": "jsbd",
                "value": "{\"HL\":41,\"NCE\":true,\"DMTO\":1,\"DOTO\":1}"
            }
        ]
        data_value = json.dumps(data)

        stamp = now - (now % (60 * 60 * 6))
        key_password = "******".format(user_agent, stamp)

        salt_bytes = os.urandom(8)
        key_iv = self.__evp_kdf(key_password.encode(),
                                salt_bytes,
                                key_size=8,
                                iv_size=4,
                                iterations=1,
                                hash_algorithm="md5")
        key = key_iv["key"]
        iv = key_iv["iv"]

        encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(key, iv))
        encrypted = encrypter.feed(data_value)
        # Again, make a final call to flush any remaining bytes and strip padding
        encrypted += encrypter.feed()

        salt_hex = binascii.hexlify(salt_bytes)
        iv_hex = binascii.hexlify(iv)
        encrypted_b64 = binascii.b2a_base64(encrypted)
        bda = {
            "ct": encrypted_b64.decode(),
            "iv": iv_hex.decode(),
            "s": salt_hex.decode()
        }
        bda_str = json.dumps(bda)
        bda_base64 = binascii.b2a_base64(bda_str.encode())

        req_dict = {
            "bda": bda_base64.decode(),
            "public_key": "FE296399-FDEA-2EA2-8CD5-50F6E3157ECA",
            "site": "https://client-api.arkoselabs.com",
            "userbrowser": user_agent,
            "simulate_rate_limit": "0",
            "simulated": "0",
            "rnd": "{}".format(random.random())
        }

        req_data = ""
        for k, v in req_dict.items():
            req_data = "{}{}={}&".format(req_data, k, self.url_encode(v))
        req_data = req_data.rstrip("&")

        arkose_headers = {"user-agent": user_agent}

        arkose_data = self.make_request(
            'https://client-api.arkoselabs.com/fc/gt2/public_key/FE296399-FDEA-2EA2-8CD5-50F6E3157ECA',
            'get',
            params=req_data,
            headers=arkose_headers)
        arkose_json = json.loads(arkose_data)
        arkose_token = arkose_json.get("token")

        if "rid=" not in arkose_token:
            self.log("Error logging in. Invalid Arkose token.")
            self.log(arkose_token)
            raise self.DplayError('Error logging in. Invalid Arkose token.')

        self.log("Succesfully required a login token from Arkose.")

        # Get new token
        self.get_token()

        discoveryplus_username = username
        discoveryplus_password = password
        creds = {
            "credentials": {
                "username": discoveryplus_username,
                "password": discoveryplus_password
            }
        }
        headers = {
            "x-disco-arkose-token":
            arkose_token,
            "x-disco-arkose-sitekey":
            "FE296399-FDEA-2EA2-8CD5-50F6E3157ECA",
            "Origin":
            "https://www.{site_url}".format(site_url=self.site_url),
            "x-disco-client":
            "WEB:10.16.0:AUTH_DPLAY_V1:4.0.1-rc2-gi1",
            # is not specified a captcha is required
            # "Sec-Fetch-Site": "same-site",
            # "Sec-Fetch-Mode": "cors",
            # "Sec-Fetch-Dest": "empty",
            "Referer":
            "https://www.{site_url}/myaccount/login".format(
                site_url=self.site_url),
            "User-Agent":
            user_agent
        }

        login_url = '{api_url}/login'.format(api_url=self.api_url)
        return self.make_request(login_url,
                                 'post',
                                 payload=json.dumps(creds),
                                 headers=headers)
Beispiel #12
0
 def update_aes_pyaes(self, key):
     self.aes = pyaes.AESModeOfOperationCBC(key, iv=bytes(self.iv))
Beispiel #13
0
 def encrypt_pyaes(self, payload):
   print 'Creating AES instance with provided key {}, iv {}'.format( key, iv)
   print("Encrypting payload")
   aes = pyaes.AESModeOfOperationCBC(self.key, iv = bytes(self.iv))
   return "".join([aes.encrypt(bytes(payload[i:i+16])) for i in range(0, len(payload), 16)])