超简易python实现RSA加解密

What:

RSA加密算法是一种非对称加密算法。在公开密钥加密和电子商业中RSA被广泛使用。所谓的公开密钥密码体制就是使用不同的加密密钥与解密密钥,是一种“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制。

img

环境

Windows10、python3.8、pycharm

步骤

熟悉RSA加解密流程、和概念

导入RSA库(导入前先安装pip install rsa)

熟悉rsa库

__all__ = ["newkeys", "encrypt", "decrypt", "sign", "verify", 'PublicKey',
           'PrivateKey', 'DecryptionError', 'VerificationError',
           'compute_hash', 'sign_hash']

输入明文

加/解密(一般推荐使用1024位)

密文/明文

检验

代码

import rsa

def rsa_encrypt(plaintext):
    '''
    输入明文、生成公钥、私钥
    公钥对明文进行加密、字符串加密
    :return:加密结果及私钥
    '''
    pub_key, priv_key = rsa.newkeys(1024)
    print(pub_key)
    print(priv_key)
    plaintext = plaintext.encode()     #the message to encrypt. Must be a byte string no longer than``k-11`` bytes
    ciphertext = rsa.encrypt(plaintext, pub_key)
    print('加密后:', ciphertext)
    return ciphertext, priv_key

def rsa_decrypt(ciphertext, priv_key):
    '''
    传参私钥和加密的明文
    :param ciphertext:
    :param priv_key:
    :return:解密结果
    '''
    plaintext = rsa.decrypt(ciphertext, priv_key)
    plaintext = plaintext.decode()
    print('解密后:', plaintext)

if __name__ == '__main__':
    plaintext = input("输入明文:\n").strip()
    ciphertext, priv_key = rsa_encrypt(plaintext)
    rsa_decrypt(ciphertext, priv_key)

  • 5
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值