Python中RSA的PKCS#1、PKCS#8,MD5加密
一、Python-RSA
RSA库只支持PKCS#1的密钥格式 需要安装第三方库rsapip install rsa
python-rsa官方地址:https://stuvel.eu/python-rsa-doc/
RSA非对称加密: 1、公钥进行加密(公开)rsa.encrypt(message, pub_key)2、私钥进行解密(保密)
rsa.decrypt(crypto, priv_key)例:
import base64
import rsa
class RsaDemo:
def __init__(self):
self.pubkey, self.privkey = rsa.newkeys(512) #生成公钥、私钥对象,密钥位数512
def encrypt_str(self,test_str):
"""
加密
:param test_str: 需要进行加密的字符串
:return: 返回加密后的str
"""
new_str = test_str.encode("utf8") #字符串转为utf8字节码
crypt_str = rsa.encrypt(message=new_str, pub_key=self.pubkey) #加密,之后数据类型为byte
b64_str = base64.b64encode(crypt_str) # base64编码,格式为byte
result = b64_str.decode() # 转为字符串
print(type(result),result)
return result
def decrypt_str(self,crypt_str:str):
"""
解密
:param crypt_str:
:return:
"""
byte_str = crypt_str.encode() #字符串编码为byte
test_str = base64.b64decode(byte_str) #base64解码
byte_result = rsa.decrypt(crypto=test_str,priv_key=self.privkey) #解密
str_result = byte_result.decode() #解码为字符串
print(type(str_result), str_result)
if __name__ == '__main__':
test = RsaDemo()
phone = "15200000001"
crypt_phone = test.encrypt_str(phone)
decrypt_phone = test.decrypt_str(crypt_phone)
二、pyhton的Crypto
支持PKCS#1、PKCS#8等密钥格式 1、windows下的安装pip install pycryptodome
2、使用
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as PKCS1_cipher
#公钥
public_key = """-----BEGIN PUBLIC KEY-----
********************************
-----END PUBLIC KEY-----"""
#私钥
private_key ="""-----BEGIN RSA PRIVATE KEY-----
********************************
-----END RSA PRIVATE KEY-----"""
message = "qq123456"
#加密
pub_key = RSA.importKey(public_key)
cipher = PKCS1_cipher.new(pub_key)
rsa_text = base64.b64encode(cipher.encrypt(message.encode("utf-8)"))) #加密并转为b64编码
text = rsa_text.decode("utf8") #解码为字符串
print("加密后的内容:",text)
# 解密
pri_Key = RSA.importKey(private_key)
cipher = PKCS1_cipher.new(pri_Key)
back_text = cipher.decrypt(base64.b64decode(text.encode("utf8")), 0)
print("解密后的内容:",back_text.decode("utf-8"))
三、MD5
import hashlib
work_no = "00865"
work_no = work_no.encode("utf8") #转为byte
#md5_no = hashlib.md5(work_no) #编码为md5对象
#md5_no = md5_no.hexdigest() #转为16进制字符串
result = hashlib.md5(work_no).hexdigest()
print(result)
备注:关于PKCS#8和PKCS#1证书格式之间,可进行转换 参考资料:https://www.jianshu.com/p/ada97fd7f8f6 https://wenku.baidu.com/view/f3b082072c60ddccda38376baf1ffc4fff47e257.html https://blog.csdn.net/weixin_42856871/article/details/116268046 https://blog.csdn.net/weixin_43824829/article/details/124045403 https://blog.csdn.net/viviliving/article/details/113575418