最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

python rsa加解密

2022-11-17 15:50 作者:限量版范兒  | 我要投稿

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): ? ?''' ? ?創(chuàng)建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): ? ?# 字符串指定編碼(轉(zhuǎn)為bytes) ? ?text = text.encode('utf-8') ? ?# 構(gòu)建公鑰對象 ? ?cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key)) ? ?# 加密(bytes) ? ?text_encrypted = cipher_public.encrypt(text) ? ?# base64編碼,并轉(zhuǎn)為字符串 ? ?text_encrypted_base64 = base64.b64encode(text_encrypted).decode() ? ?return text_encrypted_base64 # ------------------------解密------------------------ def decryption(text_encrypted_base64: str, private_key: bytes): ? ?# 字符串指定編碼(轉(zhuǎn)為bytes) ? ?text_encrypted_base64 = text_encrypted_base64.encode('utf-8') ? ?# base64解碼 ? ?text_encrypted = base64.b64decode(text_encrypted_base64) ? ?# 構(gòu)建私鑰對象 ? ?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)

鏈接:https://www.dianjilingqu.com/613925.html

python rsa加解密的評論 (共 條)

分享到微博請遵守國家法律
乌什县| 通河县| 民权县| 鱼台县| 观塘区| 宣化县| 金乡县| 彩票| 延安市| 岚皋县| 华阴市| 云龙县| 壤塘县| 恩施市| 乐至县| 嘉鱼县| 建平县| 高清| 泸州市| 曲阜市| 思南县| 鱼台县| 什邡市| 奉新县| 临邑县| 宜兰市| 新野县| 探索| 博爱县| 盈江县| 土默特右旗| 武义县| 桃江县| 盐源县| 田林县| 清远市| 泸州市| 鹿泉市| 隆子县| 岗巴县| 三门县|