python RSA模块加密和解密

 使用RSA加密和解密,将保密内容加密后写入文件,使用时读取加密文件并用私钥对加密内容进行解密得到加密前的数据。

# coding=utf-8
import rsa

def create_keys():  # 生成公钥和私钥
    (pubkey, privkey) = rsa.newkeys(1024)
    pub = pubkey.save_pkcs1()
    with open('public.pem','wb+')as f:
        f.write(pub)
 
    pri = privkey.save_pkcs1()
    with open('private.pem','wb+')as f:
        f.write(pri)

def encrypt():  # 用公钥加密
    with open('public.pem', 'rb') as publickfile:
        p = publickfile.read()
    pubkey = rsa.PublicKey.load_pkcs1(p)
    original_text = 'zhangjunxue/123456'.encode('utf8')
    crypt_text = rsa.encrypt(original_text, pubkey)
    print(crypt_text)
    # return crypt_text  # 加密后的密文
    f = open('passwd.data', 'wb')
    f.write(crypt_text)
    f.close()

def decrypt():  # 用私钥解密
    with open('private.pem', 'rb') as privatefile:
        p = privatefile.read()
    privkey = rsa.PrivateKey.load_pkcs1(p)
    f = open('passwd.data', 'rb')
    crypt_text = f.read()
    lase_text = rsa.decrypt(crypt_text, privkey).decode()  # 注意,这里如果结果是bytes类型,就需要进行decode()转化为str
 
    print(lase_text)
    f.close()


if __name__ == "__main__":
    encrypt()
    decrypt()

 

你可能感兴趣的:(python,RSA加密和解密)