Python RSA 算法使用

RSA加密实现

基于本文你可以:

  • 基于python使用RSA算法加密数据

算法百科

(https://baike.baidu.com/item/RSA算法/263310?fromtitle=RSA&fromid=210678 "RSA算法百度百科")

创始人
RSA算法的三位爸爸们

Python代码实现

公钥密钥为随机生成

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDeOF64E9PkZ7XR4xEz4BZs4z0X
Piy2Z/znMUKn1te/MoA8jaGhXCFAtWVaG11N8SnT9S8+Py5M2UUUmBGXwWka+HQw
0poV+oSU2H6GjLTHpmZjd/jDHBGPdLXx52aa7qzT+GkFZn0Foh86eE35BrdnDGfF
iq/nDlIrL1Ad/O7hiQIDAQAB
-----END PUBLIC KEY-----"""

sk = """-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAN44XrgT0+RntdHj
ETPgFmzjPRc+LLZn/OcxQqfW178ygDyNoaFcIUC1ZVobXU3xKdP1Lz4/LkzZRRSY
EZfBaRr4dDDSmhX6hJTYfoaMtMemZmN3+MMcEY90tfHnZprurNP4aQVmfQWiHzp4
TfkGt2cMZ8WKr+cOUisvUB387uGJAgMBAAECgYEArPZvMxOrv4HBkUYNo7Ttf383
k5m/L5Ks1D4RRZYBgz4Jdhg/D9snvrfx1TqrWvk0t1eFmAuRPBt4m1jpiJbv+Ky7
VZPl9POJbbHYzd5UDmHSxXisb2pvjwlPKE1b88SkBD5Yzj6u8OpPLHxJC4wUjwcA
zkce3q/yrpyULsPn3gECQQDz2ZhDWCbFSWAYkEC8zKCEYyXmxXsPbVT2acC7p1v4
A4t4lbfrP5B9xcJtIEVH2r5HviGVDpdotoAzuqRGV6opAkEA6Urg6XRgmexMDMDb
B7wBZ0ixFrI42T70jzq/0VH5jY/0bO4Wz6MoMK9QQjw08Hm8kus8zApAYt0RWzmO
wDkoYQJASsm9zUnH+lIayu3TLRSFVpUiFrkSmRSrLjgZCHS33EUaDY29rsT8B9cT
Xmy7UuJf4ZkKq7Ch91eh0ju4DmrsoQJAT0OUtV1IMSQbFr4z7SXQqEIHgTmenRmJ
yFxirgEXNCT0HEqsz3GVBy2ZrFd+eTIzgwuQBZd6Ft0bt44P1XnWIQJAUvwYE0Lu
VIKkaNtlUuzmXPX5QcNptuz2kJ2CIp+4s/bCWHqAhjV6IG5oEmElv4EC0ZZlcSkz
VHs1wziCq3Vjfw==
-----END PRIVATE KEY-----
"""

key = RSA.importKey(pk)

cipher = PKCS1_cipher.new(key)

text = '原文本'
encrypted_text = base64.b64encode(cipher.encrypt(text.encode('utf-8')))
rsa_text = encrypted_text.decode('utf-8'))
print("加密文本", rsa_text))

Note

  • PK 和 SK 需要保留前缀和后缀
  • 每行64位,以换行符分割
posted @ 2021-08-31 11:13  dmyHero  阅读(516)  评论(0编辑  收藏  举报