【Python3】RSA公钥解密


使用python进行公钥加密私钥解密,网上方法很多,这里就不再介绍了。 因公司项目测试需要,要使用rsa公钥加密后的数据请求服务器,服务器使用私钥解密,并将响应使用私钥加密后返回,再使用公钥进行解密,对响应结果进行校验。**


以下为核心代码

根据这位大佬的方法增加了128位的分段,以便用于超长数据的解密
python 实现私钥加密公钥解密

import rsa
import base64

 
class DecryptByPublicKey:
    """
        先产生模数因子
        然后生成rsa公钥
        再使用rsa公钥去解密传入的加密str
    """
    def __init__(self, encrypt_text, pub_key):
        missing_padding = 4 - len(encrypt_text) % 4
        if missing_padding:
            encrypt_text += '=' * missing_padding
        self._encrypt_text = encrypt_text.replace(" ", "+")
        self._pub_string_key = pub_key
        # 使用公钥字符串求出模数和因子
        self._modulus = None   # 模数
        self._exponent = None  # 因子
        # 使用PublicKey(模数,因子)算出公钥
        self._pub_rsa_key = None
 
    def _gen_modulus_exponent(self, s):
        # 对字符串解码, 解码成功返回 模数和指数
        b_str = base64.b64decode(s)
        if len(b_str) < 162:
            return False
        hex_str = b_str.hex()
        # 找到模数和指数的开头结束位置
        m_start = 29 * 2
        e_start = 159 * 2
        m_len = 128 * 2
        e_len = 3 * 2
        self._modulus = int(hex_str[m_start:m_start + m_len], 16)
        self._exponent = int(hex_str[e_start:e_start + e_len], 16)
 
    def _gen_rsa_pubkey(self):
        # 将pub key string 转换为 pub rsa key
        try:
            rsa_pubkey = rsa.PublicKey(self._modulus, self._exponent)
            # 赋值到_pub_rsa_key
            self._pub_rsa_key = rsa_pubkey.save_pkcs1()
        except Exception as e:
            raise e
 
    def decode(self):
        """
        decrypt msg by public key
        """

        public_key = rsa.PublicKey.load_pkcs1(self._pub_rsa_key)
        b64decoded_encrypt_text = base64.b64decode(self._encrypt_text)
        length = len(b64decoded_encrypt_text)
        length_max = 128
        decryptDataText = []
        data=b''
        if length >= 128 :
            for i in range(0, length, length_max):
                encrypted = rsa.transform.bytes2int(b64decoded_encrypt_text[i:i + length_max])
                decrypted = rsa.core.decrypt_int(encrypted, public_key.e, public_key.n)
                decrypted_bytes = rsa.transform.int2bytes(decrypted)
                data+=decrypted_bytes[decrypted_bytes.find(b'\x00')+1:]

            try:
                decryptDataText.append(data.decode())
            except Exception as e:
                raise e

        else :
                encrypted = rsa.transform.bytes2int(b64decoded_encrypt_text)
                decrypted = rsa.core.decrypt_int(encrypted, public_key.e, public_key.n)
                decrypted_bytes = rsa.transform.int2bytes(decrypted)

                try:
                    decryptDataText.append(decrypted_bytes[decrypted_bytes.find(b'\x00')+1:].decode())
                except Exception as e:
                    raise e

        if decryptDataText :      
            return "".join(decryptDataText)
        else :
            return 'null'
        

    def decrypt(self):
        """
        先产生模数因子
        然后生成rsa公钥
        再使用rsa公钥去解密
        """
        self._gen_modulus_exponent(self._pub_string_key)
        self._gen_rsa_pubkey()
        ret = self.decode()
        return ret
 
 
if __name__ == "__main__":
    pub_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChGYdKQ7b9Gjp6HZI3u7LjAKeAdoMVOh7ZroHaICi1l2dhMGiOwlZv8SFr6IUPJJIGnkA2cfbv3jECwJmfu1sBNxuoKp32sLmmbDiea7mgBbWJSB1NeDVg5j1479MKJGXNsYDFrgfdIaN3tFOvCTKXM1xkwvEiL8GtMF7UxO+xOQIDAQAB'
    encrypt_text = 'VB/mJnmufqx1ShAGfH5RVQ/LJhOxKYL2rlyuJUFfmDcUorQtuvBbeZlGz18oz9COgHFztowsNH4Yj9sQutawyNOZ1RLHxCRfxGn9a3gwk8ACvEHa7pBEfxWpZwjH0thhTonWq1xMttHDVZ+hIn2UL4yzHxI2IwGZIyn5phWS6jsu00RnCWuEL5Y6MOqP4TRlHl68joNwP/5EF0LfkSUdvqoQzXhAYlbX3XsJnA2Gg8uoXLcUlY5vOKrEDkFwmzG4DhTJRDMsWejVj8fcIQLeUjH1uJy4yuYk7BgbbiDbkxD/+wllo5XMOzf5oIRAy6k5YlmBPMKhfTa+zECcD/zT9GKtxpoEJs4PvPR4XR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saQu16bOqxh39DsKbCjsmKwcCyTVHraxo8whSK/J2dGG6DzBSwvBFpKxxYVBntP8kawnYQUv36ZpkVJAX9I9BpJ9oYmzloPq7wjJnRnUPZaHFk4sg4A9Sya8MHnbOJVOMol5H5Q0p1VxBAb7bEgoqZijhhvFJzP18='  # encrypt_text 是被私钥加密后的密文
    result = DecryptByPublicKey(encrypt_text,pub_key).decrypt()
    print(result)
RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,用于在计算机通信中提供数据保密。Python中,你可以使用`cryptography`库来实现RSA公钥解密。以下是一个简单的步骤概述: 1. 安装`cryptography`库(如果未安装): ```bash pip install cryptography ``` 2. 导入必要的模块和功能: ```python from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.backends import default_backend ``` 3. 生成RSA密钥对(包括公钥和私钥): ```python private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) public_key = private_key.public_key() ``` 4. 获取公钥(用于解密): ```python public_numbers = public_key.public_numbers() n = public_numbers.n e = public_numbers.e ``` 5. 接收加密后的消息(通常是以Base64或hex编码的形式): ```python encrypted_message = b"your_base64_or_hex_encoded_ciphertext" ``` 6. 解密消息: ```python def encrypt_rsa(message, public_key, e): ciphertext = pow(int.from_bytes(message, byteorder="big"), e, n).to_bytes((n.bit_length() + 7) // 8, byteorder="big") return ciphertext decrypted_message = public_key.decrypt(encrypted_message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) ``` 7. 最后,解密后的消息将是一个字节串,可以转换为字符串: ```python decrypted_message_str = decrypted_message.decode("utf-8") ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值