python rsa密钥对的加密/解密、加签/解签...
经常在报文的传输过程中为了保证传输的安全性需要对其进行加密/解密,或是对报文进行加签操作,在收到的报文中再验证签名。
在这里主要研究的是rsa密钥对的使用方式的解读,python提供了一个rsa的非标准库供我们使用。
使用pip的方式进行安装即可。
pip install rsa
准备好之后,进入正式的表演环节,将rsa导入到导入到代码块中。
import rsa
1. 生成rsa密钥对
这里选择生成.pem格式文件的秘钥。
(public_key,private_key) = rsa.newkeys(1024)
生成公钥/私钥以后将其保存成.pem文件以便后面使用的时候调用。
# 保存公钥文件 public_txt = public_key.save_pkcs1() public_file = open(public_key.pem,w+) public_file.write(public_txt) public_file.close() # 保存私钥文件 private_txt = public_key.save_pkcs1() private_file = open(private_key.pem, w+) private_file.write(private_txt) private_file.close()
2. 字符串加解密
使用在第一步中生成的公钥和私钥对字符串完成加密和解密操作。
# 定义一个字符串 str_ = www.baidu.com # 加载公钥文件,获取公钥 with open(public_key.pem) as public_file: public_txt = public_file.read() public_key = rsa.PublicKey.load_pkcs1(public_txt) # 加载私钥文件,获取私钥 with open(private_key.pem) as private_file: private_txt = private_file.read() private_key = rsa.PrivateKey.load_pkcs1(private_txt) # 使用公钥key对字符串进行加密 crypt_str = rsa.encrypt(str_, public_key) # 使用私钥key对字符串进行解密 result = rsa.decrypt(crypt_str, private_key)
3. 字符串加解签
使用从公钥或者私钥文件中加载出来的公钥和私钥可以对字符串完成加签或者解签验证的处理。
# 对字符串str_加上签名 signature = rsa.sign(str_, private_key, SHA-1) # 验证签名是否正确,若是签名正确再做其他处理 rsa.verify(str_, signature, public_key)
若是签名验证通过的情况下,再对传输过来的数据进行处理。若是签名验证失败则很可能是非法数据就要小心了。
上一篇:
JS实现多线程数据分片下载