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

python简单的加密解密

root3年前 (2021-02-04)python502

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

分享给朋友:

相关文章

python os 模块文件常用操作

123456import os #回去当前文件路径os.path.realpath(__file__)#获取文件是否存在os.path.exists(filepath)#获取文件大小os.path.getsize(fil...

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...

pandas用法总结

首先导入pandas库,一般都会用到numpy库,所以我们先导入备用import numpy as np import pandas as pd导入CSV或者xlsx文件df&n...

python 装饰器 之打印函数执行时间

在实际开发中 遇见很多需要排查函数执行时间定位性能瓶颈点用装饰器获取函数执行的时间还是比较方便的import inspect import time def timethis(func):  ...

python进行远程ssh连接的pexpect模块

from pexpect import pxssh s=pxssh.pxssh() s.login(host, user, password) s.sendline(cmd) s.p...