python RSA加密解密

申明: 文章为转载
原文地址原文

RSA是一种非对称加密算法

非对称加密需要公钥(publickey)和私钥(privatekey)

消息传递前需要先生成公钥和私钥,发送方将待发送消息用公钥加密,发送给接收方。接收方收到消息后,用私钥解密。在这个过程中,公钥负责加密,私钥负责解密,消息在传输过程中即使被截获,攻击者由于没有私钥,无法破解截获的消息。

非对称加密算法的加解密速度低于对称加密算法,但是安全性更高。

非对称加密算法:RSA、DSA、ECC等算法

RSA加密解密过程:

import rsa

# rsa加密
def rsaEncrypt(str):
    # 生成公钥、私钥
    (pubkey, privkey) = rsa.newkeys(512)
    print("公钥:\n%s\n私钥:\n%s" % (pubkey, privkey))
    # 明文编码格式
    content = str.encode("utf-8")
    # 公钥加密
    crypto = rsa.encrypt(content, pubkey)
    return (crypto, privkey)

# rsa解密
def rsaDecrypt(str, pk):
    # 私钥解密
    content = rsa.decrypt(str, pk)
    con = content.decode("utf-8")
    return con

if __name__ == "__main__":
    str, pk = rsaEncrypt("password")
    print("加密后密文:\n%s" % str)

    content = rsaDecrypt(str, pk)
    print("解密后明文:\n%s" % content)

使用 Crypto.PublicKey.RSA 生成公钥、私钥

import Crypto.PublicKey.RSA
import Crypto.Random

x = Crypto.PublicKey.RSA.generate(2048)
a = x.exportKey("PEM")  # 生成私钥
b = x.publickey().exportKey()   # 生成公钥
with open("a.pem", "wb") as x:
    x.write(a)
with open("b.pem", "wb") as x:
    x.write(b)

y = Crypto.PublicKey.RSA.generate(2048, Crypto.Random.new().read)   # 使用 Crypto.Random.new().read 伪随机数生成器
c = y.exportKey()   # 生成私钥
d = y.publickey().exportKey()   #生成公钥
with open("c.pem", "wb") as x:
    x.write(c)
with open("d.pem", "wb") as x:
    x.write(d)

使用 Crypto.PublicKey.RSA.importKey(private_key) 生成公钥和证书

import Crypto.PublicKey.RSA

with open("a.pem", "rb") as x:
    xx = Crypto.PublicKey.RSA.importKey(x.read())

b = xx.publickey().exportKey()   # 生成公钥
with open("b.pem", "wb") as x:
    x.write(b)

a = xx.exportKey("DER")   # 生成 DER 格式的证书
with open("a.der", "wb") as x:
    x.write(a)

使用 RSA 生成公钥、私钥

import rsa

f, e = rsa.newkeys(1024)  # 生成公钥、私钥

e = e.save_pkcs1()  # 保存为 .pem 格式
with open("private.pem", "wb") as x:  # 保存私钥
    x.write(e)
f = f.save_pkcs1()  # 保存为 .pem 格式
with open("public.pem", "wb") as x:  # 保存公钥
    x.write(f)

RSA非对称加密

import rsa
import base64

password = 'password'
print('password:%s' % password)

y = base64.b64encode(password.encode())
print('y:%s' % y)

with open("public.pem", "rb") as x:
    f = x.read()
    f = rsa.PublicKey.load_pkcs1(f)  # load 公钥

with open("private.pem", "rb") as x:
    e = x.read()
    e = rsa.PrivateKey.load_pkcs1(e)  # load 私钥

cipher_text = rsa.encrypt(y, f)  # 使用公钥加密
print('cipher_text:%s' % cipher_text)

msg = base64.b64encode(cipher_text).decode()
print('msg:%s' % msg)

crypto = base64.b64decode(msg)
print('crypto:%s' % crypto)

text = rsa.decrypt(crypto, e).decode()  # 使用私钥解密
print('text:%s' % text)

password = base64.b64decode(text).decode()
print('password:%s' % password)

参数说明

Image text

原文链接: python RSA加密解密 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-666.html )

发表评论

0则评论给“python RSA加密解密”