[Python] RSA

来源:互联网 发布:h5单页商品详情源码 编辑:程序博客网 时间:2024/06/10 02:16

首先需要安装rsa库,方法是:pip install rsa

具体程序如下:

# -*- coding: utf-8 -*  中文注释import rsa# 先生成一对密钥,然后保存.pem格式文件,当然也可以直接使用(pubkey, privkey) = rsa.newkeys(1024)pub = pubkey.save_pkcs1()pubfile = open('public.pem','w+')pubfile.write(pub)pubfile.close()pri = privkey.save_pkcs1()prifile = open('private.pem','w+')prifile.write(pri)prifile.close()# load公钥和密钥message = 'hello'with open('public.pem') as publickfile:    p = publickfile.read()    pubkey = rsa.PublicKey.load_pkcs1(p)with open('private.pem') as privatefile:    p = privatefile.read()    privkey = rsa.PrivateKey.load_pkcs1(p)# 用公钥加密、再用私钥解密crypto = rsa.encrypt(message, pubkey)message = rsa.decrypt(crypto, privkey)print message# sign 用私钥签名认证、再用公钥验证签名signature = rsa.sign(message, privkey, 'SHA-1')rsa.verify('hello', signature, pubkey)

结束

0 0