RSA加密是一种非对称加密算法。被公钥加密的数据只能用私钥解密,被私钥加密的数据只能被公钥解密。公钥和私钥只是对两种密钥的使用场景以及是否对外公开来区分的,本质上区别不大。
这里我们采用pycryptodome库来进行加密
代码语言:javascript复制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())
执行结果
代码语言:javascript复制Private key:
b'-----BEGIN RSA PRIVATE KEY-----nMIICXQIBAAKBgQC1VXQ1fPm ORtKUckPHbrOPqQqy/SFeciqI1uiKJFq0Nw8jpIYnbU56IV486ByiExKy1E5j5vTR2MSwGJCF2b5iL 7OfN WJ6DN/3Fh055FUmvt1dy2nFb85M8kYE7tzFNBC f5QhBDdPLKLZNeEOvHk/xnIcE8uFbWQ7Bhf0EVU7wIDAQABnAoGAFHU7eEy3w7wfSz9hOXkyBKfGOg/VmqN2k1S24gYaqzGSJKuJvwNsqam5vzxenp/MSlntjtrCtU l//fAKNMJapfpBtcbK5gCj5vC/HLkRZvWUbu36PMvzjjgTzRoIn0rxNsNvincGSCjTqX278fpMTE2PXG2GsJPqLEEZxzdV09i0CQQDUTC6Ob n1xer/neAJchnjAx0Y3V9QamnyUueWKgHW3RwRPxk0IpuO5n/sH0J aAFEErcblOzyVLJD8nLbnCGVU9AkEA2qmE J75sTWKJqcHInIi8YlalctATOCUlhRj93rX4wp4nzcV3c8vnzB6VXxEBvSUguDvHiJcCzqxMgy3Nf 8tmwJBAMa fwM3gBZm76W0Crnl5ZvLsk9TnOKyjHaf6FArCUfF/WWj5YtqLqjr3qwFY7GE2lKJFsSKefwvECgMbJ4CvSJ0CQEPHnxoM27FmFKiTfI7QGw1Qx6pWCYpUyDH0VJwPA3YjwZwGblriiD8PrOwwz/mD UE0rnoqdxgBpGiJUlLo1Yu78CQQDPMMQuMqLThQQM5FmZLv5AJo6IjuJkostqUrWEV8CKngIhfetMeWBd8xGijanqAEG2qkX66c7RS3obh36W2GvAFn-----END RSA PRIVATE KEY-----'
Public key:
b'-----BEGIN PUBLIC KEY-----nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC1VXQ1fPm ORtKUckPHbrOPqQqny/SFeciqI1uiKJFq0Nw8jpIYbU56IV486ByiExKy1E5j5vTR2MSwGJCF2b5iL 7OnfN WJ6DN/3Fh055FUmvt1dy2Fb85M8kYE7tzFNBC f5QhBDdPLKLZNeEOvHk/xnIncE8uFbWQ7Bhf0EVU7wIDAQABn-----END PUBLIC KEY-----'
原文: 红红火火恍恍惚惚
加密后的密文: b'xa4xaf,Wx0cxd7x08x88>%4^x0b\x07x19xbf5Exffxc4x91:5Mxbfxbexeaxa1=iaxc2xcchwox04xe4x06xbfx9dx91x03Mx8cx08)xf4e{xbc8xefxb4xf3xb9xcexe3xe1?!x80.xa9xb0x11x00rxc8NLxffx98x97xc2xef%x91xc7x1dxbcxb9xadOE#Rpxadr@Ssx02xd5xdex16x05x80xf6xaaxa0#4xd5Xxb5xb5x08xa8\xb4zx92x03xe7Gx1cx93lxacx06;qx0fGe'
解密后的密文: 红红火火恍恍惚惚