Super simple python achieve RSA encryption and decryption

What:

RSA encryption algorithm is an asymmetric encryption algorithm. In public-key encryption and electronic commerce RSA is widely used. The so-called public key cryptography is the use of a different encryption key and decryption key, a "is derived from the known encryption key decryption key is computationally infeasible" cryptosystems.

img

surroundings

Windows10、python3.8、pycharm

step

Familiar with the RSA encryption and decryption processes, and concepts

RSA import library (before importing install pip install rsa)

Familiar rsa library

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

Input plaintext

Encryption / decryption (generally recommended 1024)

The ciphertext / plaintext

test

Code

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)

Published 40 original articles · won praise 2 · Views 2385

Guess you like

Origin blog.csdn.net/qq_42404383/article/details/105136866