python进行RSA加密
python进行RSA加密

python进行RSA加密

RSA加密是一种非对称加密算法。被公钥加密的数据只能用私钥解密,被私钥加密的数据只能被公钥解密。公钥和私钥只是对两种密钥的使用场景以及是否对外公开来区分的,本质上区别不大。

这里我们采用pycryptodome库来进行加密

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto import Random


random_generator = Random.new().read
#生成RSA密钥对
new_rsa = RSA.generate(1024, random_generator)
#导出私钥用户可以保存下来多次使用
private_pem = new_rsa.exportKey()
print('Private key:')
print(private_pem)

#导出公钥
public_pem = new_rsa.publickey().exportKey()
print('Public key:')
print(public_pem)


def encrypt(pub_key, msg):
    rsa = RSA.importKey(pub_key)
    cipher = PKCS1_OAEP.new(rsa)
    return cipher.encrypt(msg)


def decrypt(private_key, msg):
    rsa = RSA.importKey(private_key)
    cipher = PKCS1_OAEP.new(rsa)
    return cipher.decrypt(msg)


plaintext = '红红火火恍恍惚惚'
print('原文:', plaintext)
message = encrypt(public_pem, plaintext.encode())
print('加密后的密文:', message)
text = decrypt(private_pem, message)
print('解密后的密文:', text.decode())

执行结果

Private key:
b'-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC1VXQ1fPm+ORtKUckPHbrOPqQqy/SFeciqI1uiKJFq0Nw8jpIY\nbU56IV486ByiExKy1E5j5vTR2MSwGJCF2b5iL+7OfN+WJ6DN/3Fh055FUmvt1dy2\nFb85M8kYE7tzFNBC+f5QhBDdPLKLZNeEOvHk/xnIcE8uFbWQ7Bhf0EVU7wIDAQAB\nAoGAFHU7eEy3w7wfSz9hOXkyBKfGOg/VmqN2k1S24gYaqzGSJKuJvwNsqam5vzxe\np/MSlntjtrCtU+l//fAKNMJapfpBtcbK5gCj5vC/HLkRZvWUbu36PMvzjjgTzRoI\n0rxNsNvincGSCjTqX278fpMTE2PXG2GsJPqLEEZxzdV09i0CQQDUTC6Ob+n1xer/\neAJchnjAx0Y3V9QamnyUueWKgHW3RwRPxk0IpuO5n/sH0J+aAFEErcblOzyVLJD8\nLbnCGVU9AkEA2qmE+J75sTWKJqcHInIi8YlalctATOCUlhRj93rX4wp4nzcV3c8v\nzB6VXxEBvSUguDvHiJcCzqxMgy3Nf+8tmwJBAMa+fwM3gBZm76W0Crnl5ZvLsk9T\nOKyjHaf6FArCUfF/WWj5YtqLqjr3qwFY7GE2lKJFsSKefwvECgMbJ4CvSJ0CQEPH\nxoM27FmFKiTfI7QGw1Qx6pWCYpUyDH0VJwPA3YjwZwGblriiD8PrOwwz/mD+UE0r\noqdxgBpGiJUlLo1Yu78CQQDPMMQuMqLThQQM5FmZLv5AJo6IjuJkostqUrWEV8CK\ngIhfetMeWBd8xGijanqAEG2qkX66c7RS3obh36W2GvAF\n-----END RSA PRIVATE KEY-----'
Public key:
b'-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC1VXQ1fPm+ORtKUckPHbrOPqQq\ny/SFeciqI1uiKJFq0Nw8jpIYbU56IV486ByiExKy1E5j5vTR2MSwGJCF2b5iL+7O\nfN+WJ6DN/3Fh055FUmvt1dy2Fb85M8kYE7tzFNBC+f5QhBDdPLKLZNeEOvHk/xnI\ncE8uFbWQ7Bhf0EVU7wIDAQAB\n-----END PUBLIC KEY-----'
原文: 红红火火恍恍惚惚
加密后的密文: b'\xa4\xaf,W\x0c\xd7\x08\x88>%4^\x0b\\\x07\x19\xbf5E\xff\xc4\x91:5M\xbf\xbe\xea\xa1=ia\xc2\xcchwo\x04\xe4\x06\xbf\x9d\x91\x03M\x8c\x08)\xf4e{\xbc8\xef\xb4\xf3\xb9\xce\xe3\xe1?!\x80.\xa9\xb0\x11\x00\r\xc8NL\xff\x98\x97\xc2\xef%\x91\xc7\x1d\xbc\xb9\xadOE#Rp\xad\[email protected]\x02\xd5\xde\x16\x05\x80\xf6\xaa\xa0#4\xd5X\xb5\xb5\x08\xa8\\\xb4z\x92\x03\xe7G\x1c\x93l\xac\x06;q\x0fGe'
解密后的密文: 红红火火恍恍惚惚

发表评论