Python中RSA的PKCS#1、PKCS#8,MD5加密
阅读原文时间:2023年07月08日阅读:1

一、Python-RSA

RSA库只支持PKCS#1的密钥格式

需要安装第三方库rsa

pip 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 = "13300000001"
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 = "123456"

#加密
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
no = "0001"
no = no.encode("utf8") #转为byte

#md5_no = hashlib.md5(no) #编码为md5对象
#md5_no = md5_no.hexdigest() #转为16进制字符串

result = hashlib.md5(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

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章