Python中RSA的PKCS#1、PKCS#8,MD5加密
一、Python-RSA
RSA库只支持PKCS#1的密钥格式
需要安装第三方库rsa
1 | pip install rsa |
python-rsa官方地址:https://stuvel.eu/python-rsa-doc/
RSA非对称加密:
1、公钥进行加密(公开)
1 | rsa.encrypt(message, pub_key) |
2、私钥进行解密(保密)
1 | rsa.decrypt(crypto, priv_key) |
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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下的安装
1 | pip install pycryptodome |
2、使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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
1 2 3 4 5 6 7 8 9 | 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证书格式之间,可进行转换
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构