python rsa加解密
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | python rsa加解密代码: 只适用python3: import base64 from Crypto.Cipher import PKCS1_v1_5 from Crypto import Random from Crypto.PublicKey import RSA # ------------------------生成密钥对------------------------ def create_rsa_pair(is_save = False ): ''' 创建rsa公钥私钥对 :param is_save: default:False :return: public_key, private_key ''' f = RSA.generate( 2048 ) private_key = f.exportKey( "PEM" ) # 生成私钥 public_key = f.publickey().exportKey() # 生成公钥 if is_save: with open ( "crypto_private_key.pem" , "wb" ) as f: f.write(private_key) with open ( "crypto_public_key.pem" , "wb" ) as f: f.write(public_key) return public_key, private_key def read_public_key(file_path = "crypto_public_key.pem" ) - > bytes: with open (file_path, "rb" ) as x: b = x.read() return b def read_private_key(file_path = "crypto_private_key.pem" ) - > bytes: with open (file_path, "rb" ) as x: b = x.read() return b # ------------------------加密------------------------ def encryption(text: str , public_key: bytes): # 字符串指定编码(转为bytes) text = text.encode( 'utf-8' ) # 构建公钥对象 cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key)) # 加密(bytes) text_encrypted = cipher_public.encrypt(text) # base64编码,并转为字符串 text_encrypted_base64 = base64.b64encode(text_encrypted).decode() return text_encrypted_base64 # ------------------------解密------------------------ def decryption(text_encrypted_base64: str , private_key: bytes): # 字符串指定编码(转为bytes) text_encrypted_base64 = text_encrypted_base64.encode( 'utf-8' ) # base64解码 text_encrypted = base64.b64decode(text_encrypted_base64) # 构建私钥对象 cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key)) # 解密(bytes) text_decrypted = cipher_private.decrypt(text_encrypted, Random.new().read) # 解码为字符串 text_decrypted = text_decrypted.decode() return text_decrypted if __name__ = = '__main__' : # 生成密钥对 # create_rsa_pair(is_save=True) # public_key = read_public_key() # private_key = read_private_key() public_key, private_key = create_rsa_pair(is_save = False ) # 加密 text = '123456' text_encrypted_base64 = encryption(text, public_key) print ( '密文:' , text_encrypted_base64) # 解密 text_decrypted = decryption(text_encrypted_base64, private_key) print ( '明文:' , text_decrypted) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」