python实现rsa的公钥加密、私钥解密及私钥加密、公钥解密

rsa包中现成的公钥加密、私钥解密代码

import rsa
def rsa_encrypt(d_str):
    # 生成公钥和私钥
    pubkey, privkey = rsa.newkeys(1024)
    # 将字符串进行编码
    content = d_str.encode('utf-8')
    # 公钥加密
    crypto = rsa.encrypt(content, pubkey)
    print ('加密后', crypto)
    return crypto, privkey

def rsa_decrypt(crypto, privkey):
    # 解密
    content = rsa.decrypt(crypto, privkey)
    # 解码
    content = content.decode('utf-8')
    print ('解密结果', content)
if __name__ == '__main__':
    a = rsa_encrypt('hello word')
    rsa_decrypt(*a)

但没有现成的私钥加密、公钥解密的实现

通过阅读源码,整理出一份简易的实现方式

import rsa
from rsa import common, transform, core
import os


def _pad_for_encryption(message, target_length):

    max_msglength = target_length - 11
    msglength = len(message)

    if msglength > max_msglength:
      
Python中,可以使用`cryptography`库来实现RSA算法的加解密操作。RSA是一种非对称加密技术,它包含两个关键:公钥私钥公钥用于加密数据,而私钥用于解密。以下是基本步骤: 1. 安装库:首先需要安装`cryptography`库,你可以通过pip命令安装: ``` pip install cryptography ``` 2. 导入库并生成密钥对:使用`cryptography.hazmat.primitives.asymmetric.rsa`模块创建RSA对象,并生成一对密钥: ```python from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa key_pair = rsa.generate_private_key( public_exponent=65537, key_size=2048 ) private_key = key_pair.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) public_key = key_pair.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) ``` 3. 加密过程:使用接收者的公钥(即发送者的私钥加密消息: ```python plaintext = b"Hello, world!" encrypted_text = public_key.decode("utf-8") cipher = serialization.load_pem_public_key(encrypted_text.encode(), backend=default_backend()) ciphertext = cipher.encrypt(plaintext) ``` 4. 解密过程:使用自己的私钥解密接收到的密文: ```python decrypted_text = private_key.decode("utf-8") decryption_key = serialization.load_pem_private_key(decrypted_text.encode(), password=None, backend=default_backend()) decrypted_message = decryption_key.decrypt(ciphertext).decode() ``` 请注意,在实际应用中,你需要妥善保管私钥,避免泄露,因为一旦私钥丢失,任何人都可以读取你的信息。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值