当前位置:首页 > python > 正文内容

python简单的加密解密

root5年前 (2021-02-04)python1397

rsa 是非对称加密

公钥加密,私钥解密

pip install rsa

import rsa
from binascii import b2a_hex, a2b_hex

class rsacrypt():
    def __init__(self):
        ''''''

    def encrypt(self, text):
        #加密文本
        self.ciphertext = rsa.encrypt(text.encode(),self.pubkey)
        return b2a_hex(self.ciphertext)

    def decrypt(self, text):
        #解密文本
        decrypt_text = rsa.decrypt(a2b_hex(text),self.prikey)
        return decrypt_text

    def create_key(self):
        #获取一对秘钥
        pubkey, prikey = rsa.newkeys(256)
        pub = pubkey.save_pkcs1()
        pri = prikey.save_pkcs1()
        return (pub,pri)

    def load_pub_key(self,pub):
        #导入公钥,为加密准备
        self.pubkey = rsa.PublicKey.load_pkcs1(pub)

    def load_pri_key(self,pri):
        #导入私钥,为解密准备
        self.prikey = rsa.PrivateKey.load_pkcs1(pri)

if __name__ == '__main__':
    my_rsacrypt = rsacrypt()
    pub,pri=my_rsacrypt.create_key()
    print(pub,pri)
    my_rsacrypt.load_pub_key(pub)
    my_rsacrypt.load_pri_key(pri)
    a = my_rsacrypt.encrypt("123")
    print(a)
    b = my_rsacrypt.decrypt(a)
    print(b)

b'5e1ed0b7583e9cdb3f9161fd6e045c29458f703cabb91a848a84e95cab35a113'

b'123'



扫描二维码推送至手机访问。

版权声明:本文由一叶知秋发布,如需转载请注明出处。

本文链接:https://zhiqiu.top/?id=77

分享给朋友:

相关文章

flask 服务添加ssl 证书

flask 服务添加ssl 证书

1、利用openssl生成自用的ssl证书利用openssl 生成证书openssl genrsa -des3 -out server.key 2048不要密码:再执行 一下:openssl rsa -in server.key -out...

python2的pip 不能使用或者使用总是报错

python2的pip 不能使用或者使用总是报错

python2.7   当然可能还有其他情况有的是pip版本升级过高,有的是pip有点问题无法执行pip的命令升级python2的 pip 一定要小心推荐命令:pip install --upgrad...

python 调用linux命令 subprocess.popen

import subprocesscommd = "echo 123"p1 = subprocess.Popen(commd, shell=True, stdout=subprocess.PIPE, stder...

PIL 模块处理图像的几种模式

PIL有九种不同模式: 1,L,P,RGB,RGBA,CMYK,YCbCr,I,F1、表示二值图像不黑就是白L、为灰度图像,每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度在PIL中,从模式“RGB”转换为...

Python 读取图片的几种方式

OpenCV读取图片OpenCV读取的图片,直接就是numpy.ndarray格式,无需转换import cv2  img_cv   = cv2.imread(dirpath)#...