Beispiel #1
0
    def _login(self):
        username, password = self._get_login_info()
        if username is None:
            return

        try:
            from Cryptodome.PublicKey import RSA
            from Cryptodome.Cipher import PKCS1_v1_5
        except ImportError:
            try:
                from Crypto.PublicKey import RSA
                from Crypto.Cipher import PKCS1_v1_5
            except ImportError:
                raise ExtractorError('pycryptodomex not found. Please install', expected=True)

        key_data = self._download_json(
            'https://passport.bilibili.tv/x/intl/passport-login/web/key?lang=en-US', None,
            note='Downloading login key', errnote='Unable to download login key')['data']

        public_key = RSA.importKey(key_data['key'])
        password_hash = PKCS1_v1_5.new(public_key).encrypt((key_data['hash'] + password).encode('utf-8'))
        login_post = self._download_json(
            'https://passport.bilibili.tv/x/intl/passport-login/web/login/password?lang=en-US', None, data=urlencode_postdata({
                'username': username,
                'password': base64.b64encode(password_hash).decode('ascii'),
                'keep_me': 'true',
                's_locale': 'en_US',
                'isTrusted': 'true'
            }), note='Logging in', errnote='Unable to log in')
        if login_post.get('code'):
            if login_post.get('message'):
                raise ExtractorError(f'Unable to log in: {self.IE_NAME} said: {login_post["message"]}', expected=True)
            else:
                raise ExtractorError('Unable to log in')
Beispiel #2
0
    def decrypt(self, ciphertext, key, padding="pkcs1_padding"):
        if padding == "pkcs1_padding":
            cipher = PKCS1_v1_5.new(key)
            if self.with_digest:
                dsize = SHA.digest_size
            else:
                dsize = 0
            sentinel = Random.new().read(32 + dsize)
            text = cipher.decrypt(ciphertext, sentinel)
            if dsize:
                _digest = text[-dsize:]
                _msg = text[:-dsize]
                digest = SHA.new(_msg).digest()
                if digest == _digest:
                    text = _msg
                else:
                    raise DecryptionFailed()
            else:
                if text == sentinel:
                    raise DecryptionFailed()
        elif padding == "pkcs1_oaep_padding":
            cipher = PKCS1_OAEP.new(key)
            text = cipher.decrypt(ciphertext)
        else:
            raise Exception("Unsupported padding")

        return text
Beispiel #3
0
 def decrypt(en_data):
     """ 
     @param string en_data
     @param string password
     return dict
     """
     # 读取密钥
     private_key = RSA.import_key(
         open(os.getcwd() + "/app/my_private_rsa_key.bin").read())
     cipher_rsa = PKCS1_v1_5.new(private_key)  # type: ignore
     #切割字符串
     en_data_list = en_data.split(",")
     data = ""
     for en in en_data_list:
         en = base64.b64decode(en)
         if len(en) == 127:
             hex_fixed = '00' + en.hex()
             en = base64.b16decode(hex_fixed.upper())
         try:
             data += str(
                 cipher_rsa.decrypt(en, None), "utf8"
             )  #chardet.detect(cipher_rsa.decrypt(en, None))['encoding'])#推断字符集
         except Exception as e:
             print(e)
     return json.loads(data, encoding='utf8')
Beispiel #4
0
    def decrypt(self, ciphertext, key, padding="pkcs1_padding"):
        if padding == "pkcs1_padding":
            cipher = PKCS1_v1_5.new(key)
            if self.with_digest:
                dsize = SHA.digest_size
            else:
                dsize = 0
            sentinel = Random.new().read(32 + dsize)
            text = cipher.decrypt(ciphertext, sentinel)
            if dsize:
                _digest = text[-dsize:]
                _msg = text[:-dsize]
                digest = SHA.new(_msg).digest()
                if digest == _digest:
                    text = _msg
                else:
                    raise DecryptionFailed()
            else:
                if text == sentinel:
                    raise DecryptionFailed()
        elif padding == "pkcs1_oaep_padding":
            cipher = PKCS1_OAEP.new(key)
            text = cipher.decrypt(ciphertext)
        else:
            raise Exception("Unsupported padding")

        return text
Beispiel #5
0
def _add_header_client_encryption_key(api_context: ApiContext, key: bytes,
                                      custom_headers: Dict[str, str]) -> None:
    public_key_server = api_context.installation_context.public_key_server
    key_cipher = PKCS1_v1_5_Cipher.new(public_key_server)
    key_encrypted = key_cipher.encrypt(key)
    key_encrypted_base64 = base64.b64encode(key_encrypted).decode()
    custom_headers[_HEADER_CLIENT_ENCRYPTION_KEY] = key_encrypted_base64
Beispiel #6
0
    def decrypt(self, cipher):
        """
        :type cipher long
        :param cipher: 密文
        :return:
        """
        cipher = self.encoding_2_long(cipher, self.cipher_encoding)
        if self.d is not None:
            d = self.d
        else:
            d = inverse(self.e, (self.p - 1) * (self.q - 1))

        if self.n is not None:
            n = self.n
        else:
            n = self.p * self.q

        rsa = RSA.construct((n, self.e, d))
        if self.padding == 'PKCS1_OAEP':
            rsa = PKCS1_OAEP.new(rsa)
            plain = rsa.decrypt(long_to_bytes(cipher))
        elif self.padding == 'PKCS1_v1_5':
            rsa = PKCS1_v1_5.new(rsa)
            plain = rsa.decrypt(long_to_bytes(cipher), True)
        else:
            plain = pow(cipher, d, n)
            return self.long_2_encoding(plain, self.plain_encoding)

        plain = self.long_2_encoding(bytes_to_long(plain), self.plain_encoding)
        return plain
Beispiel #7
0
    def _encode_password(self, password: str = None) -> Optional[str]:
        """Encrypts the raw password into a form that Instagram accepts."""
        # the api key will be retrieved from the first request, so it will not
        # be present during the initial request
        if not self.state.public_api_key: return
        key = Random.get_random_bytes(32)
        iv = Random.get_random_bytes(12)
        time = int(datetime.datetime.now().timestamp())

        pubkey = base64.b64decode(self.state.public_api_key)

        rsa_key = RSA.importKey(pubkey)
        rsa_cipher = PKCS1_v1_5.new(rsa_key)
        encrypted_key = rsa_cipher.encrypt(key)

        aes = AES.new(key, AES.MODE_GCM, nonce=iv)
        aes.update(str(time).encode('utf-8'))

        encrypted_password, cipher_tag = aes.encrypt_and_digest(bytes(password or self._unencrypted_password, 'utf-8'))

        encrypted = bytes([1,
                           int(self.state.public_api_key_id),
                           *list(iv),
                           *list(struct.pack('<h', len(encrypted_key))),
                           *list(encrypted_key),
                           *list(cipher_tag),
                           *list(encrypted_password)])
        encrypted = base64.b64encode(encrypted).decode('utf-8')

        encrypted_password = f'#PWD_INSTAGRAM:4:{time}:{encrypted}'
        if password is not None:
            return encrypted_password
        self._encrypted_password = encrypted_password
Beispiel #8
0
 def test_return_type(self):
     pt = b"XYZ"
     cipher = PKCS.new(self.key1024)
     ct = cipher.encrypt(pt)
     self.assertTrue(isinstance(ct, bytes))
     pt2 = cipher.decrypt(ct, b'\xAA' * 3)
     self.assertTrue(isinstance(pt2, bytes))
Beispiel #9
0
    def encrypt(self, plain):
        """
        :type plain long
        :param plain: 明文
        :return:
        """
        plain = self.encoding_2_long(plain, self.plain_encoding)
        rsa = RSA.construct((
            self.n,
            self.e,
        ))
        # 最佳非对称加密填充(OAEP)
        if self.padding == 'PKCS1_OAEP':
            rsa = PKCS1_OAEP.new(rsa)
            cipher = rsa.encrypt(long_to_bytes(plain))
        elif self.padding == 'PKCS1_v1_5':
            rsa = PKCS1_v1_5.new(rsa)
            cipher = rsa.encrypt(long_to_bytes(plain))
        else:
            cipher = pow(plain, self.e, self.n)
            return self.long_2_encoding(cipher, self.cipher_encoding)

        cipher = self.long_2_encoding(bytes_to_long(cipher),
                                      self.cipher_encoding)
        return cipher
Beispiel #10
0
 def mid_sever_decode(self, cypher, sq, url):
     prk = self.mid_server_transport_priKey2(self, sq, url)
     print(cypher)
     prk = prk.replace("\\n", "")[27:-25]
     start = '-----BEGIN RSA PRIVATE KEY-----\n'
     end = '-----END RSA PRIVATE KEY-----'
     length = len(prk)
     divide = 64  # 切片长度
     offset = 0  # 拼接长度
     result0 = ''
     while length - offset > 0:
         if length - offset > divide:
             result0 += prk[offset:offset + divide] + '\n'
         else:
             result0 += prk[offset:] + '\n'
         offset += divide
     result0 = start + result0 + end
     prk = result0
     prk = RSA.importKey(prk)
     prk0 = Cipher_pkcs1_v1_5.new(prk)
     # if(prk['code']==200):
     #   prk=prk['prk']
     result = prk0.decrypt(base64.b64decode(cypher), prk0)
     msg.deleteis_by_sq(sq)
     print(result)
     return {'code': 200, 'result': str(result)}
def get_sign(ts,token):
    s = token[:50] + ts
    key = '-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQENQujkLfZfc5Tu9Z1LprzedEO3F7gs+7bzrgPsMl29LX8UoPYvIG8C604CprBQ4FkfnJpnhWu2lvUB0WZyLq6sBrtuPorOc42+gLnFfyhJAwdZB6SqWfDg7bW+jNe5Ki1DtU7z8uF6Gx+blEMGo8Dg+SkKlZFc8Br7SHtbL2tQIDAQAB\n-----END PUBLIC KEY-----'
    public_key = RSA.import_key(key)
    cipher = PKCS1_v1_5.new(public_key)
    encrypted_bytes = cipher.encrypt(s.encode())
    return b64encode(encrypted_bytes).decode()
Beispiel #12
0
def encrypt(s):
    # 标准的rsa调python的库就可以了
    public_key = r"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDhNhuAr4UjFv+cj99PbAQWWx9H 	X+3jSRThJqJdXkWUMFMTRay8EYRtPFIiwiOUU4gCh4ePMxiuZJWUBHe1waOkXEFc 	Kg17luhVqECsO+EOLhxa3yHoXA5HcSKlG85hNV3G4uQCr+C8SOE0vCGTnMdnEGmU 	nG1AGGe44YKy6XR4VwIDAQAB"
    rsa_key = RSA.import_key(base64.b64decode(public_key))
    cipher = PKCS1_v1_5.new(rsa_key)
    return base64.b64encode(cipher.encrypt(
        s.encode(encoding="UTF-8"))).decode("UTF-8")
def _encrypt(connection_info_str, public_key):
    """Encrypt the connection information using a generated AES key that is then encrypted using
    the public key passed from the server.  Both are then returned in an encoded JSON payload.

    This code also exists in the R kernel-launcher's server_listener.py script.
    """
    aes_key = get_random_bytes(16)
    cipher = AES.new(aes_key, mode=AES.MODE_ECB)

    # Encrypt the connection info using the aes_key
    encrypted_connection_info = cipher.encrypt(pad(connection_info_str, 16))
    b64_connection_info = base64.b64encode(encrypted_connection_info)

    # Encrypt the aes_key using the server's public key
    imported_public_key = RSA.importKey(base64.b64decode(public_key.encode()))
    cipher = PKCS1_v1_5.new(key=imported_public_key)
    encrypted_key = base64.b64encode(cipher.encrypt(aes_key))

    # Compose the payload and Base64 encode it
    payload = {
        "version": LAUNCHER_VERSION,
        "key": encrypted_key.decode(),
        "conn_info": b64_connection_info.decode(),
    }
    b64_payload = base64.b64encode(
        json.dumps(payload).encode(encoding="utf-8"))
    return b64_payload
Beispiel #14
0
def rsa_decrypt(key, data):
    sentinel = Random.new().read(35)
    cipher = PKCS1_v1_5.new(key)
    b = base64.b64decode(data)
    s = b''.join([
        cipher.decrypt(b[i:i + 128], sentinel) for i in range(0, len(b), 128)
    ])
    return s.decode('utf-8')
 def _encrypted_password(public_key, password):
     try:
         raw_key = b64decode(public_key)
         key = RSA.importKey(raw_key)
         cipher = PKCS1_v1_5.new(key)
         return b64encode(cipher.encrypt(password.encode("utf-8")))
     except Exception as e:
         print(e)
Beispiel #16
0
 def testVerify1(self):
     for test in self._testData:
         # Build the key
         key = RSA.importKey(test[0])
         # The real test
         cipher = PKCS.new(key)
         pt = cipher.decrypt(t2b(test[2]), "---")
         self.assertEqual(pt, b(test[1]))
 def testVerify1(self):
         for test in self._testData:
                 # Build the key
                 key = RSA.importKey(test[0])
                 # The real test
                 cipher = PKCS.new(key)
                 pt = cipher.decrypt(t2b(test[2]), "---")
                 self.assertEqual(pt, b(test[1]))
Beispiel #18
0
def RSA_gKey_Decrypt(cipher_text):
    with open('ghost-private.pem', 'rb') as f:
        key = f.read()
        rsakey = RSA.importKey(key)  # 导入读取到的私钥
        cipher = Cipher_pkcs1_v1_5.new(rsakey)  # 生成对象
        # 将密文解密成明文,返回的是bytes类型,需要自己转成str,主要是对中文的处理
        text = cipher.decrypt(base64.b64decode(cipher_text), "ERROR")
        return text.decode(encoding=encode_gbk_utf8)
Beispiel #19
0
 def testEncryptVerify1(self):
     # Encrypt/Verify messages of length [0..RSAlen-11]
     # and therefore padding [8..117]
     for pt_len in range(0, 128 - 11 + 1):
         pt = self.rng(pt_len)
         cipher = PKCS.new(self.key1024)
         ct = cipher.encrypt(pt)
         pt2 = cipher.decrypt(ct, "---")
         self.assertEqual(pt, pt2)
    def __init__(self, s):

        recipient_key = RSA.import_key(open("public.pem").read())

        self.rsa = PKCS1_v1_5.new(recipient_key)

        # 使用CBC模式加密
        self.aes_mode = AES.MODE_CBC
        self.user_auth_key = {}
Beispiel #21
0
    def rsa_encode(self, public_key_file, plaintext):
        # 加载公钥
        plaintext = plaintext.encode(encoding='utf-8')
        recipient_key = RSA.import_key(open(public_key_file).read())
        cipher_rsa = PKCS1_v1_5.new(recipient_key)

        en_data = cipher_rsa.encrypt(plaintext)
        print(len(en_data), en_data)
        return en_data
Beispiel #22
0
def get_header_key(priva_key):
    public_key = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM1xhOWaThSMpfxFsjV5YaWOFHt+6RvS+zH2Pa47VVr8PkZYnRaaKKy2MYBuEh7mZfM/R1dUXTgu0gp6VTNeNQkCAwEAAQ=="
    # 导入公钥
    rsa_key = RSA.import_key(base64.b64decode(public_key))
    # 生成对象
    rsa_object = PKCS1_v1_5.new(rsa_key)
    # 加密
    header_key = base64.b64encode(rsa_object.encrypt(priva_key.encode(encoding="utf-8")))
    return header_key
Beispiel #23
0
 def decrypt(self, text: str):
     """
     rsa 解密
     """
     key = RSA.import_key(self._get_private_key())
     cipher = PKCS1_v1_5.new(key)
     return cipher.decrypt(base64.b64decode(text),
                           Random.new().read(15 +
                                             SHA.digest_size)).decode()
def get_encrypted_password_by_python(password):
    timestamp = str(int(time.time() * 1000))
    encrypted_object = timestamp + "|" + password
    public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDq04c6My441Gj0UFKgrqUhAUg+kQZeUeWSPlAU9fr4HBPDldAeqzx1UR92KJHuQh/zs1HOamE2dgX9z/2oXcJaqoRIA/FXysx+z2YlJkSk8XQLcQ8EBOkp//MZrixam7lCYpNOjadQBb2Ot0U/Ky+jF2p+Ie8gSZ7/u+Wnr5grywIDAQAB"
    rsa_key = RSA.import_key(base64.b64decode(public_key))  # 导入读取到的公钥
    cipher = PKCS1_v1_5.new(rsa_key)                        # 生成对象
    encrypted_password = base64.b64encode(cipher.encrypt(encrypted_object.encode(encoding="utf-8")))
    encrypted_password = parse.quote(encrypted_password)
    return encrypted_password
Beispiel #25
0
    def encrypt_and_decrypt_test():
        # 加载公钥
        recipient_key = RSA.import_key(
            open("my_rsa_public.pem").read()
        )
        cipher_rsa = PKCS1_v1_5.new(recipient_key)

        en_data = cipher_rsa.encrypt(b"123456")
        print(len(en_data), en_data)

        # 读取密钥
        private_key = RSA.import_key(
            open("my_private_rsa_key.bin").read()
        )
        cipher_rsa = PKCS1_v1_5.new(private_key)
        data = cipher_rsa.decrypt(en_data, None)

        print(data)
Beispiel #26
0
def RSA_gKey_Encrypt(message):
    with open('ghost-public.pem', 'rb') as f:
        key = f.read()
        rsakey = RSA.importKey(key)  # 导入读取到的公钥
        cipher = Cipher_pkcs1_v1_5.new(rsakey)  # 生成对象
        # 加密message明文,python3加密的数据必须是bytes,不能是str
        cipher_text = base64.b64encode(
            cipher.encrypt(message.encode(encoding=encode_gbk_utf8)))
        return cipher_text
 def testEncryptVerify1(self):
         # Encrypt/Verify messages of length [0..RSAlen-11]
         # and therefore padding [8..117]
         for pt_len in range(0,128-11+1):
             pt = self.rng(pt_len)
             cipher = PKCS.new(self.key1024)
             ct = cipher.encrypt(pt)
             pt2 = cipher.decrypt(ct, "---")
             self.assertEqual(pt,pt2)
Beispiel #28
0
def rsa_long_decrypt(msg):
    recipient_key = RSA.import_key(open("private.pem").read())
    rsa = PKCS1_v1_5.new(recipient_key)
    res = []
    msg = literal_eval(base64.b64decode(msg).decode())
    for i in msg:
        res.append(
            rsa.decrypt(base64.b64decode(i.encode()),
                        None).decode("utf-8", "ignore"))
    return "".join(res)
Beispiel #29
0
    def rsa_decode(self, password='******', en_data=b'', private_key_file=''):
        # 读取密钥
        # en_data=en_data.decode("ISO-8859-1", 'ignore')
        private_key = RSA.import_key(open(private_key_file).read(),
                                     passphrase=password)
        cipher_rsa = PKCS1_v1_5.new(private_key)
        data = cipher_rsa.decrypt(en_data, None)

        print(data)
        return data
Beispiel #30
0
def decrypt_rsa(encrypt_data):
    """
    Ghost使用自己的私钥对内容进行rsa 解密
    :return:
    """
    with open('ghost-private.pem') as f:
        key = f.read()
        rsakey = RSA.importKey(key)
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        text = cipher.decrypt(base64.b64decode(encrypt_data), None)
    return text.decode()
Beispiel #31
0
 def encrypt(self, msg, key, padding="pkcs1_padding"):
     if padding == "pkcs1_padding":
         cipher = PKCS1_v1_5.new(key)
         if self.with_digest:  # add a SHA digest to the message
             h = SHA.new(msg)
             msg += h.digest()
     elif padding == "pkcs1_oaep_padding":
         cipher = PKCS1_OAEP.new(key)
     else:
         raise Exception("Unsupported padding")
     return cipher.encrypt(msg)
 def get_password(self, pubkey, password):
     # publickey = rsa.PublicKey(int(pubkey, 16), int('10001', 16))
     # res = rsa.encrypt(password.encode(), publickey)
     # 生成公钥
     recipient_key = RSA.RsaKey(n=int(pubkey, 16), e=65537)
     # 创建rsa对象
     cipher_rsa = PKCS1_v1_5.new(recipient_key)
     # 加密数据+转换成16进制
     msg = binascii.b2a_hex(cipher_rsa.encrypt(password.encode())).decode()
     # print(msg)
     return msg
Beispiel #33
0
 def encrypt(cls, message):
     key = open("./MLE/public.pem").read()
     key = key.replace("-----BEGIN PUBLIC KEY-----",
                       "").replace("-----END PUBLIC KEY-----",
                                   "").replace("\n", "")
     key = base64.b64decode(key)
     key = RSA.importKey(key)
     cipher = PKCS1_v1_5.new(key)
     encrypted_message = base64.b64encode(
         cipher.encrypt(bytes(message, 'utf-8'))).decode('utf-8')
     return encrypted_message
        def testVerify2(self):
                # Verify that decryption fails if ciphertext is not as long as
                # RSA modulus
                cipher = PKCS.new(self.key1024)
                self.assertRaises(ValueError, cipher.decrypt, '\x00'*127, "---")
                self.assertRaises(ValueError, cipher.decrypt, '\x00'*129, "---")

                # Verify that decryption fails if there are less then 8 non-zero padding
                # bytes
                pt = b('\x00\x02' + '\xFF'*7 + '\x00' + '\x45'*118)
                pt_int = bytes_to_long(pt)
                ct_int = self.key1024._encrypt(pt_int)
                ct = long_to_bytes(ct_int, 128)
                self.assertEqual("---", cipher.decrypt(ct, "---"))
 def testEncrypt1(self):
         for test in self._testData:
                 # Build the key
                 key = RSA.importKey(test[0])
                 # RNG that takes its random numbers from a pool given
                 # at initialization
                 class randGen:
                     def __init__(self, data):
                         self.data = data
                         self.idx = 0
                     def __call__(self, N):
                         r = self.data[self.idx:self.idx+N]
                         self.idx += N
                         return r
                 # The real test
                 cipher = PKCS.new(key, randfunc=randGen(t2b(test[3])))
                 ct = cipher.encrypt(b(test[1]))
                 self.assertEqual(ct, t2b(test[2]))
 def testMemoryview(self):
     pt = b"XER"
     cipher = PKCS.new(self.key1024)
     ct = cipher.encrypt(memoryview(bytearray(pt)))
     pt2 = cipher.decrypt(memoryview(bytearray(ct)), "---")
     self.assertEqual(pt, pt2)
 def testEncrypt2(self):
         # Verify that encryption fail if plaintext is too long
         pt = '\x00'*(128-11+1)
         cipher = PKCS.new(self.key1024)
         self.assertRaises(ValueError, cipher.encrypt, pt)
Beispiel #38
0
    def run(self):
        if self.options.action.upper() == 'MASTERKEY':
            fp = open(options.file, 'rb')
            data = fp.read()
            mkf= MasterKeyFile(data)
            mkf.dump()
            data = data[len(mkf):]

            if mkf['MasterKeyLen'] > 0:
                mk = MasterKey(data[:mkf['MasterKeyLen']])
                data = data[len(mk):]

            if mkf['BackupKeyLen'] > 0:
                bkmk = MasterKey(data[:mkf['BackupKeyLen']])
                data = data[len(bkmk):]

            if mkf['CredHistLen'] > 0:
                ch = CredHist(data[:mkf['CredHistLen']])
                data = data[len(ch):]

            if mkf['DomainKeyLen'] > 0:
                dk = DomainKey(data[:mkf['DomainKeyLen']])
                data = data[len(dk):]

            if self.options.system and self.options.security:
                # We have hives, let's try to decrypt with them
                self.getLSA()
                decryptedKey = mk.decrypt(self.dpapiSystem['UserKey'])
                if decryptedKey:
                    print('Decrypted key with UserKey')
                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))
                    return
                decryptedKey = mk.decrypt(self.dpapiSystem['MachineKey'])
                if decryptedKey:
                    print('Decrypted key with MachineKey')
                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))
                    return
                decryptedKey = bkmk.decrypt(self.dpapiSystem['UserKey'])
                if decryptedKey:
                    print('Decrypted Backup key with UserKey')
                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))
                    return
                decryptedKey = bkmk.decrypt(self.dpapiSystem['MachineKey'])
                if decryptedKey:
                    print('Decrypted Backup key with MachineKey')
                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))
                    return
            elif self.options.key:
                key = unhexlify(self.options.key[2:])
                decryptedKey = mk.decrypt(key)
                if decryptedKey:
                    print('Decrypted key with key provided')
                    print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1'))
                    return

            elif self.options.pvk and dk:
                pvkfile = open(self.options.pvk, 'rb').read()
                key = PRIVATE_KEY_BLOB(pvkfile[len(PVK_FILE_HDR()):])
                private = privatekeyblob_to_pkcs1(key)
                cipher = PKCS1_v1_5.new(private)

                decryptedKey = cipher.decrypt(dk['SecretData'][::-1], None)
                if decryptedKey:
                    domain_master_key = DPAPI_DOMAIN_RSA_MASTER_KEY(decryptedKey)
                    key = domain_master_key['buffer'][:domain_master_key['cbMasterKey']]
                    print('Decrypted key with domain backup key provided')
                    print('Decrypted key: 0x%s' % hexlify(key).decode('latin-1'))
                return

            elif self.options.sid and self.options.key is None:
                # Do we have a password?
                if self.options.password is None:
                    # Nope let's ask it
                    from getpass import getpass
                    password = getpass("Password:"******"Password:"******"G$BCKUPKEY_PREFERRED", "G$BCKUPKEY_P"):
                buffer = crypto.decryptSecret(connection.getSessionKey(), lsad.hLsarRetrievePrivateData(dce,
                                              resp['PolicyHandle'], keyname))
                guid = bin_to_string(buffer)
                name = "G$BCKUPKEY_{}".format(guid)
                secret = crypto.decryptSecret(connection.getSessionKey(), lsad.hLsarRetrievePrivateData(dce,
                                              resp['PolicyHandle'], name))
                keyVersion = struct.unpack('<L', secret[:4])[0]
                if keyVersion == 1:  # legacy key
                    backup_key = P_BACKUP_KEY(secret)
                    backupkey = backup_key['Data']
                    if self.options.export:
                        logging.debug("Exporting key to file {}".format(name + ".key"))
                        open(name + ".key", 'wb').write(backupkey)
                    else:
                        print("Legacy key:")
                        print("0x%s" % hexlify(backupkey))
                        print("\n")

                elif keyVersion == 2:  # preferred key
                    backup_key = PREFERRED_BACKUP_KEY(secret)
                    pvk = backup_key['Data'][:backup_key['KeyLength']]
                    cert = backup_key['Data'][backup_key['KeyLength']:backup_key['KeyLength'] + backup_key['CertificateLength']]

                    # build pvk header (PVK_MAGIC, PVK_FILE_VERSION_0, KeySpec, PVK_NO_ENCRYPT, 0, cbPvk)
                    header = PVK_FILE_HDR()
                    header['dwMagic'] = 0xb0b5f11e
                    header['dwVersion'] = 0
                    header['dwKeySpec'] = 1
                    header['dwEncryptType'] = 0
                    header['cbEncryptData'] = 0
                    header['cbPvk'] = backup_key['KeyLength']
                    backupkey_pvk = header.getData() + pvk  # pvk blob

                    backupkey = backupkey_pvk
                    if self.options.export:
                        logging.debug("Exporting certificate to file {}".format(name + ".der"))
                        open(name + ".der", 'wb').write(cert)
                        logging.debug("Exporting private key to file {}".format(name + ".pvk"))
                        open(name + ".pvk", 'wb').write(backupkey)
                    else:
                        print("Preferred key:")
                        header.dump()
                        print("PRIVATEKEYBLOB:{%s}" % (hexlify(backupkey)))
                        print("\n")
            return


        elif self.options.action.upper() == 'CREDENTIAL':
            fp = open(options.file, 'rb')
            data = fp.read()
            cred = CredentialFile(data)
            blob = DPAPI_BLOB(cred['Data'])

            if self.options.key is not None:
                key = unhexlify(self.options.key[2:])
                decrypted = blob.decrypt(key)
                if decrypted is not None:
                    creds = CREDENTIAL_BLOB(decrypted)
                    creds.dump()
                    return
            else:
                # Just print the data
                blob.dump()

        elif self.options.action.upper() == 'VAULT':
            if options.vcrd is None and options.vpol is None:
                print('You must specify either -vcrd or -vpol parameter. Type --help for more info')
                return
            if options.vcrd is not None:
                fp = open(options.vcrd, 'rb')
                data = fp.read()
                blob = VAULT_VCRD(data)

                if self.options.key is not None:
                    key = unhexlify(self.options.key[2:])

                    cleartext = None
                    for i, entry in enumerate(blob.attributesLen):
                        if entry > 28:
                            attribute = blob.attributes[i]
                            if 'IV' in attribute.fields and len(attribute['IV']) == 16:
                                cipher = AES.new(key, AES.MODE_CBC, iv=attribute['IV'])
                            else:
                                cipher = AES.new(key, AES.MODE_CBC)
                            cleartext = cipher.decrypt(attribute['Data'])

                    if cleartext is not None:
                        # Lookup schema Friendly Name and print if we find one
                        if blob['FriendlyName'].decode('utf-16le')[:-1] in VAULT_KNOWN_SCHEMAS:
                            # Found one. Cast it and print
                            vault = VAULT_KNOWN_SCHEMAS[blob['FriendlyName'].decode('utf-16le')[:-1]](cleartext)
                            vault.dump()
                        else:
                            # otherwise
                            hexdump(cleartext)
                        return
                else:
                    blob.dump()

            elif options.vpol is not None:
                fp = open(options.vpol, 'rb')
                data = fp.read()
                vpol = VAULT_VPOL(data)
                vpol.dump()

                if self.options.key is not None:
                    key = unhexlify(self.options.key[2:])
                    blob = vpol['Blob']
                    data = blob.decrypt(key)
                    if data is not None:
                        keys = VAULT_VPOL_KEYS(data)
                        keys.dump()
                        return

        print('Cannot decrypt (specify -key or -sid whenever applicable) ')