Python rsa.decrypt() Examples

The following are 30 code examples of rsa.decrypt(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rsa , or try the search function .
Example #1
Source File: bcrypt_hash.py    From listen-now with MIT License 6 votes vote down vote up
def Check_Token(self, token_crypto, ip, ua):
        global re_dict
        if str(token_crypto)[-4:-1] != "NQZ":
            return "[-]token flag is error!"
        else:
            # with open('../project/Helper/privkey.pem','r') as f:
            #     privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())

            token_message = base64.b64decode(token_crypto[:-4])

            # token_message = rsa.decrypt(token_crypto, privkey)
            print("RSA解密后 ", token_message)
            message       = AES_Crypt_Cookies()
            if message.Decrypt_Check_Token(token_message, ip, ua):
                # token 校验成功,合法
                re_dict["token_status"] = ReturnStatus.TOKEN_ERROR
            else:
                # token 校验失败,不合法
                re_dict["token_status"] = ReturnStatus.TOKEN_SUCCESS 
Example #2
Source File: v2rayMS_Client.py    From v2rayMS with MIT License 6 votes vote down vote up
def pull_aes_key():
    def agreemnt_key(string):
        send_data(string)
        key_rsa = sock.recv(BUFSIZE)
        return key_rsa

    import rsa
    AES_Key_RSA = agreemnt_key(b'ApplyKey')
    with open('private.pem', 'r') as f:
        priv_key = rsa.PrivateKey.load_pkcs1(f.read().encode())
    AES_Key = rsa.decrypt(AES_Key_RSA, priv_key).decode('utf-8')
    print('Obtaining Key Success!')
    return AES_Key


# AES模块 
Example #3
Source File: rsaencrypt.py    From seecode-scanner with GNU General Public License v3.0 6 votes vote down vote up
def decrypt_str(self, message):
        """

        :param message:
        :return: bytes
        """
        msg = base64.b64decode(message)
        length = len(msg)
        default_length = self.default_length + 11
        # 长度不用分段
        if length < default_length:
            return rsa.decrypt(msg, self.private_key)
        # 需要分段
        offset = 0
        res = []
        while length - offset > 0:
            if length - offset > default_length:
                res.append(rsa.decrypt(msg[offset:offset + default_length], self.private_key))
            else:
                res.append(rsa.decrypt(msg[offset:], self.private_key))
            offset += default_length
        return b''.join(res) 
Example #4
Source File: v2rayMS_Client.py    From v2rayMS with MIT License 6 votes vote down vote up
def accept_cfg():
    Gud = ['pull_list']
    Gud_str = '#'.join(Gud)
    user_config_raw = accept_data(Gud_str)
    user_config_temp = crytpion.decrypt(user_config_raw)
    if user_config_temp != 'None':
        print('Update user list')
        try:
            user_config_list = [eval(i) for i in user_config_temp.split("#")]
            update_cfg(user_config_list, run_os)
            print('Update OK!')
        except Exception as e:
            print(e)
            print('Update Error!')
    else:
        print('Updates could not be found')


# 更新流量 
Example #5
Source File: v2rayMS_Client.py    From v2rayMS with MIT License 6 votes vote down vote up
def update_traffic():
    Gud = ['push_traffic']
    for user in User_list:
        try:
            traffic_msg = traffic_check(user['email'])
            if traffic_msg != 0:
                Gud.append([
                    int(user['email'][:-(len(DOMAIN) + 1)]), traffic_msg[0],
                    traffic_msg[1], traffic_msg[2]
                ])
        except Exception as e:
            print('ID:' + user['email'][:-(len(DOMAIN) + 1)] +
                  ' Traffic read error!')
            print(e)
    Gud_str = '#'.join('%s' % i for i in Gud)
    if crytpion.decrypt(accept_data(Gud_str)) == '$%^':
        return
    else:
        pass


# 主函数 
Example #6
Source File: decryptpassword.py    From bash-lambda-layer with MIT License 6 votes vote down vote up
def add_to_params(self, parameters, value):
        """
        This gets called with the value of our ``--priv-launch-key``
        if it is specified.  It needs to determine if the path
        provided is valid and, if it is, it stores it in the instance
        variable ``_key_path`` for use by the decrypt routine.
        """
        if value:
            path = os.path.expandvars(value)
            path = os.path.expanduser(path)
            if os.path.isfile(path):
                self._key_path = path
                endpoint_prefix = \
                    self._operation_model.service_model.endpoint_prefix
                event = 'after-call.%s.%s' % (endpoint_prefix,
                                              self._operation_model.name)
                self._session.register(event, self._decrypt_password_data)
            else:
                msg = ('priv-launch-key should be a path to the '
                       'local SSH private key file used to launch '
                       'the instance.')
                raise ValueError(msg) 
Example #7
Source File: cli.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args=None):
        """Decrypts files."""

        return rsa.decrypt(indata, priv_key) 
Example #8
Source File: __init__.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
def my_decrypt(self, text):
        """
        解密方法
        :param text: 加密后的密文
        :return:
        """
        # 初始化加密器
        aes = AES.new(self.add_to_16(self.key), AES.MODE_ECB)
        # 优先逆向解密base64成bytes
        base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
        # 执行解密密并转码返回str
        decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '')
        # print('[INFO]: 你的解密为:{}'.format(decrypted_text))
        return decrypted_text 
Example #9
Source File: __init__.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
def to_decrypt(cls, message, private_path=None, private_key=None, be_base64=True):
        # 非对称解密
        if be_base64: message = base64.b64decode(message)
        message = cls.check_message(message)

        private_key_obj = cls.load_private_key(private_path, private_key)

        return rsa.decrypt(message, private_key_obj).decode() 
Example #10
Source File: cli.py    From xbmc-addons-chinese with GNU General Public License v2.0 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args=None):
        """Decrypts files."""

        return rsa.decrypt(indata, priv_key) 
Example #11
Source File: cli.py    From xbmc-addons-chinese with GNU General Public License v2.0 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args=None):
        """Decrypts files."""

        return rsa.decrypt(indata, priv_key) 
Example #12
Source File: cli.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args=None):
        '''Decrypts files.'''

        return rsa.decrypt(indata, priv_key) 
Example #13
Source File: cli.py    From opsbro with MIT License 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args=None):
        '''Decrypts files.'''

        return rsa.decrypt(indata, priv_key) 
Example #14
Source File: cli.py    From plugin.video.bdyun with GNU General Public License v3.0 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args=None):
        """Decrypts files."""

        return rsa.decrypt(indata, priv_key) 
Example #15
Source File: decryptpassword.py    From bash-lambda-layer with MIT License 5 votes vote down vote up
def _decrypt_password_data(self, parsed, **kwargs):
        """
        This handler gets called after the GetPasswordData command has been
        executed.  It is called with the and the ``parsed`` data.  It checks to
        see if a private launch key was specified on the command.  If it was,
        it tries to use that private key to decrypt the password data and
        replace it in the returned data dictionary.
        """
        if self._key_path is not None:
            logger.debug("Decrypting password data using: %s", self._key_path)
            value = parsed.get('PasswordData')
            if not value:
                return
            try:
                with open(self._key_path) as pk_file:
                    pk_contents = pk_file.read()
                    private_key = rsa.PrivateKey.load_pkcs1(six.b(pk_contents))
                    value = base64.b64decode(value)
                    value = rsa.decrypt(value, private_key)
                    logger.debug(parsed)
                    parsed['PasswordData'] = value.decode('utf-8')
                    logger.debug(parsed)
            except Exception:
                logger.debug('Unable to decrypt PasswordData', exc_info=True)
                msg = ('Unable to decrypt password data using '
                       'provided private key file.')
                raise ValueError(msg) 
Example #16
Source File: bcrypt_hash.py    From listen-now with MIT License 5 votes vote down vote up
def Decrypt_Check_Token(self,token_crypto, ip, ua):

        aes = AES.new(self.key, self.mode,self.key)
        # token_crypto = base64.b64decode(token_crypto)
        token_crypto = str(aes.decrypt(token_crypto), encoding="utf8").split(";")
        token_time   = int(token_crypto[0])
        now_time     = int(time.time())
        if now_time<token_time and ip == token_crypto[2] and ua == token_crypto[3]:
            print("[+]token is exist!")
            return 1
        else:
            print("[-]token bad!")
            return 0
        print(now_time, token_time, token_crypto) 
Example #17
Source File: cli.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args=None):
        """Decrypts files."""

        return rsa.decrypt(indata, priv_key) 
Example #18
Source File: __init__.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
def my_decrypt(self, text):
        cryptor = AES.new(self.key, self.mode, b'0000000000000000')
        plain_text = cryptor.decrypt(a2b_hex(text)).decode('utf-8')
        return plain_text.rstrip('\0') 
Example #19
Source File: RSA-AES-MD5-DES-DES3-MD5-SHA-HMAC.py    From R-A-M-D-D3-S-M-H with MIT License 5 votes vote down vote up
def decodebytes(self, text):
        aes = self.aes()
        return str(aes.decrypt(base64.decodebytes(bytes(
            text, encoding='utf8'))).rstrip(b'\0').decode("utf8"))  # 解密 
Example #20
Source File: cli.py    From bash-lambda-layer with MIT License 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args=None):
        """Decrypts files."""

        return rsa.decrypt(indata, priv_key) 
Example #21
Source File: cli.py    From baidupan_shell with GNU General Public License v2.0 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args=None):
        '''Decrypts files.'''

        return rsa.decrypt(indata, priv_key) 
Example #22
Source File: cli.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def perform_operation(self, indata, priv_key, cli_args=None):
        """Decrypts files."""

        return rsa.decrypt(indata, priv_key) 
Example #23
Source File: security.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
def aes_decrypt(self, encrypt):
		return self.aes_encrypt(encrypt)
		#aes_obj_enc = AES.new(self.aes, AES.MODE_CBC, self.iv)
		#return aes_obj_enc.decrypt(encrypt).rstrip(PADDING) 
Example #24
Source File: security.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
def rsa_long_decrypt(self, crypto, length = 128):
		res = []

		for i in range(0, len(crypto), length):
			res.append(rsa.decrypt(crypto[i : i + length], self.privkey))

		return b"".join(res) 
Example #25
Source File: rsalib.py    From swift_rpc with MIT License 5 votes vote down vote up
def decrypt(crypto):
    message = rsa.decrypt(crypto, privkey)
    return message 
Example #26
Source File: v2rayMS_Client.py    From v2rayMS with MIT License 5 votes vote down vote up
def decrypt(self, text):
        cryptor = self.AES.new(self.key, self.mode, self.iv)
        plain_text = cryptor.decrypt(self.a2b_hex(text))
        return plain_text.rstrip(b'\0').decode() 
Example #27
Source File: RSA-AES-MD5-DES-DES3-MD5-SHA-HMAC.py    From R-A-M-D-D3-S-M-H with MIT License 5 votes vote down vote up
def decrypt(self, text):
        cryptor = DES3.new(self.key, self.mode)
        plain_text = cryptor.decrypt(text)
        st = str(plain_text.decode("utf-8")).rstrip('\0')
        return st 
Example #28
Source File: RSA-AES-MD5-DES-DES3-MD5-SHA-HMAC.py    From R-A-M-D-D3-S-M-H with MIT License 5 votes vote down vote up
def descrypt(self, text):
        """
        DES 解密
        :param text: 加密后的字符串,bytes
        :return:  解密后的字符串
        """
        secret_key = self.key
        iv = self.iv
        k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
        de = k.decrypt(text, padmode=PAD_PKCS5)
        return de.decode() 
Example #29
Source File: RSA-AES-MD5-DES-DES3-MD5-SHA-HMAC.py    From R-A-M-D-D3-S-M-H with MIT License 5 votes vote down vote up
def rsaDecrypt(self, text):
        """
        :param text:bytes 
        :return: str
        """
        content = rsa.decrypt(text, self.privkey)
        con = content.decode('utf-8')
        return con 
Example #30
Source File: utility.py    From tuijam with MIT License 4 votes vote down vote up
def lookup_keys(*key_ids):
    import base64
    import yaml
    import rsa
    import requests

    from tuijam import CONFIG_FILE

    keys = [None] * len(key_ids)
    # First, check if any are in configuration file
    with open(CONFIG_FILE, "r") as f:
        cfg = yaml.safe_load(f)
        for idx, id_ in enumerate(key_ids):
            try:
                keys[idx] = cfg[id_]
            except KeyError:
                pass

    # Next, if any unspecified in config file, ask the server for them
    to_query = {}
    for idx, (id_, key) in enumerate(zip(key_ids, keys)):
        if key is None:
            # keep track of position of each key so output order matches
            to_query[id_] = idx

    if to_query:
        (pub, priv) = rsa.newkeys(512)  # Generate new RSA key pair. Do not reuse keys!
        host = cfg.get("key_server", "https://tuijam.fangmeier.tech")

        res = requests.post(
            host, json={"public_key": pub.save_pkcs1().decode(), "ids": list(to_query)}
        )

        for id_, key_encrypted in res.json().items():
            # On the server, the api key is encrypted with the public RSA key,
            # and then base64 encoded to be delivered. Reverse that process here.
            key_decrypted = rsa.decrypt(
                base64.decodebytes(key_encrypted.encode()), priv
            ).decode()
            keys[to_query[id_]] = key_decrypted

    return keys