超简易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)

发布了40 篇原创文章 · 获赞 2 · 访问量 2385

猜你喜欢

转载自blog.csdn.net/qq_42404383/article/details/105136866